From 650599d860bf07aeb8dcc7a05dbd78122c33c418 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 00:34:01 +0100 Subject: [PATCH 01/95] Rewrite the tests of the notes' pure modules around their rules (#1716) Fields, Markdown outline and slides, checklist, kinds, priorities, conversions and drawings; the dead FIELD_NAME_PATTERN goes with the test that held it to the rule. --- crates/engine/src/closed_enum.rs | 44 ++++ crates/engine/src/notes/checklist.rs | 35 +-- crates/engine/src/notes/convert.rs | 265 ++++++++++++------- crates/engine/src/notes/drawing.rs | 181 ++++++++----- crates/engine/src/notes/kind.rs | 33 +-- crates/engine/src/notes/markdown.rs | 291 +++++++++++++------- crates/engine/src/notes/placeholder.rs | 351 +++++++++++++------------ crates/engine/src/notes/priority.rs | 28 +- docs/architecture.md | 5 - 9 files changed, 753 insertions(+), 480 deletions(-) diff --git a/crates/engine/src/closed_enum.rs b/crates/engine/src/closed_enum.rs index 8cfa4c41a..bd700a220 100644 --- a/crates/engine/src/closed_enum.rs +++ b/crates/engine/src/closed_enum.rs @@ -57,3 +57,47 @@ macro_rules! closed_enum { } pub(crate) use crate::closed_enum; + +#[cfg(test)] +mod tests { + use std::str::FromStr; + + closed_enum! { + enum Shade { + #[default] + Light = "light", + Dark = "dark-ish", + } + } + + #[test] + fn every_variant_is_listed_once_in_declaration_order() { + assert_eq!(Shade::ALL, [Shade::Light, Shade::Dark]); + } + + #[test] + fn one_spelling_serves_display_parsing_and_serde() { + for shade in Shade::ALL { + let spelling = shade.as_str(); + + assert_eq!(shade.to_string(), spelling); + assert_eq!(Shade::from_str(spelling), Ok(shade)); + assert_eq!( + serde_json::to_string(&shade).unwrap(), + format!("\"{spelling}\"") + ); + assert_eq!( + serde_json::from_str::(&format!("\"{spelling}\"")).unwrap(), + shade + ); + } + } + + #[test] + fn a_spelling_it_never_heard_of_is_refused() { + for unknown in ["", "Light", "dark", "dark-ish "] { + assert_eq!(Shade::from_str(unknown), Err(()), "{unknown:?}"); + assert!(serde_json::from_str::(&format!("\"{unknown}\"")).is_err()); + } + } +} diff --git a/crates/engine/src/notes/checklist.rs b/crates/engine/src/notes/checklist.rs index c090be8af..cdce44e02 100644 --- a/crates/engine/src/notes/checklist.rs +++ b/crates/engine/src/notes/checklist.rs @@ -39,48 +39,49 @@ mod tests { fn item(text: &str, done: bool) -> ChecklistItem { ChecklistItem { - text: text.to_string(), + text: text.into(), done, } } #[test] - fn normalizing_trims_and_drops_the_blank_rows() { - let items = normalize_items(&[ - item(" Ship it ", true), - item(" ", false), - item("", true), - ]); + fn an_item_is_kept_trimmed_with_its_state() { + let items = normalize_items(&[item(" Ship it\t", true), item("Write it up", false)]); - assert_eq!(items, [item("Ship it", true)]); + assert_eq!(items, [item("Ship it", true), item("Write it up", false)]); } #[test] - fn two_identical_tasks_are_two_tasks() { - let items = normalize_items(&[item("Call back", false), item("Call back", false)]); + fn a_blank_item_is_dropped() { + let items = normalize_items(&[item("", false), item(" \t ", true), item("kept", false)]); - assert_eq!(items.len(), 2); + assert_eq!(items, [item("kept", false)]); } #[test] - fn normalizing_keeps_the_order_it_was_given() { - let items = normalize_items(&[item("b", false), item("a", false), item("c", false)]); + fn two_identical_items_are_two_items_in_their_order() { + let items = normalize_items(&[item("b", false), item("a", false), item("b", false)]); assert_eq!( - items.iter().map(|i| i.text.as_str()).collect::>(), - ["b", "a", "c"] + items, + [item("b", false), item("a", false), item("b", false)] ); } #[test] - fn markdown_marks_the_ticked_boxes() { + fn an_empty_list_stays_empty() { + assert!(normalize_items(&[]).is_empty()); + } + + #[test] + fn a_list_is_written_as_markdown_tasks_one_a_line() { let markdown = to_markdown(&[item("Ship it", true), item("Write it up", false)]); assert_eq!(markdown, "- [x] Ship it\n- [ ] Write it up"); } #[test] - fn an_empty_list_renders_to_nothing_at_all() { + fn an_empty_list_is_written_as_nothing() { assert_eq!(to_markdown(&[]), ""); } } diff --git a/crates/engine/src/notes/convert.rs b/crates/engine/src/notes/convert.rs index 1979365e7..d84a634ad 100644 --- a/crates/engine/src/notes/convert.rs +++ b/crates/engine/src/notes/convert.rs @@ -122,162 +122,223 @@ pub struct NoteConversion { #[cfg(test)] mod tests { - use std::collections::BTreeMap; + use super::*; + use crate::notes::fixtures; - use chrono::Utc; + const PYTHON: &str = "#!/usr/bin/env python\nprint(1)"; - use super::*; - use crate::notes::model::NoteLifecycle; - use crate::notes::priority::Priority; + fn item(text: &str, done: bool) -> ChecklistItem { + ChecklistItem { + text: text.into(), + done, + } + } - fn note_of(kind: NoteKind, content: &str) -> Note { + fn note(kind: NoteKind, content: &str) -> Note { Note { - id: "note".to_string(), - space_id: "space".to_string(), - folder_id: None, - title: String::new(), - language: Language::default(), - content: content.to_string(), - source: String::new(), - tags: Vec::new(), - pinned: false, - created_at: Utc::now(), - updated_at: Utc::now(), - lifecycle: NoteLifecycle::Permanent, kind, - priority: Priority::None, - items: Vec::new(), - placeholder_values: BTreeMap::new(), + content: content.into(), + ..fixtures::note() } } - fn item(text: &str, done: bool) -> ChecklistItem { - ChecklistItem { - text: text.to_string(), - done, + fn checklist(items: Vec) -> Note { + Note { + kind: NoteKind::Checklist, + content: String::new(), + items, + ..fixtures::note() } } - fn checklist(items: &[ChecklistItem]) -> Note { - let mut note = note_of(NoteKind::Checklist, ""); - note.items = items.to_vec(); - note + fn scene(texts: &[&str]) -> String { + let objects: Vec<_> = texts + .iter() + .map(|text| serde_json::json!({ "type": "textbox", "text": text })) + .collect(); + serde_json::json!({ "scene": { "objects": objects } }).to_string() } #[test] - fn a_sheet_keeps_its_text_both_ways_and_reads_for_no_language() { - let sheet = "prix = 120 €\nprix × 3"; - - let as_calc = convert(¬e_of(NoteKind::Snippet, sheet), NoteKind::Calc); - let back = convert(¬e_of(NoteKind::Calc, sheet), NoteKind::Note); - let lines = convert( - &checklist(&[ChecklistItem { - text: "2 + 2".into(), - done: false, - }]), - NoteKind::Calc, + fn text_kinds_keep_the_text_as_it_is() { + for from in [NoteKind::Snippet, NoteKind::Note, NoteKind::Calc] { + for into in [NoteKind::Snippet, NoteKind::Note, NoteKind::Calc] { + let body = convert(¬e(from, "a\n**b**"), into); + + assert_eq!(body.content, "a\n**b**", "{from} → {into}"); + assert!(body.items.is_empty()); + assert_eq!(body.kind, into); + } + } + } + + #[test] + fn only_a_snippet_reads_its_text_for_a_language() { + for (into, language) in [ + (NoteKind::Snippet, Language::Py), + (NoteKind::Note, Language::Txt), + (NoteKind::Calc, Language::Txt), + (NoteKind::Checklist, Language::Txt), + ] { + assert_eq!( + convert(¬e(NoteKind::Note, PYTHON), into).language, + language, + "{into}" + ); + } + } + + #[test] + fn a_text_becomes_one_item_per_line_that_is_not_blank() { + let body = convert( + ¬e(NoteKind::Note, "- [ ] write\n\n - [x] ship \n plain"), + NoteKind::Checklist, ); + assert_eq!(body.content, ""); assert_eq!( - (as_calc.content.as_str(), as_calc.language), - (sheet, Language::default()) + body.items, + [ + item("write", false), + item("ship", true), + item("plain", false) + ] ); - assert_eq!(back.content, sheet); - assert_eq!(lines.content, "2 + 2"); } - /// Not offered from the menu: what Rust answers stays coherent all the same. #[test] - fn a_drawing_gives_its_words_and_is_made_empty() { - let scene = r#"{"scene":{"objects":[{"text":"API"},{"text":"DB"}]}}"#; + fn a_todo_list_becomes_a_task_list_in_a_note() { + let body = convert( + &checklist(vec![item("write", true), item("ship", false)]), + NoteKind::Note, + ); - let as_note = convert(¬e_of(NoteKind::Drawing, scene), NoteKind::Note); - let as_list = convert(¬e_of(NoteKind::Drawing, scene), NoteKind::Checklist); - let drawn = convert(¬e_of(NoteKind::Note, "words"), NoteKind::Drawing); - let kept = convert(¬e_of(NoteKind::Drawing, scene), NoteKind::Drawing); + assert_eq!(body.content, "- [x] write\n- [ ] ship"); + assert!(body.items.is_empty()); + } - assert_eq!(as_note.content, "API\nDB"); + #[test] + fn a_todo_list_becomes_its_texts_one_a_line_elsewhere() { + for into in [NoteKind::Snippet, NoteKind::Calc] { + let body = convert( + &checklist(vec![item("2 + 2", true), item("3 * 3", false)]), + into, + ); + + assert_eq!(body.content, "2 + 2\n3 * 3", "{into}"); + assert!(body.items.is_empty()); + } + } + + #[test] + fn a_todo_list_kept_a_todo_list_keeps_its_items_and_their_state() { + let items = vec![item("write", true), item("ship", false)]; + + let body = convert(&checklist(items.clone()), NoteKind::Checklist); + + assert_eq!(body.items, items); + assert_eq!(body.content, ""); + } + + #[test] + fn a_drawing_gives_its_words_to_a_text_and_to_a_todo_list() { + let drawing = note(NoteKind::Drawing, &scene(&["Login", "Logout"])); + + assert_eq!(convert(&drawing, NoteKind::Note).content, "Login\nLogout"); assert_eq!( - as_list - .items - .iter() - .map(|item| item.text.as_str()) - .collect::>(), - ["API", "DB"] + convert(&drawing, NoteKind::Checklist).items, + [item("Login", false), item("Logout", false)] ); - assert_eq!(drawn.content, ""); - assert_eq!(kept.content, scene); } #[test] - fn a_snippet_and_a_note_keep_their_text_as_it_is() { - let code = "fn main() {\n println!(\"hi\");\n}"; + fn a_drawing_kept_a_drawing_keeps_its_scene() { + let content = scene(&["Login"]); - let as_note = convert(¬e_of(NoteKind::Snippet, code), NoteKind::Note); - let as_snippet = convert(¬e_of(NoteKind::Note, code), NoteKind::Snippet); + let body = convert(¬e(NoteKind::Drawing, &content), NoteKind::Drawing); - assert_eq!(as_note.content, code); - assert_eq!(as_note.language, Language::default()); - assert_eq!(as_snippet.content, code); - assert_eq!(as_snippet.language, language::from_content(code)); + assert_eq!(body.content, content); } #[test] - fn a_todo_list_becomes_a_task_list_in_a_note_and_lines_in_a_snippet() { - let list = checklist(&[item("Freeze", true), item("Deploy", false)]); + fn nothing_written_becomes_a_drawing() { + let sources = [ + note(NoteKind::Snippet, PYTHON), + checklist(vec![item("a", false)]), + ]; - let as_note = convert(&list, NoteKind::Note); - let as_snippet = convert(&list, NoteKind::Snippet); + for source in sources { + let body = convert(&source, NoteKind::Drawing); - assert_eq!(as_note.content, "- [x] Freeze\n- [ ] Deploy"); - assert!(as_note.items.is_empty()); - assert_eq!(as_snippet.content, "Freeze\nDeploy"); + assert_eq!(body.content, ""); + assert!(body.items.is_empty()); + } } #[test] - fn a_text_becomes_one_item_per_line_its_markers_dropped_and_its_boxes_read() { - let text = "Release\n\n- Freeze the merges\n* [x] Back the database up\n+ [ ] Ship\n12. Watch\n3) Tell\n [X] Close "; + fn the_body_before_a_conversion_is_the_note_s_own() { + let source = checklist(vec![item("a", true)]); - let list = convert(¬e_of(NoteKind::Note, text), NoteKind::Checklist); - - assert_eq!(list.content, ""); - assert_eq!(list.language, Language::default()); assert_eq!( - list.items, - [ - item("Release", false), - item("Freeze the merges", false), - item("Back the database up", true), - item("Ship", false), - item("Watch", false), - item("Tell", false), - item("Close", true), - ] + NoteBody::of(&source), + NoteBody { + kind: NoteKind::Checklist, + language: Language::Txt, + content: String::new(), + items: vec![item("a", true)], + } ); } #[test] - fn a_number_alone_or_a_word_after_a_dash_is_text_not_a_marker() { + fn a_list_marker_is_dropped_from_an_item() { + let items = items_of("- a\n* b\n+ c\n1. d\n12) e\n- f"); + + let texts: Vec<_> = items.iter().map(|item| item.text.as_str()).collect(); + assert_eq!(texts, ["a", "b", "c", "d", "e", "f"]); + } + + #[test] + fn a_task_box_is_read_as_the_item_s_state() { + let items = items_of("[ ] a\n[x] b\n[X] c\n- [x] d"); + assert_eq!( - items_of("2026 budget\n-dash\n1.5 litres"), + items, [ - item("2026 budget", false), - item("-dash", false), - item("1.5 litres", false) + item("a", false), + item("b", true), + item("c", true), + item("d", true) ] ); } #[test] - fn a_task_list_goes_round_a_note_and_back_unchanged() { - let items = [item("One", true), item("Two", false)]; + fn what_only_looks_like_a_marker_is_kept_as_written() { + let items = items_of("-a\n2024 report\n1.5 kg\n[x]done\n(1) first"); - let as_note = convert(&checklist(&items), NoteKind::Note); - let back = convert( - ¬e_of(NoteKind::Note, &as_note.content), - NoteKind::Checklist, + let texts: Vec<_> = items.iter().map(|item| item.text.as_str()).collect(); + assert_eq!( + texts, + ["-a", "2024 report", "1.5 kg", "[x]done", "(1) first"] ); + assert!(items.iter().all(|item| !item.done)); + } + + #[test] + fn a_todo_list_goes_round_a_note_and_back_unchanged() { + let items = vec![item("One", true), item("Two", false)]; + + let as_note = convert(&checklist(items.clone()), NoteKind::Note); + let back = convert(¬e(NoteKind::Note, &as_note.content), NoteKind::Checklist); assert_eq!(back.items, items); } + + #[test] + fn a_text_with_nothing_written_gives_no_item() { + for text in ["", "\n \n\t"] { + assert!(items_of(text).is_empty(), "{text:?}"); + } + } } diff --git a/crates/engine/src/notes/drawing.rs b/crates/engine/src/notes/drawing.rs index 29c11f979..ac2488d22 100644 --- a/crates/engine/src/notes/drawing.rs +++ b/crates/engine/src/notes/drawing.rs @@ -124,102 +124,143 @@ fn gather(shapes: &[Shape], lines: &mut Vec) { mod tests { use super::*; - /// The eight bytes every PNG opens with, and a few after them. - fn png_uri() -> String { - uri_of(b"\x89PNG\r\n\x1a\nIHDR") + fn png_of(length: usize) -> Vec { + let mut bytes = SIGNATURE.to_vec(); + bytes.resize(length.max(SIGNATURE.len()), 0); + bytes + } + + fn pictures(thumbnail: &str, picture: &str) -> DrawingPictures { + DrawingPictures { + thumbnail: thumbnail.into(), + picture: picture.into(), + } + } + + fn refused_field(pictures: &DrawingPictures) -> &'static str { + pictures.decoded().expect_err("refused").field + } + + fn reference(id: &str, title: &str) -> DrawingRef { + DrawingRef { + id: id.into(), + title: title.into(), + } + } + + #[test] + fn two_png_pictures_are_decoded_to_their_bytes() { + let small = png_of(16); + let large = png_of(64); + + let decoded = pictures(&uri_of(&small), &uri_of(&large)).decoded(); + + assert_eq!( + decoded, + Ok(Some(Pictures { + thumbnail: small, + picture: large + })) + ); + } + + #[test] + fn no_picture_at_all_is_a_drawing_emptied() { + assert_eq!(pictures("", "").decoded(), Ok(None)); } #[test] - fn the_words_are_read_through_the_groups_a_line_each() { - let body = r#"{ - "version": 1, - "scene": { - "version": "7.4.0", - "objects": [ - { "type": "Rect", "left": 10 }, - { "type": "Textbox", "text": "API gateway" }, - { "type": "Group", "objects": [{ "type": "Textbox", "text": " Postgres\nprimary " }] }, - { "type": "Textbox", "text": " " } - ] - } - }"#; - - assert_eq!(words(body), "API gateway\nPostgres primary"); + fn one_picture_without_the_other_is_refused() { + let uri = uri_of(&png_of(16)); + + assert_eq!(refused_field(&pictures(&uri, "")), "pictures.picture"); + assert_eq!(refused_field(&pictures("", &uri)), "pictures.thumbnail"); } #[test] - fn a_body_that_does_not_parse_is_an_empty_drawing() { - for body in ["", "not json", "[1, 2]", r#"{ "scene": 3 }"#] { - assert_eq!(words(body), ""); + fn a_picture_that_is_not_a_png_data_uri_is_refused() { + let good = uri_of(&png_of(16)); + for bad in [ + "data:image/jpeg;base64,/9j/4AAQ".to_string(), + "data:image/svg+xml;base64,PHN2Zz4=".to_string(), + "javascript:alert(1)".to_string(), + "iVBORw0KGgo=".to_string(), + "data:image/png;base64,***".to_string(), + uri_of(b"GIF89a, not a PNG"), + ] { + assert_eq!( + refused_field(&pictures(&bad, &good)), + "pictures.thumbnail", + "{bad}" + ); + assert_eq!( + refused_field(&pictures(&good, &bad)), + "pictures.picture", + "{bad}" + ); } } #[test] - fn two_pngs_are_taken_as_bytes_and_given_back_as_they_came() { - let sent = DrawingPictures { - thumbnail: png_uri(), - picture: png_uri(), - }; + fn a_picture_just_under_the_limit_is_kept() { + let largest = png_of(PICTURE_MAX_BYTES - 1); - let decoded = sent.decoded().unwrap().unwrap(); + let decoded = pictures(&uri_of(&png_of(16)), &uri_of(&largest)).decoded(); - assert!(decoded.thumbnail.starts_with(SIGNATURE)); - assert_eq!(uri_of(&decoded.picture), png_uri()); + assert_eq!( + decoded.unwrap().unwrap().picture.len(), + PICTURE_MAX_BYTES - 1 + ); } #[test] - fn drawings_are_named_in_the_order_of_their_titles() { - let drawing = |id: &str, title: &str| DrawingRef { - id: id.to_string(), - title: title.to_string(), - }; - let mut drawings = vec![ - drawing("3", "Réseau"), - drawing("2", "archi"), - drawing("1", "Archi"), - ]; + fn a_picture_past_the_limit_is_refused_before_it_is_decoded() { + let past = format!("{PNG}{}", "*".repeat(PICTURE_MAX_BYTES / 3 * 4 + 8)); - sort_drawings(&mut drawings); + let refused = pictures(&past, &uri_of(&png_of(16))).decoded().unwrap_err(); assert_eq!( - drawings - .iter() - .map(|each| each.id.as_str()) - .collect::>(), - ["1", "2", "3"] + refused, + ValidationError::new("pictures.thumbnail", "too large") ); } #[test] - fn two_empty_pictures_take_them_away() { - let emptied = DrawingPictures { - thumbnail: String::new(), - picture: String::new(), - }; + fn the_words_of_a_drawing_are_its_texts_one_a_line_groups_included() { + let body = serde_json::json!({ + "scene": { "objects": [ + { "type": "rect" }, + { "type": "textbox", "text": " Login " }, + { "type": "group", "objects": [ + { "type": "i-text", "text": "two\nlines" }, + { "type": "group", "objects": [{ "type": "text", "text": "deep" }] }, + ]}, + { "type": "textbox", "text": " " }, + ]} + }); + + assert_eq!(words(&body.to_string()), "Login\ntwo lines\ndeep"); + } - assert_eq!(emptied.decoded().unwrap(), None); + #[test] + fn a_body_that_does_not_read_as_a_scene_has_no_words() { + for content in ["", "not json", "[]", "{}", r#"{"scene": 3}"#] { + assert_eq!(words(content), "", "{content}"); + } } - /// Shown by an `` alone: anything but a PNG is no picture, nor one too big. #[test] - fn what_is_not_a_png_is_refused_and_named() { - let refused = |thumbnail: &str| { - DrawingPictures { - thumbnail: thumbnail.to_string(), - picture: png_uri(), - } - .decoded() - .unwrap_err() - }; + fn drawings_sort_by_title_as_a_search_folds_it_then_by_id() { + let mut drawings = [ + reference("3", "zèbre"), + reference("2", "Écran"), + reference("9", "ecran"), + reference("1", "ecran"), + ]; - assert_eq!( - refused("data:image/svg+xml;base64,PHN2Zz4=").field, - "pictures.thumbnail" - ); - assert_eq!(refused("javascript:alert(1)").detail, "not a PNG data URI"); - assert_eq!(refused("data:image/png;base64,***").detail, "not base64"); - assert_eq!(refused(&uri_of(b"GIF89a")).detail, "not a PNG"); - let huge = format!("{PNG}{}", "A".repeat(PICTURE_MAX_BYTES / 3 * 4 + 8)); - assert_eq!(refused(&huge).detail, "too large"); + sort_drawings(&mut drawings); + + let ids: Vec<_> = drawings.iter().map(|drawing| drawing.id.as_str()).collect(); + assert_eq!(ids, ["1", "2", "9", "3"]); } } diff --git a/crates/engine/src/notes/kind.rs b/crates/engine/src/notes/kind.rs index 096a8810d..39d0bc27e 100644 --- a/crates/engine/src/notes/kind.rs +++ b/crates/engine/src/notes/kind.rs @@ -29,32 +29,25 @@ mod tests { use super::*; #[test] - fn the_serialized_form_matches_the_stored_one() { - for kind in NoteKind::ALL { - let json = serde_json::to_string(&kind).unwrap(); - - assert_eq!(json, format!("\"{}\"", kind.as_str())); - assert_eq!(kind.as_str().parse::().unwrap(), kind); - } - } - - #[test] - fn an_unknown_stored_kind_is_refused_rather_than_guessed() { - assert!("kanban".parse::().is_err()); + fn a_note_of_no_stated_kind_is_a_snippet() { + assert_eq!(NoteKind::default(), NoteKind::Snippet); } #[test] - fn a_note_written_before_todo_lists_reads_back_as_a_snippet() { - assert_eq!(NoteKind::default(), NoteKind::Snippet); + fn only_a_snippet_has_a_language() { + for kind in NoteKind::ALL { + assert_eq!(kind.has_language(), kind == NoteKind::Snippet, "{kind}"); + } } + /// Stored in every library and every export: a spelling never changes. #[test] - fn only_a_snippet_has_a_language() { - let with_language: Vec<_> = NoteKind::ALL - .into_iter() - .filter(|kind| kind.has_language()) - .collect(); + fn each_kind_keeps_its_stored_spelling_in_the_rail_s_order() { + let spellings = NoteKind::ALL.map(NoteKind::as_str); - assert_eq!(with_language, [NoteKind::Snippet]); + assert_eq!( + spellings, + ["snippet", "note", "checklist", "calc", "drawing"] + ); } } diff --git a/crates/engine/src/notes/markdown.rs b/crates/engine/src/notes/markdown.rs index a55e496ce..e76c89719 100644 --- a/crates/engine/src/notes/markdown.rs +++ b/crates/engine/src/notes/markdown.rs @@ -203,169 +203,274 @@ impl Out { mod tests { use super::*; + fn text(text: &str) -> OutlineLine { + OutlineLine::Text { text: text.into() } + } + + fn item(text: &str, depth: u32, marker: &str) -> OutlineLine { + OutlineLine::Item { + text: text.into(), + depth, + marker: marker.into(), + } + } + + fn task(text: &str, depth: u32, done: bool) -> OutlineLine { + OutlineLine::Task { + text: text.into(), + depth, + done, + } + } + + fn node(text: &str, slide: u32, children: Vec) -> MapNode { + MapNode { + text: text.into(), + slide, + children, + } + } + + #[test] + fn each_block_is_one_line_saying_what_it_is() { + let lines = outline("# Title\n\nA paragraph.\n\n```sql\nSELECT 1;\n -- *as is*\n```\n"); + + assert_eq!( + lines, + [ + OutlineLine::Heading { + text: "Title".into() + }, + text("A paragraph."), + OutlineLine::Code { + text: "SELECT 1;\n -- *as is*".into() + }, + ] + ); + } + #[test] fn the_rich_editor_reads_markdown_with_the_same_options() { assert_eq!(OPTIONS, richtext::OPTIONS); } #[test] - fn the_syntax_goes_and_the_words_stay() { + fn what_the_rich_editor_escapes_reads_as_typed() { assert_eq!( - plain("# Release\n\nShip **today**, not *tomorrow* — ~~maybe~~ `v2`."), - "Release\nShip today, not tomorrow — maybe v2." + plain("2 \\* 3 and \\[x\\] for {{db_host}}"), + "2 * 3 and [x] for {{db_host}}" ); + assert_eq!(plain(" indented"), "\tindented"); } #[test] - fn lists_are_marked_as_a_card_can_show_them() { - assert_eq!( - plain("- one\n- two\n - nested\n\n1. first\n2. second"), - "• one\n• two\n • nested\n1. first\n2. second" - ); + fn inline_markup_is_taken_away_and_its_words_kept() { + let lines = outline("**bold** _it_ `code` ~~gone~~ [link](https://x.test) ![alt](a.png)"); + + assert_eq!(lines, [text("bold it code gone link alt")]); } #[test] - fn a_task_says_whether_it_is_done() { + fn the_lines_of_a_paragraph_are_joined_by_a_space() { + assert_eq!(outline("one\ntwo"), [text("one two")]); + } + + #[test] + fn a_hard_break_starts_a_new_line() { + assert_eq!(outline("one \ntwo"), [text("one"), text("two")]); + } + + #[test] + fn a_bulleted_item_is_marked_with_a_bullet_and_its_depth() { + let lines = outline("- a\n - b\n - c\n- d"); + assert_eq!( - plain("- [ ] write the notes\n- [x] book the room"), - "☐ write the notes\n☑ book the room" + lines, + [ + item("a", 0, "•"), + item("b", 1, "•"), + item("c", 2, "•"), + item("d", 0, "•"), + ] ); } #[test] - fn a_link_keeps_its_text_and_a_quote_its_words() { + fn a_numbered_item_is_marked_with_its_number_from_the_list_s_first() { + let lines = outline("3. c\n4. d\n\n---\n\n1. a\n 1. a.a\n2. b"); + assert_eq!( - plain("See [the runbook](https://example.com).\n\n> Measure first."), - "See the runbook.\nMeasure first." + lines, + [ + item("c", 0, "3."), + item("d", 0, "4."), + item("a", 0, "1."), + item("a.a", 1, "1."), + item("b", 0, "2."), + ] ); } #[test] - fn a_table_reads_row_by_row() { + fn a_task_says_whether_it_is_done() { + let lines = outline("- [ ] open\n- [x] closed\n - [X] nested"); + assert_eq!( - plain("| host | port |\n| --- | --- |\n| db | 5432 |"), - "host · port\ndb · 5432" + lines, + [ + task("open", 0, false), + task("closed", 0, true), + task("nested", 1, true) + ] ); } - /// What the rich editor escapes, and what a field is, come back as typed. #[test] - fn escapes_and_fields_read_as_typed() { + fn the_items_of_a_loose_list_are_one_line_each() { assert_eq!( - plain("2 \\* 3 and \\[x\\] for {{db_host}}"), - "2 * 3 and [x] for {{db_host}}" + outline("- a\n\n- b"), + [item("a", 0, "•"), item("b", 0, "•")] ); } - /// How the rich editor stores a tab starting a line, which Markdown would read as code. #[test] - fn a_tab_written_as_an_entity_reads_as_a_tab() { - assert_eq!(plain(" indented"), "\tindented"); + fn a_table_row_is_one_line_of_its_cells() { + let lines = outline("| a | b |\n|---|---|\n| 1 | 2 |"); + + assert_eq!(lines, [text("a · b"), text("1 · 2")]); + } + + #[test] + fn a_block_with_nothing_readable_gives_no_line() { + for markdown in ["", "\n\n", "---", "
", "- ", "#"] { + assert_eq!(outline(markdown), [], "{markdown:?}"); + } + } + + #[test] + fn a_quote_reads_as_its_text() { + assert_eq!(outline("> said"), [text("said")]); } - /// A card shows a code block's lines as written, and a search finds and quotes them. #[test] - fn a_code_block_reads_as_its_lines() { + fn plain_spells_out_each_marker_indented_two_spaces_a_level() { + let markdown = "# Plan\n\n- a\n - b\n\n1. one\n\n- [ ] todo\n - [x] done"; + assert_eq!( - plain( - "Check: - -```sql -SELECT 1; - -- *not* emphasis -``` - -Done." - ), - "Check: -SELECT 1; - -- *not* emphasis -Done." + plain(markdown), + "Plan\n• a\n • b\n1. one\n☐ todo\n ☑ done" ); } #[test] - fn plain_text_stays_plain() { - assert_eq!(plain("just a line\nand another"), "just a line and another"); + fn plain_of_an_empty_body_is_empty() { assert_eq!(plain(""), ""); } - fn node(text: &str, slide: u32, children: Vec) -> MapNode { - MapNode { - text: text.to_string(), - slide, - children, - } + #[test] + fn a_body_without_heading_or_rule_is_one_slide() { + let shown = present("\n Just text.\n\n- and a list\n\n"); + + assert_eq!(shown.slides, ["Just text.\n\n- and a list"]); + assert!(shown.map.is_empty()); } #[test] - fn a_note_is_cut_at_its_sections_and_its_rules_as_the_body_wrote_them() { - let presentation = present( - "Intro line.\n\n## Why\n\nBecause *so*.\n\n---\n\nA pause.\n\n# Next\n\n### Detail\n\nMore.", + fn an_empty_body_has_no_slide() { + assert_eq!( + present(" \n"), + Presentation { + slides: vec![], + map: vec![] + } ); + } + + #[test] + fn a_first_or_second_level_heading_starts_a_slide_and_a_third_does_not() { + let shown = present("intro\n# One\nbody\n## Two\n### Three\nmore"); assert_eq!( - presentation.slides, - [ - "Intro line.", - "## Why\n\nBecause *so*.", - "A pause.", - "# Next\n\n### Detail\n\nMore." - ] + shown.slides, + ["intro", "# One\nbody", "## Two\n### Three\nmore"] ); } - /// A `##` in a fence is code, and one in a quote or a list belongs to it. #[test] - fn a_heading_or_a_rule_inside_a_block_cuts_nothing() { - let presentation = present( - "## One\n\n```md\n## not a slide\n---\n```\n\n> ## quoted\n\n- item\n\n ---\n\n more", - ); + fn an_underlined_heading_starts_a_slide_too() { + let shown = present("intro\n\nTitle\n=====\nbody"); - assert_eq!(presentation.slides.len(), 1); + assert_eq!(shown.slides, ["intro", "Title\n=====\nbody"]); } #[test] - fn nothing_to_cut_is_one_slide_and_nothing_at_all_none() { - assert_eq!(present("Just words.").slides, ["Just words."]); - assert!(present(" \n\n---\n\n---\n").slides.is_empty()); - assert!(present("").map.is_empty()); + fn a_rule_ends_a_slide_and_is_not_part_of_either() { + let shown = present("one **bold**\n\n---\n\ntwo"); + + assert_eq!(shown.slides, ["one **bold**", "two"]); } #[test] - fn the_map_holds_each_heading_under_the_one_above_it_with_its_slide() { - let presentation = present( - "# Plan\n\n## Build\n\n### Rust\n\n### Front\n\n## Ship `v2` **now**\n\n#### Deep\n\n##\n", - ); + fn a_heading_or_rule_inside_a_list_a_quote_or_code_cuts_nothing() { + for markdown in [ + "- item\n\n # not a cut", + "> # quoted\n>\n> ---", + "```\n# comment\n---\n```", + " # indented code", + ] { + assert_eq!(present(markdown).slides, [markdown.trim()], "{markdown:?}"); + } + } - assert_eq!( - presentation.map, - [node( - "Plan", - 0, - vec![ - node( - "Build", - 1, - vec![node("Rust", 1, vec![]), node("Front", 1, vec![])] - ), - node("Ship v2 now", 2, vec![node("Deep", 2, vec![])]), - ], - )] - ); + #[test] + fn a_slide_with_nothing_in_it_is_dropped() { + let shown = present("---\n# One\n\n---\n\n---\n\n# Two\n---\n"); + + assert_eq!(shown.slides, ["# One", "# Two"]); } - /// Two trees side by side when the Note opens on a `##` and a `#` comes later. #[test] - fn a_heading_above_the_first_one_starts_a_tree_of_its_own() { - let presentation = present("## Before\n\n# After\n\n## Under"); + fn the_map_holds_each_heading_under_the_one_above_with_its_slide() { + let shown = present("# A\n## A.1\n### A.1.a\n## A.2\n# B\n### B.x"); assert_eq!( - presentation.map, + shown.map, [ - node("Before", 0, vec![]), - node("After", 1, vec![node("Under", 2, vec![])]) + node( + "A", + 0, + vec![ + node("A.1", 1, vec![node("A.1.a", 1, vec![])]), + node("A.2", 2, vec![]), + ] + ), + node("B", 3, vec![node("B.x", 3, vec![])]), ] ); } + + #[test] + fn a_deeper_heading_before_any_shallower_one_is_a_root_of_the_map() { + let shown = present("### Aside\n# Main"); + + assert_eq!( + shown.map, + [node("Aside", 0, vec![]), node("Main", 1, vec![])] + ); + } + + #[test] + fn a_heading_s_words_in_the_map_lose_their_markup() { + let shown = present("# The `query_notes` **call**"); + + assert_eq!(shown.map, [node("The query_notes call", 0, vec![])]); + } + + #[test] + fn an_empty_heading_cuts_a_slide_but_is_not_in_the_map() { + let shown = present("intro\n\n#\n\nafter"); + + assert_eq!(shown.slides, ["intro", "#\n\nafter"]); + assert!(shown.map.is_empty()); + } } diff --git a/crates/engine/src/notes/placeholder.rs b/crates/engine/src/notes/placeholder.rs index 89a7c4726..ce2f569f5 100644 --- a/crates/engine/src/notes/placeholder.rs +++ b/crates/engine/src/notes/placeholder.rs @@ -14,11 +14,6 @@ pub struct Placeholder { pub value: String, } -/// The rule of [`is_field_name`] as a pattern, which crosses as a constant: the front end -/// refuses a name in the same terms without keeping a copy. ⚠️ Rust checks characters rather -/// than matching it, so only `the_pattern_and_the_rule_agree` keeps the two in step. -pub const FIELD_NAME_PATTERN: &str = "^[A-Za-z0-9_-]+$"; - /// Restricted to `[A-Za-z0-9_-]` on purpose: without it a note holding Angular template /// code (`{{ user.name }}`) would demand a form on every copy. fn is_field_name(name: &str) -> bool { @@ -236,248 +231,274 @@ impl<'a> Utf16Cursor<'a> { #[cfg(test)] mod tests { - /// Every case that distinguishes the pattern from the character check is listed here: - /// nothing else stops the two drifting. - #[test] - fn the_pattern_and_the_rule_agree() { - let names = [ - "host", - "HOST", - "port_2", - "a-b", - "_", - "-", - "0", - "", - " host", - "host ", - "user.name", - "user name", - "café", - "хост", - "2", - "host\n", - "{{host}}", - ]; - - // A hand-rolled reader of the pattern: the crate carries no regex engine. - let matches = |name: &str| { - let class = super::FIELD_NAME_PATTERN - .strip_prefix("^[") - .and_then(|rest| rest.strip_suffix("]+$")) - .expect("a character class pattern"); - - !name.is_empty() - && name.chars().all(|c| { - (class.contains("A-Z") && c.is_ascii_uppercase()) - || (class.contains("a-z") && c.is_ascii_lowercase()) - || (class.contains("0-9") && c.is_ascii_digit()) - || (class.contains('_') && c == '_') - || (class.ends_with('-') && c == '-') - }) - }; - - for name in names { - assert_eq!( - super::is_field_name(name), - matches(name), - "{name:?} is read differently by the rule and by the pattern" - ); - } - } - use super::*; - fn values(pairs: &[(&str, &str)]) -> BTreeMap { + fn map(pairs: &[(&str, &str)]) -> BTreeMap { pairs .iter() - .map(|(key, value)| ((*key).to_string(), (*value).to_string())) + .map(|(name, value)| ((*name).to_string(), (*value).to_string())) .collect() } fn names(content: &str) -> Vec { parse(content, &BTreeMap::new()) .into_iter() - .map(|placeholder| placeholder.name) + .map(|field| field.name) .collect() } #[test] - fn each_field_is_listed_once_in_order_of_appearance() { - assert_eq!( - names("psql -h {{host}} -p {{port}} -d {{db}} # {{host}}"), - ["host", "port", "db"] - ); + fn a_name_of_ascii_letters_digits_underscores_and_hyphens_is_a_field() { + for (content, name) in [ + ("{{host}}", "host"), + ("{{API_KEY}}", "API_KEY"), + ("{{api-key}}", "api-key"), + ("{{9}}", "9"), + ("{{ host }}", "host"), + ] { + assert_eq!(names(content), [name], "{content}"); + } } #[test] - fn a_default_value_is_read_after_the_equals_sign() { - assert_eq!( - parse("{{ port = 5432 }}", &BTreeMap::new()), - [Placeholder { - name: "port".to_string(), - default_value: "5432".to_string(), - value: String::new(), - }] - ); + fn a_name_with_any_other_character_is_text_and_not_a_field() { + for content in [ + "{{ user.name }}", + "{{my host}}", + "{{hôte}}", + "{{2}}", + "{{items[0]}}", + "{{a$b}}", + "{{}}", + "{{ }}", + "{{=5432}}", + "{{{host}}}", + ] { + assert!(names(content).is_empty(), "{content}"); + } } #[test] - fn a_field_carries_what_was_already_typed_for_it() { - assert_eq!( - parse("{{host}}", &values(&[("host", "db.internal")])), - [Placeholder { - name: "host".to_string(), - default_value: String::new(), - value: "db.internal".to_string(), - }] - ); + fn the_default_is_what_follows_the_first_equals_sign_trimmed() { + for (content, default) in [ + ("{{port=5432}}", "5432"), + ("{{ port = 5432 }}", "5432"), + ("{{url=a=b}}", "a=b"), + ("{{port=}}", ""), + ("{{port}}", ""), + ] { + let fields = parse(content, &BTreeMap::new()); + + assert_eq!(fields[0].default_value, default, "{content}"); + } } #[test] - fn a_value_whose_token_left_the_text_is_not_a_field() { - let fields = parse("{{hostname}}", &values(&[("host", "db")])); + fn fields_come_once_each_in_the_order_of_their_first_token() { + let fields = parse("{{b}} {{a=1}} {{b=2}} {{a=3}}", &BTreeMap::new()); - assert_eq!(names("{{hostname}}"), ["hostname"]); - assert!(fields[0].value.is_empty()); + let found: Vec<_> = fields + .iter() + .map(|field| (field.name.as_str(), field.default_value.as_str())) + .collect(); + assert_eq!(found, [("b", ""), ("a", "1")]); } #[test] - fn only_what_can_designate_a_token_is_kept_for_writing() { - assert_eq!( - normalize_values(values(&[ - ("host", "db.internal"), - ("port", ""), - ("user.name", "x"), - ])), - values(&[("host", "db.internal")]) - ); + fn a_stored_value_reaches_the_field_of_the_same_name() { + let fields = parse("{{host=localhost}}", &map(&[("host", "db.internal")])); + + assert_eq!(fields[0].value, "db.internal"); + assert_eq!(fields[0].default_value, "localhost"); } #[test] - fn a_template_expression_is_not_a_field() { - assert!(names("

{{ user.name }}

{{ items[0] }}").is_empty()); + fn field_names_are_case_sensitive() { + let fields = parse("{{Host}} {{host}}", &map(&[("host", "db")])); + + let found: Vec<_> = fields + .iter() + .map(|field| (field.name.as_str(), field.value.as_str())) + .collect(); + assert_eq!(found, [("Host", ""), ("host", "db")]); } #[test] - fn an_unterminated_token_ends_the_scan_without_panicking() { - assert_eq!(names("{{host}} puis {{oops"), ["host"]); + fn a_value_whose_token_left_the_text_is_not_a_field() { + let fields = parse("{{renamed}}", &map(&[("former", "kept")])); + + assert_eq!(fields.len(), 1); + assert_eq!(fields[0].name, "renamed"); + assert_eq!(fields[0].value, ""); } #[test] - fn a_global_variable_fills_a_field_the_note_says_nothing_about() { - let globals = values(&[("host", "db.internal")]); + fn an_opening_without_its_closing_ends_the_fields() { + assert_eq!(names("{{a}} {{b"), ["a"]); + assert_eq!(names("{{a {{b}}"), Vec::::new()); + assert_eq!(names("}} {{a}}"), ["a"]); + } - assert_eq!( - fill("{{host}}", &resolve(&globals, &BTreeMap::new())), - "db.internal" - ); + #[test] + fn a_text_without_tokens_has_no_fields() { + for content in ["", "psql -h localhost", "{ {host} }"] { + assert!(names(content).is_empty(), "{content}"); + } } #[test] - fn what_was_typed_on_the_note_wins_over_the_global_variable() { - let globals = values(&[("host", "db.internal")]); + fn normalize_values_keeps_only_non_empty_values_of_field_names() { + let values = map(&[ + ("host", "db"), + ("port", ""), + ("user.name", "ada"), + ("", "orphan"), + ]); + + assert_eq!(normalize_values(values), map(&[("host", "db")])); + } - assert_eq!( - fill( - "{{host}}", - &resolve(&globals, &values(&[("host", "localhost")])) - ), - "localhost" - ); + #[test] + fn a_note_value_comes_before_the_global_variable() { + let cases = [ + (&[("host", "global")][..], &[("host", "note")][..], "note"), + (&[("host", "global")], &[("host", "")], "global"), + (&[("host", "global")], &[], "global"), + (&[], &[("host", "note")], "note"), + ]; + + for (globals, values, expected) in cases { + let resolved = resolve(&map(globals), &map(values)); + + assert_eq!(resolved["host"], expected, "{globals:?} {values:?}"); + } } #[test] - fn an_empty_entry_leaves_the_global_variable_in_place() { - let globals = values(&[("host", "db.internal")]); + fn a_global_variable_comes_before_the_default_written_in_the_text() { + let resolved = resolve(&map(&[("port", "6543")]), &BTreeMap::new()); - assert_eq!( - fill("{{host}}", &resolve(&globals, &values(&[("host", "")]))), - "db.internal" - ); + assert_eq!(fill("{{port=5432}}", &resolved), "6543"); } #[test] - fn a_global_variable_wins_over_the_default_written_in_the_text() { - let globals = values(&[("port", "6543")]); + fn an_empty_note_value_over_no_global_resolves_to_nothing() { + let resolved = resolve(&BTreeMap::new(), &map(&[("host", "")])); - assert_eq!( - fill("{{port=5432}}", &resolve(&globals, &BTreeMap::new())), - "6543" - ); + assert!(resolved.is_empty()); } #[test] - fn filling_substitutes_every_occurrence() { - assert_eq!( - fill( - "{{host}}:{{port}}/{{host}}", - &values(&[("host", "db"), ("port", "5432")]) - ), - "db:5432/db" + fn fill_puts_each_value_in_place_of_every_token_of_its_field() { + let filled = fill( + "psql -h {{host}} -p {{ port = 5432 }} # {{host}}", + &map(&[("host", "db"), ("port", "6543")]), ); + + assert_eq!(filled, "psql -h db -p 6543 # db"); } #[test] - fn a_missing_value_falls_back_to_the_default() { - assert_eq!(fill("{{port=5432}}", &BTreeMap::new()), "5432"); + fn fill_falls_back_to_the_default_when_the_value_is_missing_or_empty() { + for values in [map(&[]), map(&[("port", "")])] { + assert_eq!(fill("-p {{port=5432}}", &values), "-p 5432"); + } } #[test] - fn an_empty_value_falls_back_to_the_default_too() { - assert_eq!(fill("{{port=5432}}", &values(&[("port", "")])), "5432"); + fn fill_empties_a_field_with_neither_value_nor_default() { + assert_eq!(fill("[{{host}}]", &BTreeMap::new()), "[]"); } #[test] - fn a_field_without_value_nor_default_disappears() { - assert_eq!(fill("a{{x}}b", &BTreeMap::new()), "ab"); + fn fill_leaves_what_is_not_a_field_as_written() { + for content in [ + "{{ user.name }}", + "{{}}", + "{{{host}}}", + "echo {{host", + "}} closing first", + "no token", + "", + ] { + assert_eq!(fill(content, &map(&[("host", "db")])), content); + } } #[test] - fn what_is_not_a_field_survives_untouched() { - let template = "

{{ user.name }}

"; + fn fill_does_not_read_a_filled_value_as_a_token() { + let filled = fill("{{a}}", &map(&[("a", "{{b}}"), ("b", "x")])); - assert_eq!(fill(template, &values(&[("user", "x")])), template); + assert_eq!(filled, "{{b}}"); } - /// In the editor's units: `é`, `→` and `😀` are two, three and four bytes, and one, one and - /// two UTF-16 units. #[test] - fn spans_lie_where_the_editor_counts_them() { - let spans = super::spans("é {{host}} → {{port = 5432}} 😀{{x}}"); - + fn a_span_covers_each_field_token_braces_included() { assert_eq!( - spans, + spans("ssh {{user}}@{{host}}"), [ - super::FieldSpan { - from: 2, - to: 10, - default: None + FieldSpan { + from: 4, + to: 12, + default: None, }, - super::FieldSpan { + FieldSpan { from: 13, - to: 28, - default: Some((22, 26)) + to: 21, + default: None, + }, + ] + ); + } + + #[test] + fn a_span_marks_its_default_trimmed() { + assert_eq!( + spans("{{port = 5432 }}"), + [FieldSpan { + from: 0, + to: 16, + default: Some((9, 13)), + }] + ); + } + + #[test] + fn an_empty_default_marks_no_default() { + assert_eq!(spans("{{port=}}")[0].default, None); + assert_eq!(spans("{{port= }}")[0].default, None); + } + + #[test] + fn spans_are_counted_in_utf_16_units() { + // é is one unit for two bytes, 😀 two units for four, ü one for two. + assert_eq!( + spans("é😀 {{a=ü}} {{b}}"), + [ + FieldSpan { + from: 4, + to: 11, + default: Some((8, 9)), }, - super::FieldSpan { - from: 31, - to: 36, - default: None + FieldSpan { + from: 12, + to: 17, + default: None, }, ] ); } #[test] - fn spans_skip_what_is_not_a_field() { - let text = "{{ user.name }} {{=x}} {{name=}} {{open"; + fn a_token_that_is_not_a_field_has_no_span() { + let found = spans("{{ user.name }} {{a}} {{b"); assert_eq!( - super::spans(text), - [super::FieldSpan { - from: 23, - to: 32, - default: None + found, + [FieldSpan { + from: 16, + to: 21, + default: None, }] ); } diff --git a/crates/engine/src/notes/priority.rs b/crates/engine/src/notes/priority.rs index 0578f0d6d..0de61a151 100644 --- a/crates/engine/src/notes/priority.rs +++ b/crates/engine/src/notes/priority.rs @@ -18,17 +18,29 @@ mod tests { use super::*; #[test] - fn the_serialized_form_matches_the_stored_one() { - for priority in Priority::ALL { - let json = serde_json::to_string(&priority).unwrap(); + fn a_note_of_no_stated_priority_has_none() { + assert_eq!(Priority::default(), Priority::None); + } + + #[test] + fn priorities_rank_from_none_to_urgent() { + let mut shuffled = [ + Priority::High, + Priority::None, + Priority::Urgent, + Priority::Low, + Priority::Medium, + ]; + shuffled.sort(); - assert_eq!(json, format!("\"{}\"", priority.as_str())); - assert_eq!(priority.as_str().parse::().unwrap(), priority); - } + assert_eq!(shuffled, Priority::ALL); } + /// Stored in every library and every export: a spelling never changes. #[test] - fn a_note_without_one_has_none() { - assert_eq!(Priority::default(), Priority::None); + fn each_priority_keeps_its_stored_spelling() { + let spellings = Priority::ALL.map(Priority::as_str); + + assert_eq!(spellings, ["none", "low", "medium", "high", "urgent"]); } } diff --git a/docs/architecture.md b/docs/architecture.md index d96205d3e..470edaa93 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -3839,11 +3839,6 @@ render — exactly the second one uses it from another application. They are dec though: `ShortcutBindings::defaults()` crosses as the `DEFAULT_SHORTCUTS` constant, next to `GLOBAL_ACTION_EVENT` and `APP_METADATA`, and the front re-exports it rather than retyping it. -The same treatment closes the other mirror: `notes::placeholder` exports `FIELD_NAME_PATTERN`, -and `isVariableName` builds its `RegExp` from it. ⚠️ Rust checks characters rather than -matching a regex, so the pattern and `is_field_name` are held together by one test — -`the_pattern_and_the_rule_agree` — and by nothing else. - `AutostartService` reads the system **first** and aligns the preference on what it finds: turning the entry off from the task manager has to uncheck the box, not see DevNotes put it back. From 30715bac74e839860c8b1edf09247eead07c60cb Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 00:34:04 +0100 Subject: [PATCH 02/95] Note model: unit tests rewritten for drafts, patches and previews (#1717) * Rewrite the tests of the note model around its rules Drafts, patches and when they date an edit, footers and expiry, previews, tags and the exported shape. * Name the patch cases' check type for Clippy --- crates/engine/src/notes/model.rs | 1033 ++++++++++++++++++------------ 1 file changed, 628 insertions(+), 405 deletions(-) diff --git a/crates/engine/src/notes/model.rs b/crates/engine/src/notes/model.rs index 9fffff13d..595385584 100644 --- a/crates/engine/src/notes/model.rs +++ b/crates/engine/src/notes/model.rs @@ -603,614 +603,837 @@ pub fn normalize_tags(tags: &[String]) -> Vec { .collect() } +/// What deleting a space or a folder does to the notes it holds: they live on elsewhere, or go to +/// the trash with it. Never erased: only emptying the trash, or its retention, is final. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum HeldNotes { + #[default] + Keep, + Trash, +} + #[cfg(test)] mod tests { + use chrono::TimeDelta; + use super::*; - use crate::notes::fixtures::{NOW, at, note as sample}; + use crate::notes::fixtures::{NOW, at, note}; - #[test] - fn a_rename_normalises_its_sources_and_refuses_a_blank_target() { - let (sources, target) = - retagging(&["#Auth".to_string(), "auth".to_string()], " #identity ").unwrap(); + const PYTHON: &str = "#!/usr/bin/env python\nprint(1)"; - assert_eq!(sources, ["Auth"]); - assert_eq!(target, "identity"); - assert_eq!(retagging(&sources, " # ").unwrap_err().field, "tag"); + fn later() -> DateTime { + at("2026-07-26T10:00:00.000Z") } - #[test] - fn an_imported_note_is_brought_to_the_rules_of_a_write() { - let imported = Note { - tags: vec!["#auth".to_string(), "Auth".to_string(), " ".to_string()], - placeholder_values: BTreeMap::from([ - ("host".to_string(), "db".to_string()), - ("not a field".to_string(), "x".to_string()), - ]), - ..sample() + fn strings(values: &[&str]) -> Vec { + values.iter().map(|value| (*value).to_string()).collect() + } + + fn item(text: &str, done: bool) -> ChecklistItem { + ChecklistItem { + text: text.into(), + done, } - .normalized(); + } - assert_eq!(imported.tags, ["auth"]); - assert_eq!(imported.placeholder_values.len(), 1); + fn draft(kind: NoteKind, language: Language, content: &str) -> NoteDraft { + NoteDraft { + space_id: "s-1".into(), + folder_id: Some("f-1".into()), + title: "Deploy".into(), + language, + content: content.into(), + source: "Ops / Deploy".into(), + tags: strings(&["#ops", "OPS", " deploy "]), + pinned: true, + lifecycle: NoteLifecycle::Permanent, + kind, + priority: Priority::High, + items: vec![item(" a ", true), item(" ", false)], + } } - fn normalized(tags: &[&str]) -> Vec { - normalize_tags(&tags.iter().copied().map(String::from).collect::>()) + fn of_kind(kind: NoteKind, content: &str) -> Note { + Note { + kind, + content: content.into(), + ..note() + } } - #[test] - fn padding_and_blanks_are_dropped() { - assert_eq!( - normalized(&[" urgent ", "", " ", "later"]), - ["urgent", "later"] - ); + fn patched(mut target: Note, patch: &NotePatch) -> Note { + patch.apply(&mut target, later()); + target } - #[test] - fn a_duplicate_keeps_its_first_spelling() { - assert_eq!(normalized(&["Urgent", "urgent", "URGENT"]), ["Urgent"]); + fn preview(target: Note) -> DisplayNote { + let mut shown = decorate(target, at(NOW)); + shown.cut_to_preview(at(NOW).date_naive()); + shown } + // --- A draft becomes a note. + #[test] - fn only_leading_hashes_are_stripped() { - assert_eq!(normalized(&["##c++", "a#b"]), ["c++", "a#b"]); + fn a_draft_becomes_a_note_dated_now_under_the_given_id() { + let made = draft(NoteKind::Snippet, Language::Sh, "ls").into_note("n-9".into(), at(NOW)); + + assert_eq!(made.id, "n-9"); + assert_eq!((made.created_at, made.updated_at), (at(NOW), at(NOW))); + assert_eq!(made.folder_id.as_deref(), Some("f-1")); + assert_eq!(made.space_id, "s-1"); + assert_eq!(made.title, "Deploy"); + assert_eq!(made.source, "Ops / Deploy"); + assert!(made.pinned); + assert_eq!(made.priority, Priority::High); + assert!(made.placeholder_values.is_empty()); } #[test] - fn a_tag_reduced_to_nothing_is_dropped_rather_than_stored_empty() { - assert!(normalized(&[" # ", "#"]).is_empty()); + fn a_draft_s_tags_and_items_are_brought_to_the_rules() { + let made = draft(NoteKind::Checklist, Language::Txt, "").into_note("n".into(), at(NOW)); + + assert_eq!(made.tags, ["ops", "deploy"]); + assert_eq!(made.items, [item("a", true)]); } #[test] - fn tag_case_folding_reaches_beyond_ascii() { - assert_eq!(normalized(&["Étape", "étape"]), ["Étape"]); - } + fn a_snippet_draft_keeps_the_language_chosen_or_detects_one() { + let chosen = draft(NoteKind::Snippet, Language::Sh, PYTHON).into_note("n".into(), at(NOW)); + let detected = + draft(NoteKind::Snippet, Language::Txt, PYTHON).into_note("n".into(), at(NOW)); - fn now() -> DateTime { - at(NOW) + assert_eq!(chosen.language, Language::Sh); + assert_eq!(detected.language, Language::Py); } - fn expiring(at_iso: &str) -> Note { - Note { - lifecycle: NoteLifecycle::Expires { at: at(at_iso) }, - ..sample() + #[test] + fn a_draft_of_another_kind_has_no_language() { + for kind in [ + NoteKind::Note, + NoteKind::Checklist, + NoteKind::Calc, + NoteKind::Drawing, + ] { + let made = draft(kind, Language::Py, PYTHON).into_note("n".into(), at(NOW)); + + assert_eq!(made.language, Language::Txt, "{kind}"); } } - fn draft(language: Language, content: &str) -> NoteDraft { - NoteDraft { - space_id: "s-1".to_string(), - folder_id: None, - title: "Title".to_string(), - language, - content: content.to_string(), - source: "API Gateway".to_string(), - tags: vec![" #Urgent ".to_string(), "urgent".to_string()], - pinned: true, - lifecycle: NoteLifecycle::Permanent, - kind: NoteKind::Snippet, - priority: Priority::None, - items: Vec::new(), - } - } + // --- A patch edits a note. #[test] - fn a_draft_becomes_a_note_carrying_the_id_and_the_instant_it_was_given() { - let note = draft(Language::Md, "some prose").into_note("n-7".to_string(), now()); - - assert_eq!(note.id, "n-7"); - assert_eq!(note.created_at, now()); - assert_eq!(note.updated_at, now()); + fn an_empty_patch_changes_nothing_not_even_the_date() { + assert_eq!(patched(note(), &NotePatch::default()), note()); } #[test] - fn turning_a_draft_into_a_note_detects_the_language_and_normalizes_the_tags() { - let note = draft(Language::Txt, "{\"a\": 1}").into_note("n-7".to_string(), now()); - - assert_eq!(note.language, Language::Json); - assert_eq!(note.tags, ["Urgent"]); - } + fn each_field_a_patch_sets_is_written_and_dates_the_edit() { + type Written = fn(&Note) -> bool; + let cases: [(NotePatch, Written); 8] = [ + ( + NotePatch { + title: Some("New".into()), + ..NotePatch::default() + }, + |n| n.title == "New", + ), + ( + NotePatch { + content: Some("body".into()), + ..NotePatch::default() + }, + |n| n.content == "body", + ), + ( + NotePatch { + source: Some("A / B".into()), + ..NotePatch::default() + }, + |n| n.source == "A / B", + ), + ( + NotePatch { + pinned: Some(true), + ..NotePatch::default() + }, + |n| n.pinned, + ), + ( + NotePatch { + language: Some(Language::Rs), + ..NotePatch::default() + }, + |n| n.language == Language::Rs, + ), + ( + NotePatch { + space_id: Some("s-2".into()), + ..NotePatch::default() + }, + |n| n.space_id == "s-2", + ), + ( + NotePatch { + kind: Some(NoteKind::Calc), + ..NotePatch::default() + }, + |n| n.kind == NoteKind::Calc, + ), + ( + NotePatch { + lifecycle: Some(NoteLifecycle::Expires { at: later() }), + ..NotePatch::default() + }, + |n| n.lifecycle == NoteLifecycle::Expires { at: later() }, + ), + ]; - #[test] - fn turning_a_draft_into_a_note_leaves_everything_else_alone() { - let note = draft(Language::Md, "SELECT 1").into_note("n-7".to_string(), now()); + for (patch, written) in cases { + let edited = patched(note(), &patch); - assert_eq!(note.language, Language::Md); - assert_eq!(note.content, "SELECT 1"); - assert_eq!(note.space_id, "s-1"); - assert_eq!(note.source, "API Gateway"); - assert!(note.pinned); + assert!(written(&edited), "{patch:?}"); + assert_eq!(edited.updated_at, later(), "{patch:?}"); + assert_eq!(edited.created_at, at(NOW)); + } } #[test] - fn a_patch_only_touches_the_fields_it_carries() { - let mut note = sample(); + fn a_field_written_back_as_it_was_is_no_edit() { + let same = note(); let patch = NotePatch { - title: Some("New".to_string()), + space_id: Some(same.space_id.clone()), + title: Some(same.title.clone()), + content: Some(same.content.clone()), + tags: Some(strings(&[" #auth "])), + pinned: Some(same.pinned), ..NotePatch::default() }; - patch.apply(&mut note, at("2026-07-25T10:00:00.000Z")); + let edited = patched(same, &patch); - assert_eq!(note.title, "New"); - assert_eq!(note.content, "Content"); - assert_eq!(note.tags, ["auth"]); - assert_eq!(note.updated_at, at("2026-07-25T10:00:00.000Z")); - assert_eq!(note.created_at, now()); + assert_eq!(edited.updated_at, at(NOW)); + assert_eq!(edited.tags, ["auth"]); } #[test] - fn a_patch_that_changes_nothing_leaves_the_date_alone() { - let mut note = sample(); + fn pictures_alone_are_no_edit_of_the_note() { let patch = NotePatch { - title: Some(note.title.clone()), - content: Some(note.content.clone()), - tags: Some(vec!["#auth".to_string()]), + pictures: Some(drawing::DrawingPictures::default()), ..NotePatch::default() }; - patch.apply(&mut note, at("2026-07-25T10:00:00.000Z")); - - assert_eq!(note.updated_at, now()); + assert_eq!(patched(note(), &patch), note()); } #[test] - fn a_patch_normalizes_the_tags_it_replaces() { - let mut note = sample(); + fn a_patch_s_tags_and_items_are_brought_to_the_rules() { let patch = NotePatch { - tags: Some(vec![ - " #Ops ".to_string(), - "OPS".to_string(), - " ".to_string(), - ]), + tags: Some(strings(&["##ci", "CI", " "])), + items: Some(vec![item(" x ", false), item("", true)]), ..NotePatch::default() }; - patch.apply(&mut note, now()); + let edited = patched(note(), &patch); - assert_eq!(note.tags, ["Ops"]); + assert_eq!(edited.tags, ["ci"]); + assert_eq!(edited.items, [item("x", false)]); } #[test] - fn typing_into_an_empty_note_keeps_it_a_note() { - let mut note = Note { - kind: NoteKind::Note, - content: String::new(), - ..sample() + fn moving_to_another_space_leaves_the_folder_and_staying_keeps_it() { + let filed = Note { + folder_id: Some("f-1".into()), + ..note() }; - let patch = NotePatch { - content: Some("## Standup\n\nSELECT 1 is slow".to_string()), + let moving = NotePatch { + space_id: Some("s-2".into()), + ..NotePatch::default() + }; + let staying = NotePatch { + space_id: Some(filed.space_id.clone()), ..NotePatch::default() }; - patch.apply(&mut note, now()); - - assert_eq!(note.kind, NoteKind::Note); - assert_eq!(note.language, Language::Txt); + assert_eq!(patched(filed.clone(), &moving).folder_id, None); + assert_eq!(patched(filed, &staying).folder_id.as_deref(), Some("f-1")); } #[test] - fn a_patch_filling_an_empty_snippet_detects_its_language() { - let mut note = Note { - language: Language::Txt, - content: String::new(), - ..sample() + fn a_note_leaving_the_snippets_loses_its_language() { + let snippet = Note { + language: Language::Py, + ..of_kind(NoteKind::Snippet, PYTHON) }; let patch = NotePatch { - content: Some("SELECT 1".to_string()), + kind: Some(NoteKind::Note), + language: Some(Language::Py), ..NotePatch::default() }; - patch.apply(&mut note, now()); - - assert_eq!(note.language, Language::Sql); + assert_eq!(patched(snippet, &patch).language, Language::Txt); } #[test] - fn a_patch_gives_a_note_no_language() { - let mut note = Note { - kind: NoteKind::Note, - ..sample() + fn an_empty_snippet_s_first_content_decides_its_language() { + let empty = of_kind(NoteKind::Snippet, " "); + let patch = NotePatch { + content: Some(PYTHON.into()), + ..NotePatch::default() }; + + assert_eq!(patched(empty, &patch).language, Language::Py); + } + + #[test] + fn a_language_already_there_or_chosen_is_not_detected_over() { let patch = NotePatch { - language: Some(Language::Sql), + content: Some(PYTHON.into()), ..NotePatch::default() }; + let chosen = NotePatch { + language: Some(Language::Sh), + ..patch.clone() + }; + let written = of_kind(NoteKind::Snippet, "echo hi"); + let set = Note { + language: Language::Rs, + ..of_kind(NoteKind::Snippet, "") + }; - patch.apply(&mut note, now()); + assert_eq!(patched(written, &patch).language, Language::Txt); + assert_eq!(patched(set, &patch).language, Language::Rs); + assert_eq!( + patched(of_kind(NoteKind::Snippet, ""), &chosen).language, + Language::Sh + ); + } + + #[test] + fn a_note_written_as_prose_is_not_read_for_a_language() { + let patch = NotePatch { + content: Some(PYTHON.into()), + ..NotePatch::default() + }; - assert_eq!(note.language, Language::Txt); + for kind in [NoteKind::Note, NoteKind::Checklist] { + assert_eq!( + patched(of_kind(kind, ""), &patch).language, + Language::Txt, + "{kind}" + ); + } } - /// Code pasted into an empty Note: the note leaves for the code field. #[test] fn a_note_turned_into_a_snippet_takes_the_language_it_is_given() { - let mut note = Note { - kind: NoteKind::Note, - content: String::new(), - ..sample() - }; let patch = NotePatch { kind: Some(NoteKind::Snippet), language: Some(Language::Sql), - content: Some("SELECT 1".to_string()), + content: Some("SELECT 1".into()), ..NotePatch::default() }; - patch.apply(&mut note, now()); + let edited = patched(of_kind(NoteKind::Note, ""), &patch); - assert_eq!(note.kind, NoteKind::Snippet); - assert_eq!(note.language, Language::Sql); + assert_eq!( + (edited.kind, edited.language), + (NoteKind::Snippet, Language::Sql) + ); } - const DRAWING: &str = r#"{"scene":{"objects":[{"type":"Textbox","text":"Fill {{host}}"}]}}"#; + // --- What a card shows. - /// Its scene is no text a card could draw: nothing of the body goes, and the card asks for - /// its picture. #[test] - fn a_drawing_reaches_a_card_without_its_scene() { - let mut note = decorate( + fn the_footer_is_the_deadline_then_the_source_s_root_then_the_age() { + let expiring = Note { + lifecycle: NoteLifecycle::Expires { at: later() }, + source: "API / Auth".into(), + ..note() + }; + // Unpinned: the source was once shown on pinned notes alone. + let sourced = Note { + source: "API Gateway / Auth / Tokens".into(), + pinned: false, + ..note() + }; + let blank_root = Note { + source: " / Auth".into(), + ..note() + }; + + assert_eq!( + decorate(expiring, at(NOW)).footer, + NoteFooter::Expiry { at: later() } + ); + assert_eq!( + decorate(sourced, at(NOW)).footer, + NoteFooter::Source { + value: "API Gateway".into() + } + ); + assert_eq!( + decorate(blank_root, at(NOW)).footer, + NoteFooter::Age { at: at(NOW) } + ); + assert_eq!( + decorate(note(), at(NOW)).footer, + NoteFooter::Age { at: at(NOW) } + ); + } + + #[test] + fn a_list_by_creation_dates_the_age_from_creation_and_leaves_the_rest() { + let edited = Note { + created_at: at("2026-01-01T00:00:00.000Z"), + ..note() + }; + let mut aged = decorate(edited.clone(), at(NOW)); + let mut sourced = decorate( Note { - kind: NoteKind::Drawing, - content: DRAWING.to_string(), - ..sample() + source: "API".into(), + ..edited }, - now(), + at(NOW), ); - note.cut_to_preview(chrono::NaiveDate::MIN); + aged.dated_by_creation(); + sourced.dated_by_creation(); - assert_eq!(note.content, ""); - assert!(note.truncated); + assert_eq!( + aged.footer, + NoteFooter::Created { + at: at("2026-01-01T00:00:00.000Z") + } + ); + assert_eq!( + sourced.footer, + NoteFooter::Source { + value: "API".into() + } + ); } #[test] - fn a_drawing_reads_as_its_words_and_holds_no_field_to_fill() { - let note = Note { - kind: NoteKind::Drawing, - content: DRAWING.to_string(), - ..sample() - }; + fn a_note_expires_soon_from_three_days_before_its_deadline() { + let now = at(NOW); + let three_days = TimeDelta::days(3); + let one_second = TimeDelta::seconds(1); + + for (deadline, soon) in [ + (now + three_days + one_second, false), + (now + three_days, true), + (now, true), + (now - three_days, true), + ] { + let expiring = Note { + lifecycle: NoteLifecycle::Expires { at: deadline }, + ..note() + }; - assert_eq!(note.readable_body(), "Fill {{host}}"); - let shown = decorate(note, now()); - assert!(shown.placeholders.is_empty()); - assert_eq!(shown.copy_text, None); + assert_eq!(expires_soon(&expiring, now), soon, "{deadline}"); + assert_eq!(decorate(expiring, now).expiring_soon, soon); + } + assert!(!expires_soon(¬e(), now)); } - /// Cut even when it fits, so the list never passes the words off as the Markdown. #[test] - fn a_note_reaches_a_card_without_its_markdown() { - let mut note = decorate( - Note { - kind: NoteKind::Note, - content: "- [x] **ship** it".to_string(), - ..sample() - }, - now(), - ); - - note.cut_to_preview(chrono::NaiveDate::MIN); + fn a_card_lists_the_fields_of_its_text_with_their_stored_values() { + let snippet = Note { + content: "ssh {{user}}@{{host=db}}".into(), + placeholder_values: [("user".to_string(), "ada".to_string())].into(), + ..note() + }; - assert_eq!(note.content, "☑ ship it"); - assert!(note.truncated); - assert_eq!( - note.outline, - [OutlineLine::Task { - text: "ship it".to_string(), - depth: 0, - done: true - }] - ); + let fields = decorate(snippet, at(NOW)).placeholders; + + let found: Vec<_> = fields + .iter() + .map(|field| { + ( + field.name.as_str(), + field.value.as_str(), + field.default_value.as_str(), + ) + }) + .collect(); + assert_eq!(found, [("user", "ada", ""), ("host", "", "db")]); } #[test] - fn a_notes_card_draws_its_heading_and_its_items() { - let mut note = decorate( - Note { - kind: NoteKind::Note, - content: "## Décisions\n\n- Bascule le 14/10\n- Réplica d'abord".to_string(), - ..sample() - }, - now(), + fn words_written_on_a_drawing_are_no_field() { + let drawing = of_kind( + NoteKind::Drawing, + r#"{"scene":{"objects":[{"text":"{{host}}"}]}}"#, ); - note.cut_to_preview(chrono::NaiveDate::MIN); + assert!(decorate(drawing, at(NOW)).placeholders.is_empty()); + } - let item = |text: &str| OutlineLine::Item { - text: text.to_string(), - depth: 0, - marker: "•".to_string(), + #[test] + fn only_a_todo_list_copies_as_something_other_than_its_body() { + let list = Note { + items: vec![item("a", true)], + ..of_kind(NoteKind::Checklist, "") }; + assert_eq!( - note.outline, - [ - OutlineLine::Heading { - text: "Décisions".to_string() - }, - item("Bascule le 14/10"), - item("Réplica d'abord"), - ] + decorate(list, at(NOW)).copy_text.as_deref(), + Some("- [x] a") ); + for kind in [ + NoteKind::Snippet, + NoteKind::Note, + NoteKind::Calc, + NoteKind::Drawing, + ] { + assert_eq!( + decorate(of_kind(kind, "x"), at(NOW)).copy_text, + None, + "{kind}" + ); + } } - /// A code block is one entry of several lines: the card's room is counted in lines. #[test] - fn a_notes_card_holds_as_many_lines_as_any_card() { - let body = format!("# Title\n\n```sh\n{}\n```", ["one"; 9].join("\n")); - let mut note = decorate( - Note { - kind: NoteKind::Note, - content: body, - ..sample() - }, - now(), - ); - - note.cut_to_preview(chrono::NaiveDate::MIN); - - assert_eq!(note.outline.len(), 2); - let OutlineLine::Code { text } = ¬e.outline[1] else { - panic!("the second line is the code block"); + fn a_global_variable_becomes_a_field_s_default_and_never_its_value() { + let snippet = Note { + content: "{{host=localhost}} {{port}}".into(), + placeholder_values: [("port".to_string(), "6543".to_string())].into(), + ..note() }; - assert_eq!(text.lines().count(), PREVIEW_LINES - 1); + let globals = [ + ("host".to_string(), "db".to_string()), + ("port".to_string(), "5432".to_string()), + ("unused".to_string(), "x".to_string()), + ] + .into(); + let mut shown = decorate(snippet, at(NOW)); + + apply_global_defaults(&mut shown, &globals); + + let found: Vec<_> = shown + .placeholders + .iter() + .map(|field| { + ( + field.name.as_str(), + field.value.as_str(), + field.default_value.as_str(), + ) + }) + .collect(); + assert_eq!(found, [("host", "", "db"), ("port", "6543", "5432")]); } + // --- A list sends previews. + #[test] - fn a_snippets_card_has_no_outline() { - let mut note = decorate( - Note { - content: "# not a heading, a comment".to_string(), - language: Language::Sh, - ..sample() - }, - now(), - ); + fn a_body_that_fits_the_card_is_sent_whole() { + let lines = ["1", "2", "3", "4", "5"].join("\n"); + let chars = "x".repeat(PREVIEW_CHARS); - note.cut_to_preview(chrono::NaiveDate::MIN); + for body in [lines, chars, String::new()] { + let shown = preview(of_kind(NoteKind::Snippet, &body)); - assert!(note.outline.is_empty()); + assert_eq!(shown.content, body); + assert!(!shown.truncated); + } } #[test] - fn a_text_snippet_keeps_its_markdown_characters_on_a_card() { - let mut note = decorate( - Note { - language: Language::Txt, - content: "- [x] **ship** it".to_string(), - ..sample() - }, - now(), - ); - - note.cut_to_preview(chrono::NaiveDate::MIN); + fn a_body_past_five_lines_is_cut_to_five() { + let shown = preview(of_kind(NoteKind::Snippet, "1\n2\n3\n4\n5\n6")); - assert_eq!(note.content, "- [x] **ship** it"); - assert!(!note.truncated); + assert_eq!(shown.content, "1\n2\n3\n4\n5"); + assert!(shown.truncated); } #[test] - fn a_snippet_keeps_its_characters_on_a_card() { - let mut note = decorate( - Note { - language: Language::Sh, - content: "echo **not bold**".to_string(), - ..sample() - }, - now(), - ); - - note.cut_to_preview(chrono::NaiveDate::MIN); + fn a_body_past_a_thousand_characters_is_cut_on_a_character() { + let shown = preview(of_kind(NoteKind::Snippet, &"é".repeat(PREVIEW_CHARS + 1))); - assert_eq!(note.content, "echo **not bold**"); - assert!(!note.truncated); + assert_eq!(shown.content, "é".repeat(PREVIEW_CHARS)); + assert!(shown.truncated); } #[test] - fn an_ordinary_note_shows_the_age_of_its_last_change() { - let footer = footer_of(&sample()); + fn a_note_s_preview_is_its_words_and_its_card_lines() { + let shown = preview(of_kind(NoteKind::Note, "# Plan\n\n- [x] **ship**")); - assert_eq!(footer, NoteFooter::Age { at: at(NOW) }); + assert_eq!(shown.content, "Plan\n☑ ship"); + assert!(shown.truncated); + assert_eq!( + shown.outline, + [ + OutlineLine::Heading { + text: "Plan".into() + }, + OutlineLine::Task { + text: "ship".into(), + depth: 0, + done: true + }, + ] + ); } #[test] - fn only_a_snippet_is_given_a_guessed_language() { - for kind in [NoteKind::Checklist, NoteKind::Note] { - let draft = NoteDraft { - kind, - content: "{ \"a\": 1 }".to_string(), - ..draft(Language::Txt, "") - }; - - let note = draft.into_note("n-2".to_string(), now()); + fn a_note_without_markup_that_fits_is_sent_whole() { + let shown = preview(of_kind(NoteKind::Note, "Just words.")); - assert_eq!(note.language, Language::Txt, "{kind}"); - } + assert_eq!(shown.content, "Just words."); + assert!(!shown.truncated); } #[test] - fn turning_a_note_into_a_checklist_does_not_trigger_a_detection() { - let mut note = Note { - language: Language::Txt, - content: String::new(), - ..sample() - }; - let patch = NotePatch { - kind: Some(NoteKind::Checklist), - content: Some("{ \"a\": 1 }".to_string()), - ..NotePatch::default() - }; + fn a_note_s_card_lines_stop_at_five_rows_a_code_block_counting_each_of_its_own() { + let body = "intro\n\n```\na\nb\nc\nd\ne\n```\n\nafter"; - patch.apply(&mut note, now()); + let shown = preview(of_kind(NoteKind::Note, body)); - assert_eq!(note.language, Language::Txt); + assert_eq!( + shown.outline, + [ + OutlineLine::Text { + text: "intro".into() + }, + OutlineLine::Code { + text: "a\nb\nc\nd".into() + }, + ] + ); } #[test] - fn a_patch_replaces_the_whole_item_list_and_normalizes_it() { - let mut note = Note { - items: vec![ChecklistItem { - text: "Old".to_string(), - done: true, - }], - ..sample() - }; - let patch = NotePatch { - items: Some(vec![ - ChecklistItem { - text: " Ship it ".to_string(), - done: false, - }, - ChecklistItem { - text: " ".to_string(), - done: false, - }, - ]), - ..NotePatch::default() - }; + fn a_note_s_card_lines_stop_at_a_thousand_characters() { + let body = format!("{}\n\n{}\n\nlast", "a".repeat(600), "b".repeat(600)); - patch.apply(&mut note, now()); + let shown = preview(of_kind(NoteKind::Note, &body)); assert_eq!( - note.items, - [ChecklistItem { - text: "Ship it".to_string(), - done: false - }] + shown.outline, + [ + OutlineLine::Text { + text: "a".repeat(600) + }, + OutlineLine::Text { + text: "b".repeat(400) + }, + ] ); } #[test] - fn a_patch_that_says_nothing_about_the_items_leaves_them_alone() { - let mut note = Note { - items: vec![ChecklistItem { - text: "Ship it".to_string(), - done: true, - }], - ..sample() - }; + fn a_drawing_sends_no_body_to_a_list() { + let shown = preview(of_kind(NoteKind::Drawing, r#"{"scene":{"objects":[]}}"#)); - NotePatch { - title: Some("T".to_string()), - ..NotePatch::default() - } - .apply(&mut note, now()); + assert_eq!(shown.content, ""); + assert!(shown.truncated); + } - assert_eq!(note.items.len(), 1); + #[test] + fn a_sheet_s_card_lines_are_read_from_the_whole_sheet_before_it_is_cut() { + let sheet = (1..=8) + .map(|n| n.to_string()) + .collect::>() + .join("\n"); + + let shown = preview(of_kind(NoteKind::Calc, &sheet)); + + let expressions: Vec<_> = shown + .calc + .iter() + .map(|line| line.expression.as_str()) + .collect(); + assert_eq!(expressions, ["5", "6", "7", "8"]); + assert_eq!(shown.content, "1\n2\n3\n4\n5"); } - /// Shown for pinned notes alone, a context typed under the title was nowhere on its card (COD-21). #[test] - fn a_note_shows_the_first_segment_of_its_context_pinned_or_not() { - for pinned in [true, false] { - let note = Note { - pinned, - source: "API Gateway / Auth / Tokens".to_string(), - ..sample() - }; + fn a_snippet_keeps_its_markdown_characters_on_a_card() { + let shown = preview(of_kind(NoteKind::Snippet, "- [x] **ship** it")); - assert_eq!( - footer_of(¬e), - NoteFooter::Source { - value: "API Gateway".to_string() - } - ); - } + assert_eq!(shown.content, "- [x] **ship** it"); + assert!(!shown.truncated); } #[test] - fn a_note_without_context_falls_back_to_its_age() { - let note = Note { - pinned: true, - source: String::new(), - ..sample() - }; - - assert!(matches!(footer_of(¬e), NoteFooter::Age { .. })); + fn the_fields_are_read_from_the_whole_body_before_it_is_cut() { + let shown = preview(of_kind( + NoteKind::Snippet, + "1\n2\n3\n4\n5\npsql -h {{host}}", + )); + + assert_eq!(shown.placeholders[0].name, "host"); + assert!(shown.truncated); } #[test] - fn an_expiring_note_shows_its_deadline_even_when_pinned() { - let note = Note { - pinned: true, - source: "API Gateway".to_string(), - ..expiring("2026-08-01T00:00:00.000Z") - }; + fn only_a_sheet_has_card_results_and_only_a_note_card_lines() { + let snippet = preview(of_kind(NoteKind::Snippet, "1 + 1\n# x")); - assert!(matches!(footer_of(¬e), NoteFooter::Expiry { .. })); + assert!(snippet.calc.is_empty()); + assert!(snippet.outline.is_empty()); } + // --- The note itself. + #[test] - fn a_permanent_note_never_counts_as_expiring_soon() { - assert!(!expires_soon(&sample(), now())); + fn the_readable_body_is_what_a_card_shows_and_a_search_quotes() { + let drawing = r#"{"scene":{"objects":[{"text":"API"}]}}"#; + + for (kind, content, readable) in [ + (NoteKind::Note, "**bold** words", "bold words"), + (NoteKind::Drawing, drawing, "API"), + (NoteKind::Snippet, "**as is**", "**as is**"), + (NoteKind::Calc, "2 * 3", "2 * 3"), + (NoteKind::Checklist, "", ""), + ] { + assert_eq!(of_kind(kind, content).readable_body(), readable, "{kind}"); + } } #[test] - fn the_threshold_is_measured_in_fractions_of_a_day() { - assert!(!expires_soon(&expiring("2026-07-28T10:00:00.000Z"), now())); - assert!(expires_soon(&expiring("2026-07-28T08:00:00.000Z"), now())); + fn only_a_note_is_rich_text() { + for kind in NoteKind::ALL { + assert_eq!( + of_kind(kind, "").is_rich_text(), + kind == NoteKind::Note, + "{kind}" + ); + } } #[test] - fn an_already_expired_note_counts_as_expiring_soon() { - assert!(expires_soon(&expiring("2026-07-01T00:00:00.000Z"), now())); + fn an_imported_note_is_brought_to_the_rules() { + let imported = Note { + tags: strings(&["#a", "A", ""]), + items: vec![item(" x ", false), item(" ", false)], + placeholder_values: [ + ("host".to_string(), "db".to_string()), + ("port".to_string(), String::new()), + ("user.name".to_string(), "x".to_string()), + ] + .into(), + ..note() + }; + + let normalized = imported.normalized(); + + assert_eq!(normalized.tags, ["a"]); + assert_eq!(normalized.items, [item("x", false)]); + assert_eq!( + normalized.placeholder_values, + [("host".to_string(), "db".to_string())].into() + ); } - /// A snippet's: a Note's preview is its words, tested on their own. - fn previewed(content: &str) -> DisplayNote { - let mut note = decorate( + #[test] + fn a_duplicate_says_everything_the_note_says_under_a_new_id_and_title_unpinned_and_dated_now() { + let original = Note { + pinned: true, + folder_id: Some("f-1".into()), + priority: Priority::Urgent, + items: vec![item("a", true)], + placeholder_values: [("host".to_string(), "db".to_string())].into(), + ..note() + }; + + let copy = original + .clone() + .duplicate("n-2".into(), "Copy".into(), later()); + + assert_eq!( + copy, Note { - language: Language::Sh, - content: content.to_string(), - ..sample() - }, - now(), + id: "n-2".into(), + title: "Copy".into(), + pinned: false, + created_at: later(), + updated_at: later(), + ..original + } ); - note.cut_to_preview(chrono::NaiveDate::MIN); - - note } - #[test] - fn a_body_that_fits_is_sent_whole_and_not_marked() { - for body in ["", "one", "1\n2\n3\n4\n5"] { - let note = previewed(body); + // --- Tags. - assert_eq!(note.content, body); - assert!(!note.truncated); + #[test] + fn a_tag_is_trimmed_of_spaces_and_leading_hashes() { + for (raw, tag) in [ + ("urgent", Some("urgent")), + (" #urgent ", Some("urgent")), + ("## urgent", Some("urgent")), + ("c#", Some("c#")), + ("a b", Some("a b")), + ("", None), + (" ## ", None), + ] { + assert_eq!(normalize_tag(raw), tag, "{raw:?}"); } } #[test] - fn a_long_body_keeps_the_lines_a_card_shows() { - let note = previewed("1\n2\n3\n4\n5\n6\n7"); + fn tags_are_kept_once_each_folding_case_and_keeping_the_first_spelling_and_order() { + let tags = normalize_tags(&strings(&[ + "Rust", "#ops", "rust", " ", "OPS", "Été", "été", + ])); - assert_eq!(note.content, "1\n2\n3\n4\n5"); - assert!(note.truncated); + assert_eq!(tags, ["Rust", "ops", "Été"]); } #[test] - fn one_long_line_is_cut_on_a_character_boundary() { - let note = previewed(&"é".repeat(PREVIEW_CHARS * 3)); + fn a_tag_with_nothing_readable_is_refused_as_a_tag() { + assert_eq!(validated_tag(" #ci "), Ok("ci".to_string())); + assert_eq!(validated_tag(" # ").unwrap_err().field, "tag"); + } - assert_eq!(note.content.chars().count(), PREVIEW_CHARS); - assert!(note.truncated); + #[test] + fn a_rename_normalises_its_sources_and_refuses_an_unreadable_target() { + assert_eq!( + retagging(&strings(&["#a", "A", "b"]), "#c"), + Ok((strings(&["a", "b"]), "c".to_string())) + ); + assert_eq!(retagging(&strings(&["a"]), "#").unwrap_err().field, "tag"); } - /// Read before the cut: a list must still know a snippet has fields past its first lines. + // --- What is exported. + #[test] - fn the_fields_are_found_in_the_whole_body() { - let note = previewed("1\n2\n3\n4\n5\npsql -h {{host}}"); + fn a_note_is_written_in_camel_case_its_lifecycle_tagged_by_kind() { + let expiring = Note { + lifecycle: NoteLifecycle::Expires { at: later() }, + ..note() + }; + + let json = serde_json::to_value(&expiring).unwrap(); - assert_eq!(note.placeholders[0].name, "host"); + assert_eq!(json["spaceId"], "s-1"); + assert!(json.get("folderId").is_some()); + assert!(json.get("createdAt").is_some() && json.get("placeholderValues").is_some()); + assert_eq!(json["lifecycle"]["kind"], "expires"); + assert_eq!( + serde_json::to_value(note()).unwrap()["lifecycle"]["kind"], + "permanent" + ); + assert_eq!(serde_json::from_value::(json).unwrap(), expiring); } -} -/// What deleting a space or a folder does to the notes it holds: they live on elsewhere, or go to -/// the trash with it. Never erased: only emptying the trash, or its retention, is final. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub enum HeldNotes { - #[default] - Keep, - Trash, + #[test] + fn a_note_from_an_older_export_reads_back_with_the_defaults_of_what_it_lacks() { + let mut json = serde_json::to_value(note()).unwrap(); + let object = json.as_object_mut().unwrap(); + for key in ["folderId", "kind", "priority", "items", "placeholderValues"] { + object.remove(key); + } + + let read = serde_json::from_value::(json).unwrap(); + + assert_eq!(read.folder_id, None); + assert_eq!(read.kind, NoteKind::Snippet); + assert_eq!(read.priority, Priority::None); + assert!(read.items.is_empty() && read.placeholder_values.is_empty()); + } } From d9af8edc7caa551236a128a5794fd4c468b40ef2 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 00:43:21 +0100 Subject: [PATCH 03/95] Rewrite the tests of the notes view around its rules (#1718) Criteria and rails, what a search answers and quotes, the orders, the sections and their create card, facets and what a card draws. --- crates/engine/src/notes/view.rs | 2099 ++++++++++++++----------------- 1 file changed, 936 insertions(+), 1163 deletions(-) diff --git a/crates/engine/src/notes/view.rs b/crates/engine/src/notes/view.rs index d68846620..6b5ecb423 100644 --- a/crates/engine/src/notes/view.rs +++ b/crates/engine/src/notes/view.rs @@ -945,31 +945,11 @@ fn build_sections( #[cfg(test)] mod tests { use super::*; + use crate::folders::model::FolderColour; use crate::notes::checklist::ChecklistItem; - use crate::notes::fixtures::{NOW, at, note as sample}; + use crate::notes::fixtures::{NOW, at, note}; - fn card(note: Note) -> Card { - Card::new(Arc::new(IndexedNote::of(note)), None) - } - - /// [`super::build_sections`] over notes just read. - fn build_sections( - notes: Vec, - layout: Layout, - pinned_first: bool, - now: DateTime, - offset: FixedOffset, - ) -> Vec { - let cards = notes.into_iter().map(card).collect(); - super::build_sections(cards, layout, pinned_first, now, offset) - } - - /// What the first card of `view` draws. - fn first_displayed(view: &NotesView) -> DisplayNote { - view.display(view.cards().next().unwrap()).clone() - } - - fn request() -> NotesQuery { + fn query() -> NotesQuery { NotesQuery { space_id: None, folder_id: None, @@ -980,7 +960,7 @@ mod tests { kinds: Vec::new(), priorities: Vec::new(), order: NoteOrder::default(), - grouping: Grouping::default(), + grouping: Grouping::Date, ranked: false, now: at(NOW), tz_offset_minutes: 0, @@ -988,1343 +968,1136 @@ mod tests { } } - fn note(id: &str, title: &str) -> Note { + fn searching(search: &str) -> NotesQuery { + NotesQuery { + search: search.into(), + ..query() + } + } + + fn titled(id: &str, title: &str) -> Note { Note { - id: id.to_string(), - title: title.to_string(), - created_at: at("2026-07-25T08:00:00.000Z"), - ..sample() + id: id.into(), + title: title.into(), + ..note() } } - fn keys(view: &NotesView) -> Vec { - view.sections.iter().map(|section| section.key).collect() + fn edited(id: &str, iso: &str) -> Note { + Note { + id: id.into(), + updated_at: at(iso), + created_at: at(iso), + ..note() + } } - #[test] - fn a_decoration_fills_the_counter_the_chip_and_the_proposed_values() { - let mut filed = model::decorate( - Note { - folder_id: Some("f-1".to_string()), - content: "ssh {{host}}".to_string(), - ..note("n-1", "Deploy") - }, - at(NOW), - ); - let decorations = Decorations { - attachment_counts: HashMap::from([("n-1".to_string(), 2)]), - folders: HashMap::from([( - "f-1".to_string(), - NoteFolder { - id: "f-1".to_string(), - name: "Ops".to_string(), - colour: crate::folders::model::FolderColour::nth(0), - path: vec!["Ops".to_string()], - }, - )]), - globals: BTreeMap::from([("host".to_string(), "db.internal".to_string())]), - }; + fn view(notes: Vec, request: &NotesQuery) -> NotesView { + build(notes, Facets::default(), request) + } - decorations.apply([&mut filed]); + fn ids(view: &NotesView) -> Vec { + view.cards().map(|card| card.id.clone()).collect() + } - assert_eq!(filed.attachment_count, 2); - assert_eq!( - filed.folder.map(|folder| folder.name), - Some("Ops".to_string()) - ); - assert_eq!(filed.placeholders[0].default_value, "db.internal"); + fn sections(view: &NotesView) -> Vec<(String, Vec)> { + view.sections + .iter() + .map(|section| { + let cards = section.cards.iter().map(|card| card.id.clone()).collect(); + (section.id.clone(), cards) + }) + .collect() } - #[test] - fn inside_an_opened_folder_a_chip_names_only_a_folder_below_it() { - let inside = NotesQuery { - folder_id: Some("f-1".to_string()), - ..request() - }; + fn ghosts(view: &NotesView) -> Vec { + view.sections + .iter() + .map(|section| section.show_create_ghost) + .collect() + } - assert!(request().keeps_chip(Some("f-1"))); - assert!(!request().keeps_chip(None)); - assert!(!inside.keeps_chip(Some("f-1"))); - assert!(inside.keeps_chip(Some("f-1a"))); + fn answered(target: &Note, needle: &str) -> bool { + answers(target, &Folded::of(target), &fold(needle)).is_some() } - #[test] - fn an_empty_search_keeps_every_note_and_reports_no_filtering() { - let view = build( - vec![note("a", "Un"), note("b", "Deux")], - Facets::default(), - &request(), - ); + /// `None` for a note found by its title, which needs no quote. + fn hit_field(target: &Note, needle: &str) -> Option<(SearchField, String)> { + answers(target, &Folded::of(target), &fold(needle)) + .expect("the note answers") + .map(|found| (found.field, found.excerpt)) + } - assert_eq!(view.matched, 2); - assert!(!view.is_filtering); - assert_eq!(keys(&view), [NoteSectionKey::Today, NoteSectionKey::Week]); + fn rails(filter: NoteFilter, tags: &[&str]) -> Criteria { + let tags: Vec = tags.iter().map(|tag| (*tag).to_string()).collect(); + Criteria::new("", filter, &tags, &[], &[], &[]) } + // --- Folding. + #[test] - fn a_search_narrows_the_notes_and_collapses_the_sections() { - let notes = vec![note("a", "Déploiement"), note("b", "Autre chose")]; + fn folding_lowers_the_case_and_takes_the_accents_away() { + for (text, folded) in [ + ("PSQL Host", "psql host"), + ("Étape Ça", "etape ca"), + ("e\u{301}te\u{301}", "ete"), + ("ÆØß", "æøß"), + ("", ""), + ] { + assert_eq!(fold(text), folded, "{text}"); + } + } - let view = build( - notes, - Facets::default(), - &NotesQuery { - search: " DEPLOI ".to_string(), - ..request() - }, - ); + // --- The criteria: search, quick filter and rails. + + #[test] + fn the_needle_is_the_search_trimmed_and_folded() { + let criteria = Criteria::new(" Étape ", NoteFilter::All, &[], &[], &[], &[]); - assert_eq!(view.matched, 1); - assert!(view.is_filtering); - assert_eq!(keys(&view), [NoteSectionKey::Results]); + assert_eq!(criteria.needle(), "etape"); } - /// `psql` opened the note edited last that held it in its body, « Connexion psql » fourth. #[test] - fn the_palette_ranks_by_how_the_title_answers_the_search_then_by_date() { - let edited = |id: &str, title: &str, content: &str, when: &str| Note { - content: content.to_string(), - updated_at: at(when), - ..note(id, title) - }; - let notes = vec![ - edited( - "body", - "zq-champs", - "psql -h db", - "2026-07-25T12:00:00.000Z", - ), - edited("word", "Connexion psql", "", "2026-07-20T08:00:00.000Z"), - edited("start", "PSQL au quotidien", "", "2026-07-21T08:00:00.000Z"), - edited("whole", "psql", "", "2026-07-19T08:00:00.000Z"), - edited("inside", "Lancerpsql", "", "2026-07-24T08:00:00.000Z"), - edited("older-body", "Autre", "psql", "2026-07-01T08:00:00.000Z"), + fn the_search_and_each_rail_narrow_and_the_quick_filter_does_not() { + let tags = ["ops".to_string()]; + let narrowing = [ + Criteria::new("x", NoteFilter::All, &[], &[], &[], &[]), + Criteria::new("", NoteFilter::All, &tags, &[], &[], &[]), + Criteria::new("", NoteFilter::All, &[], &[Language::Py], &[], &[]), + Criteria::new("", NoteFilter::All, &[], &[], &[NoteKind::Note], &[]), + Criteria::new("", NoteFilter::All, &[], &[], &[], &[Priority::High]), ]; - let ids = |view: &NotesView| -> Vec { - view.sections - .iter() - .flat_map(|section| section.cards.iter().map(|card| card.id.clone())) - .collect() - }; - - let ranked = build( - notes.clone(), - Facets::default(), - &NotesQuery { - search: "psql".to_string(), - ranked: true, - ..request() - }, - ); - assert_eq!( - ids(&ranked), - ["whole", "start", "word", "inside", "body", "older-body"] - ); - let dated = build( - notes, - Facets::default(), - &NotesQuery { - search: "psql".to_string(), - ..request() - }, - ); - assert_eq!(ids(&dated)[0], "body", "the list view keeps its own order"); + for criteria in narrowing { + assert!(criteria.narrows(), "{criteria:?}"); + } + assert!(!Criteria::new(" ", NoteFilter::Pinned, &[], &[], &[], &[]).narrows()); } #[test] - fn a_selected_tag_counts_as_filtering_even_with_no_search() { - let view = build( - vec![note("a", "Un")], - Facets::default(), - &NotesQuery { - tags: vec!["urgent".to_string()], - ..request() - }, - ); + fn the_quick_filter_keeps_the_pinned_or_the_notes_with_a_deadline() { + let pinned = Note { + pinned: true, + ..note() + }; + let expiring = Note { + lifecycle: NoteLifecycle::Expires { at: at(NOW) }, + ..note() + }; - assert!(view.is_filtering); - assert_eq!(keys(&view), [NoteSectionKey::Results]); + for (filter, target, passes) in [ + (NoteFilter::All, note(), true), + (NoteFilter::Pinned, pinned.clone(), true), + (NoteFilter::Pinned, note(), false), + (NoteFilter::Untriaged, expiring, true), + (NoteFilter::Untriaged, pinned, false), + ] { + assert_eq!( + rails(filter, &[]).passes_rails(&target), + passes, + "{filter:?}" + ); + } } #[test] - fn an_opened_folder_is_a_flat_grid_rather_than_dated_sections() { - let view = build( - vec![note("a", "Un"), note("b", "Deux")], - Facets::default(), - &NotesQuery { - folder_id: Some("f-1".to_string()), - ..request() - }, - ); + fn a_tag_rail_keeps_a_note_carrying_any_of_its_tags_whatever_the_ascii_case() { + let tagged = Note { + tags: vec!["Ops".into(), "deploy".into()], + ..note() + }; - assert!(view.is_filtering); - assert_eq!(keys(&view), [NoteSectionKey::Results]); - assert_eq!(view.matched, 2); + assert!(rails(NoteFilter::All, &["#ops"]).passes_rails(&tagged)); + assert!(rails(NoteFilter::All, &["ci", "DEPLOY"]).passes_rails(&tagged)); + assert!(!rails(NoteFilter::All, &["ci"]).passes_rails(&tagged)); } + /// `note_tags.tag` is `COLLATE NOCASE`, which folds ASCII and nothing else. #[test] - fn an_empty_folder_still_offers_the_slot_a_note_is_created_from() { - let view = build( - Vec::new(), - Facets::default(), - &NotesQuery { - folder_id: Some("f-1".to_string()), - ..request() - }, - ); + fn a_tag_beyond_ascii_matches_only_in_its_own_case() { + let tagged = Note { + tags: vec!["étape".into()], + ..note() + }; - assert_eq!(view.matched, 0); - assert_eq!(keys(&view), [NoteSectionKey::Results]); - assert!(view.sections[0].cards.is_empty()); - assert!(view.offers_creation()); + assert!(rails(NoteFilter::All, &["étape"]).passes_rails(&tagged)); + assert!(!rails(NoteFilter::All, &["Étape"]).passes_rails(&tagged)); } #[test] - fn a_search_that_finds_nothing_offers_nothing_to_create() { - let view = build( - vec![note("a", "Un")], - Facets::default(), - &NotesQuery { - search: "absent".to_string(), - ..request() - }, - ); + fn a_tag_rail_reduced_to_nothing_narrows_nothing() { + let criteria = rails(NoteFilter::All, &[" # "]); - assert_eq!(view.matched, 0); - assert!(!view.offers_creation()); + assert!(!criteria.narrows()); + assert!(criteria.passes(&Note { + tags: vec![], + ..note() + })); } #[test] - fn an_opened_folder_keeps_the_slot_a_note_is_created_from() { - let view = build( - vec![note("a", "Un")], - Facets::default(), - &NotesQuery { - folder_id: Some("f-1".to_string()), - ..request() - }, - ); + fn a_language_rail_keeps_only_snippets_of_those_languages() { + let criteria = Criteria::new("", NoteFilter::All, &[], &[Language::Txt], &[], &[]); + let text_snippet = note(); + let prose = Note { + kind: NoteKind::Note, + ..note() + }; - assert_eq!(keys(&view), [NoteSectionKey::Results]); - assert!(view.sections[0].show_create_ghost); + assert!(criteria.passes_rails(&text_snippet)); + assert!(!criteria.passes_rails(&prose)); + assert!( + !Criteria::new("", NoteFilter::All, &[], &[Language::Py], &[], &[]) + .passes_rails(&text_snippet) + ); } #[test] - fn a_search_inside_a_folder_offers_nothing_to_create() { - let view = build( - vec![note("a", "Un")], - Facets::default(), - &NotesQuery { - folder_id: Some("f-1".to_string()), - search: "Un".to_string(), - ..request() - }, - ); + fn the_kind_and_priority_rails_keep_the_notes_of_those_values() { + let urgent_list = Note { + kind: NoteKind::Checklist, + priority: Priority::Urgent, + ..note() + }; + let by_kind = |kinds: &[NoteKind]| Criteria::new("", NoteFilter::All, &[], &[], kinds, &[]); + let by_priority = + |priorities: &[Priority]| Criteria::new("", NoteFilter::All, &[], &[], &[], priorities); - assert_eq!(keys(&view), [NoteSectionKey::Results]); - assert!(!view.sections[0].show_create_ghost); + assert!(by_kind(&[NoteKind::Note, NoteKind::Checklist]).passes_rails(&urgent_list)); + assert!(!by_kind(&[NoteKind::Note]).passes_rails(&urgent_list)); + assert!(by_priority(&[Priority::Urgent]).passes_rails(&urgent_list)); + assert!(!by_priority(&[Priority::Low]).passes_rails(&urgent_list)); } - /// A facet narrows a list; it does not name a place. #[test] - fn a_selected_facet_offers_nothing_to_create_either() { - let view = build( - vec![note("a", "Un")], - Facets::default(), - &NotesQuery { - folder_id: Some("f-1".to_string()), - languages: vec![Language::Json], - ..request() - }, - ); + fn a_note_passes_when_every_rail_and_the_search_keep_it() { + let tags = ["auth".to_string()]; + let both = Criteria::new("content", NoteFilter::All, &tags, &[], &[], &[]); + let wrong_search = Criteria::new("absent", NoteFilter::All, &tags, &[], &[], &[]); + let wrong_rail = Criteria::new("content", NoteFilter::Pinned, &tags, &[], &[], &[]); - assert!(!view.sections[0].show_create_ghost); + assert!(both.passes(¬e())); + assert!(!wrong_search.passes(¬e())); + assert!(!wrong_rail.passes(¬e())); } - #[test] - fn no_folder_leaves_the_sections_exactly_as_they_were() { - let view = build( - vec![note("a", "Un")], - Facets::default(), - &NotesQuery { ..request() }, - ); + // --- What a search answers, and the quote it gives. - assert!(!view.is_filtering); - assert_ne!(keys(&view), [NoteSectionKey::Results]); + #[test] + fn a_note_found_by_its_title_needs_no_quote() { + assert_eq!(hit_field(&titled("n", "Connexion PSQL"), "psql"), None); } #[test] - fn a_tag_that_normalizes_to_nothing_does_not_count_as_filtering() { - let view = build( - vec![note("a", "Un")], - Facets::default(), - &NotesQuery { - tags: vec![" # ".to_string()], - ..request() - }, - ); + fn a_note_found_elsewhere_quotes_where_in_the_order_tag_body_item_source() { + let everywhere = Note { + title: "Nothing".into(), + tags: vec!["Postgres-prod".into()], + content: "first line\n psql -h postgres \nlast".into(), + items: vec![ChecklistItem { + text: "Back Postgres up".into(), + done: false, + }], + source: "Postgres / production".into(), + ..note() + }; + let without_tag = Note { + tags: vec![], + ..everywhere.clone() + }; + let without_body = Note { + content: String::new(), + ..without_tag.clone() + }; + let source_only = Note { + items: vec![], + ..without_body.clone() + }; - assert!(!view.is_filtering); + assert_eq!( + hit_field(&everywhere, "postgres"), + Some((SearchField::Tag, "Postgres-prod".into())) + ); + assert_eq!( + hit_field(&without_tag, "postgres"), + Some((SearchField::Body, "psql -h postgres".into())) + ); + assert_eq!( + hit_field(&without_body, "postgres"), + Some((SearchField::Item, "Back Postgres up".into())) + ); + assert_eq!( + hit_field(&source_only, "postgres"), + Some((SearchField::Source, "Postgres / production".into())) + ); } #[test] - fn a_fruitless_search_reports_filtering_with_zero_matches() { - let view = build( - vec![note("a", "Un")], - Facets::default(), - &NotesQuery { - search: "no-such-thing".to_string(), - ..request() - }, - ); - - assert_eq!(view.matched, 0); - assert!(view.is_filtering); + fn a_note_that_holds_the_search_nowhere_does_not_answer() { + assert!(!answered(¬e(), "absent")); + assert!(!matches_search(¬e(), "absent")); + assert!(matches_search(¬e(), "content")); } #[test] - fn the_rail_facets_are_passed_through_untouched() { - let view = build( - vec![note("a", "Un")], - Facets { - tags: count_tags(vec![("api".to_string(), 3), ("auth".to_string(), 1)]), - languages: count_languages(&[ - ("json".to_string(), 6), - ("klingon".to_string(), 9), - ("txt".to_string(), 2), - ]), - kinds: count_kinds(&[("note".to_string(), 2)]), - priorities: count_priorities(&[("high".to_string(), 1)]), - }, - &NotesQuery { - search: "no-such-thing".to_string(), - ..request() - }, - ); + fn a_search_reads_the_words_a_note_shows_and_not_its_markup_or_scene() { + let prose = Note { + kind: NoteKind::Note, + title: "t".into(), + content: "Ship **today**".into(), + ..note() + }; + let drawing = Note { + kind: NoteKind::Drawing, + title: "t".into(), + content: r#"{"scene":{"objects":[{"type":"textbox","text":"Gateway"}]}}"#.into(), + ..note() + }; - assert_eq!(view.available_tags, ["api", "auth"]); - assert_eq!(view.available_languages, [Language::Json, Language::Txt]); - // Format and tags count their notes too (REC-05), a language this build lacks left out. assert_eq!( - view.tag_counts - .iter() - .map(|tag| tag.count) - .collect::>(), - [3, 1] + hit_field(&prose, "ship today"), + Some((SearchField::Body, "Ship today".into())) ); + assert!(!answered(&prose, "**")); assert_eq!( - view.language_counts - .iter() - .map(|language| (language.value, language.count)) - .collect::>(), - [(Language::Json, 6), (Language::Txt, 2)] + hit_field(&drawing, "gateway"), + Some((SearchField::Body, "Gateway".into())) ); - assert_eq!(view.kind_counts[1].count, 2); - assert_eq!(view.priority_counts[3].count, 1); + assert!(!answered(&drawing, "textbox")); } #[test] - fn every_kind_is_counted_in_its_order_even_at_zero() { - let counts = count_kinds(&[ - ("checklist".to_string(), 3), - ("snippet".to_string(), 5), - ("from-a-newer-build".to_string(), 1), - ]); + fn a_search_finds_accented_words_either_way() { + let accented = Note { + content: "Étape suivante".into(), + ..note() + }; - let pairs: Vec<(NoteKind, u32)> = counts.iter().map(|c| (c.value, c.count)).collect(); - assert_eq!( - pairs, - [ - (NoteKind::Snippet, 5), - (NoteKind::Note, 0), - (NoteKind::Checklist, 3), - (NoteKind::Calc, 0), - (NoteKind::Drawing, 0) - ] - ); - } + let plain = Note { + content: "etape".into(), + ..note() + }; - mod order { - use super::*; + assert!(answered(&accented, "etape")); + assert!(answered(&plain, "ÉTAPE")); + } - fn titles(notes: &[Note]) -> Vec<&str> { - notes.iter().map(|note| note.title.as_str()).collect() - } + /// What the rich editor escaped when it wrote the Markdown is searched as it shows. + #[test] + fn a_note_is_found_across_the_escapes_its_markdown_holds() { + for (stored, searched, quoted) in [ + ("read list\\[0] first", "list[0]", "read list[0] first"), + ( + "def \\_\\_init\\_\\_(self)", + "__init__", + "def __init__(self)", + ), + ("call(\\*args)", "*args", "call(*args)"), + ] { + let prose = Note { + kind: NoteKind::Note, + content: stored.into(), + ..note() + }; - fn ordered(notes: Vec, key: SortKey, direction: SortDirection) -> Vec { - let mut cards: Vec = notes.into_iter().map(card).collect(); - order_cards(&mut cards, NoteOrder { key, direction }); - cards - .into_iter() - .map(|card| card.note.note.clone()) - .collect() + assert_eq!( + hit_field(&prose, searched), + Some((SearchField::Body, quoted.into())), + "{searched}" + ); } + } - /// Sealed titles are ordered here, folded: case and accents do not scatter them. - #[test] - fn titles_run_a_to_z_whatever_their_case_and_accents() { - let notes = vec![note("a", "zeta"), note("b", "Étape"), note("c", "alpha")]; + #[test] + fn a_quote_keeps_160_characters_and_marks_what_it_cut() { + let quote = |source: String| { + let found = Note { source, ..note() }; + hit_field(&found, "ø").expect("a quote").1 + }; - let up = ordered(notes.clone(), SortKey::Title, SortDirection::Ascending); - let down = ordered(notes, SortKey::Title, SortDirection::Descending); + assert_eq!(quote("ø".repeat(160)), "ø".repeat(160)); + assert_eq!(quote("ø".repeat(161)), format!("{}…", "ø".repeat(160))); + } - assert_eq!(titles(&up), ["alpha", "Étape", "zeta"]); - assert_eq!(titles(&down), ["zeta", "Étape", "alpha"]); - } + // --- The order of a list. - #[test] - fn priorities_run_from_the_most_pressing_down() { - let notes = [ - Priority::Low, - Priority::Urgent, - Priority::None, - Priority::High, - ] - .into_iter() - .enumerate() - .map(|(at, priority)| Note { - priority, - ..note(&at.to_string(), priority.as_str()) - }) - .collect(); + #[test] + fn a_list_runs_from_the_last_edit_by_default() { + let notes = vec![ + edited("old", "2026-07-01T00:00:00.000Z"), + edited("new", "2026-07-25T08:00:00.000Z"), + edited("mid", "2026-07-20T00:00:00.000Z"), + ]; + let flat = NotesQuery { + grouping: Grouping::None, + ..query() + }; - let down = ordered(notes, SortKey::Priority, SortDirection::Descending); + assert_eq!(ids(&view(notes, &flat)), ["new", "mid", "old"]); + } - assert_eq!(titles(&down), ["urgent", "high", "low", "none"]); - } + #[test] + fn each_sort_key_orders_its_way_and_ascending_turns_it_round() { + let at_ = |iso: &str| at(iso); + let notes = vec![ + Note { + id: "a".into(), + title: "zèbre".into(), + created_at: at_("2026-01-03T00:00:00.000Z"), + priority: Priority::Low, + kind: NoteKind::Note, + ..note() + }, + Note { + id: "b".into(), + title: "Écran".into(), + created_at: at_("2026-01-01T00:00:00.000Z"), + priority: Priority::Urgent, + kind: NoteKind::Snippet, + language: Language::Sql, + ..note() + }, + Note { + id: "c".into(), + title: "ecrou".into(), + created_at: at_("2026-01-02T00:00:00.000Z"), + priority: Priority::None, + kind: NoteKind::Snippet, + language: Language::Py, + ..note() + }, + ]; - #[test] - fn a_format_is_its_kind_then_its_language() { - let of = |id: &str, kind: NoteKind, language: Language| Note { - language, - kind, - ..note(id, id) + for (key, ascending) in [ + (SortKey::Created, ["b", "c", "a"]), + (SortKey::Priority, ["c", "a", "b"]), + (SortKey::Format, ["c", "b", "a"]), + (SortKey::Title, ["b", "c", "a"]), + ] { + let request = |direction| NotesQuery { + grouping: Grouping::None, + order: NoteOrder { key, direction }, + ..query() }; - let notes = vec![ - of("list", NoteKind::Checklist, Language::Txt), - of("sql", NoteKind::Snippet, Language::Sql), - of("prose", NoteKind::Note, Language::Txt), - of("json", NoteKind::Snippet, Language::Json), - ]; - - let up = ordered(notes, SortKey::Format, SortDirection::Ascending); + let up = ids(&view(notes.clone(), &request(SortDirection::Ascending))); + let down = ids(&view(notes.clone(), &request(SortDirection::Descending))); - assert_eq!(titles(&up), ["json", "sql", "prose", "list"]); + assert_eq!(up, ascending, "{key:?}"); + assert_eq!( + down, + ascending.iter().rev().copied().collect::>(), + "{key:?}" + ); } + } - /// Whichever way the list runs: two refreshes never swap neighbours. - #[test] - fn ties_fall_on_the_last_edit_then_the_id() { - let edited = |id: &str, at_: &str| Note { - updated_at: at(at_), - ..note(id, id) - }; - let notes = vec![ - edited("b", "2026-07-25T09:00:00.000Z"), - edited("c", "2026-07-25T10:00:00.000Z"), - edited("a", "2026-07-25T09:00:00.000Z"), - ]; - - let up = ordered(notes.clone(), SortKey::Priority, SortDirection::Ascending); - let down = ordered(notes, SortKey::Priority, SortDirection::Descending); - - assert_eq!(titles(&up), ["c", "a", "b"]); - assert_eq!(titles(&down), ["c", "a", "b"]); - } + #[test] + fn a_tie_falls_on_the_last_edit_then_the_id_whichever_way_the_list_runs() { + let notes = vec![ + edited("b", "2026-07-20T00:00:00.000Z"), + edited("c", "2026-07-21T00:00:00.000Z"), + edited("a", "2026-07-20T00:00:00.000Z"), + ]; - #[test] - fn a_list_sorted_by_creation_dates_its_cards_by_creation() { - let view = build( - vec![note("a", "Un")], - Facets::default(), - &NotesQuery { - order: NoteOrder { - key: SortKey::Created, - direction: SortDirection::Descending, - }, - ..request() + for direction in [SortDirection::Ascending, SortDirection::Descending] { + let request = NotesQuery { + grouping: Grouping::None, + order: NoteOrder { + key: SortKey::Priority, + direction, }, - ); - let plain = build(vec![note("a", "Un")], Facets::default(), &request()); + ..query() + }; - let footer = |view: &NotesView| first_displayed(view).footer; - assert!(matches!(footer(&view), model::NoteFooter::Created { .. })); - assert!(matches!(footer(&plain), model::NoteFooter::Age { .. })); + assert_eq!( + ids(&view(notes.clone(), &request)), + ["c", "a", "b"], + "{direction:?}" + ); } } #[test] - fn a_selected_priority_counts_as_filtering_and_passes_only_its_notes() { - let view = build( - vec![note("a", "Un")], - Facets::default(), - &NotesQuery { - priorities: vec![Priority::Urgent, Priority::High], - ..request() + fn a_ranked_search_puts_the_title_that_answers_best_first() { + let notes = vec![ + Note { + content: "psql in the body".into(), + ..titled("body", "Other") }, - ); - let criteria = Criteria::new("", NoteFilter::All, &[], &[], &[], &[Priority::Urgent]); - let counts = count_priorities(&[("urgent".to_string(), 2)]); + titled("inside", "mypsqlrc"), + titled("word", "Connexion psql"), + titled("start", "psql connexion"), + titled("exact", "PSQL"), + ]; + let request = NotesQuery { + ranked: true, + ..searching("psql") + }; - assert!(view.is_filtering); - assert_eq!(keys(&view), [NoteSectionKey::Results]); - assert!(criteria.passes(&Note { - priority: Priority::Urgent, - ..sample() - })); - assert!(!criteria.passes(&sample())); - assert_eq!(counts.len(), Priority::ALL.len()); - assert_eq!((counts[4].value, counts[4].count), (Priority::Urgent, 2)); + assert_eq!( + ids(&view(notes, &request)), + ["exact", "start", "word", "inside", "body"] + ); } #[test] - fn a_selected_kind_counts_as_filtering_and_passes_only_its_notes() { - let view = build( - vec![note("a", "Un")], - Facets::default(), - &NotesQuery { - kinds: vec![NoteKind::Note], - ..request() + fn an_equal_rank_falls_on_the_last_edit_then_the_id() { + let notes = vec![ + Note { + title: "psql".into(), + ..edited("b", "2026-07-20T00:00:00.000Z") }, - ); - let criteria = Criteria::new("", NoteFilter::All, &[], &[], &[NoteKind::Note], &[]); + Note { + title: "psql".into(), + ..edited("c", "2026-07-21T00:00:00.000Z") + }, + Note { + title: "psql".into(), + ..edited("a", "2026-07-20T00:00:00.000Z") + }, + ]; + let request = NotesQuery { + ranked: true, + ..searching("psql") + }; - assert!(view.is_filtering); - assert_eq!(keys(&view), [NoteSectionKey::Results]); - assert!(criteria.passes(&Note { - kind: NoteKind::Note, - ..sample() - })); - assert!(!criteria.passes(&Note { - kind: NoteKind::Snippet, - ..sample() - })); + assert_eq!(ids(&view(notes, &request)), ["c", "a", "b"]); } + // --- The sections of the list. + #[test] - fn a_selected_language_counts_as_filtering_like_a_selected_tag() { - let view = build( - vec![note("a", "Un")], - Facets::default(), - &NotesQuery { - languages: vec![Language::Json], - ..request() + fn by_date_the_list_runs_pinned_today_this_week_older() { + let notes = vec![ + edited("today", "2026-07-25T01:00:00.000Z"), + edited("week", "2026-07-20T00:00:00.000Z"), + edited("older", "2026-07-01T00:00:00.000Z"), + Note { + pinned: true, + ..edited("pinned", "2026-07-01T00:00:00.000Z") }, - ); + ]; - assert!(view.is_filtering); - assert_eq!(keys(&view), [NoteSectionKey::Results]); + assert_eq!( + sections(&view(notes, &query())), + [ + ("pinned".to_string(), vec!["pinned".to_string()]), + ("today".to_string(), vec!["today".to_string()]), + ("week".to_string(), vec!["week".to_string()]), + ("older".to_string(), vec!["older".to_string()]), + ] + ); } - mod search { - use super::*; + #[test] + fn by_date_only_this_week_stays_when_empty_and_holds_the_create_card() { + let shown = view(vec![], &query()); - #[test] - fn the_title_the_tags_and_the_content_are_all_searched() { - let note = Note { - title: "Déploiement".to_string(), - content: "kubectl apply".to_string(), - tags: vec!["ops".to_string()], - ..sample() - }; + assert_eq!(sections(&shown), [("week".to_string(), vec![])]); + assert_eq!(ghosts(&shown), [true]); + assert!(shown.offers_creation()); + } - assert!(matches_search(¬e, &fold("déploi"))); - assert!(matches_search(¬e, &fold("kubectl"))); - assert!(matches_search(¬e, &fold("ops"))); - assert!(!matches_search(¬e, &fold("terraform"))); - } + #[test] + fn every_note_lands_in_exactly_one_dated_section() { + let notes: Vec = (0..24 * 10) + .map(|hour| { + let mut dated = edited(&format!("{hour:03}"), NOW); + dated.updated_at = at(NOW) - TimeDelta::hours(hour) + TimeDelta::hours(12); + dated.pinned = hour % 7 == 0; + dated + }) + .collect(); - #[test] - fn search_case_folding_reaches_beyond_ascii() { - let note = Note { - title: "Étape suivante".to_string(), - ..sample() + for tz_offset_minutes in [-840, -120, 0, 300, 840] { + let request = NotesQuery { + tz_offset_minutes, + ..query() }; + let mut seen = ids(&view(notes.clone(), &request)); + seen.sort(); - assert!(matches_search(¬e, &fold("étape"))); - assert!(matches_search(¬e, &fold("ÉTAPE"))); + let mut expected: Vec = notes.iter().map(|note| note.id.clone()).collect(); + expected.sort(); + assert_eq!(seen, expected, "{tz_offset_minutes}"); } + } - /// Nobody reaches for the accent key to search. - #[test] - fn an_unaccented_needle_finds_accented_text() { - let note = Note { - title: "Étape de migration".to_string(), - content: "Prévenir l'équipe".to_string(), - tags: vec!["déploiement".to_string()], - ..sample() - }; - - assert!(matches_search(¬e, &fold("etape"))); - assert!(matches_search(¬e, &fold("equipe"))); - assert!(matches_search(¬e, &fold("deploiement"))); - } + #[test] + fn this_week_is_the_seven_days_before_now_both_ends_included() { + let notes = vec![ + edited("edge", "2026-07-18T09:00:00.000Z"), + edited("past", "2026-07-18T08:59:59.000Z"), + edited("future", "2026-07-27T00:00:00.000Z"), + ]; - /// Both sides go through `fold`, so it works the other way round too. - #[test] - fn an_accented_needle_finds_unaccented_text() { - let note = Note { - title: "Etape de migration".to_string(), - ..sample() - }; + assert_eq!( + sections(&view(notes, &query())), + [ + ("week".to_string(), vec!["edge".to_string()]), + ( + "older".to_string(), + vec!["future".to_string(), "past".to_string()] + ), + ] + ); + } - assert!(matches_search(¬e, &fold("Étape"))); - } + #[test] + fn today_is_the_local_day_of_the_offset_given() { + // 23:30 UTC the day before is 01:30 today at UTC+2 (an offset of −120). + let late = edited("late", "2026-07-24T23:30:00.000Z"); - /// Only what a canonical decomposition separates is folded away. - #[test] - fn a_letter_of_its_own_is_not_folded_into_another() { - let note = Note { - title: "Størrelse".to_string(), - ..sample() - }; + let at_utc = view(vec![late.clone()], &query()); + let at_plus_two = view( + vec![late], + &NotesQuery { + tz_offset_minutes: -120, + ..query() + }, + ); - assert!(matches_search(¬e, &fold("størrelse"))); - assert!(!matches_search(¬e, &fold("storrelse"))); - } + assert_eq!(at_utc.sections[0].id, "week"); + assert_eq!(at_plus_two.sections[0].id, "today"); + } - #[test] - fn folding_leaves_an_ascii_needle_alone() { - assert_eq!(fold("Kubectl APPLY"), "kubectl apply"); + #[test] + fn an_offset_past_fourteen_hours_is_read_as_utc() { + for (minutes, east) in [ + (-120, 7_200), + (840, -50_400), + (-840, 50_400), + (841, 0), + (i32::MIN, 0), + (i32::MAX, 0), + ] { + assert_eq!( + offset_from_minutes(minutes).local_minus_utc(), + east, + "{minutes}" + ); } + } - #[test] - fn a_checklist_is_found_by_the_text_of_its_items() { - let note = Note { - title: "Sprint".to_string(), - content: String::new(), - kind: NoteKind::Checklist, - items: vec![ - ChecklistItem { - text: "Review the migration".to_string(), - done: false, - }, - ChecklistItem { - text: "Prévenir l'équipe".to_string(), - done: true, - }, - ], - ..sample() - }; + #[test] + fn sorted_by_creation_the_sections_split_on_the_creation_date() { + let made_long_ago = Note { + created_at: at("2026-01-01T00:00:00.000Z"), + ..edited("n", "2026-07-25T08:00:00.000Z") + }; + let request = NotesQuery { + order: NoteOrder { + key: SortKey::Created, + direction: SortDirection::Descending, + }, + ..query() + }; - assert!(matches_search(¬e, &fold("migration"))); - assert!(matches_search(¬e, &fold("equipe"))); - assert!(!matches_search(¬e, &fold("terraform"))); - } + assert_eq!( + view(vec![made_long_ago.clone()], &query()).sections[0].id, + "today" + ); + assert_eq!(view(vec![made_long_ago], &request).sections[1].id, "older"); } - mod hits { - use super::*; + #[test] + fn without_pinned_first_a_pinned_note_stays_in_its_date_section() { + let pinned = Note { + pinned: true, + ..edited("p", "2026-07-25T08:00:00.000Z") + }; + let request = NotesQuery { + pinned_first: false, + ..query() + }; - fn hit_for(note: Note, search: &str) -> Option { - let view = build( - vec![note], - Facets::default(), - &NotesQuery { - search: search.to_string(), - ..request() - }, - ); + assert_eq!( + sections(&view(vec![pinned], &request)), + [ + ("today".to_string(), vec!["p".to_string()]), + ("week".to_string(), vec![]) + ] + ); + } - view.cards().next().and_then(|card| card.hit.clone()) - } + #[test] + fn by_priority_the_sections_run_from_urgent_down_and_none_is_always_there() { + let notes = vec![ + Note { + priority: Priority::Low, + ..titled("low", "a") + }, + Note { + priority: Priority::Urgent, + ..titled("urgent", "b") + }, + ]; + let request = NotesQuery { + grouping: Grouping::Priority, + ..query() + }; - #[test] - fn quotes_the_line_that_matched_and_not_the_first_one() { - let note = Note { - language: crate::notes::language::Language::Sh, - content: "first\nsecond\n kubectl rollout restart\nfourth".to_string(), - ..sample() - }; + let shown = view(notes, &request); - let hit = hit_for(note, "rollout").expect("a body match is worth quoting"); - assert_eq!(hit.field, SearchField::Body); - // Trimmed: a card shows one line and it should start with the code. - assert_eq!(hit.excerpt, "kubectl rollout restart"); - } + assert_eq!( + sections(&shown), + [ + ("priority-urgent".to_string(), vec!["urgent".to_string()]), + ("priority-low".to_string(), vec!["low".to_string()]), + ("priority-none".to_string(), vec![]), + ] + ); + assert_eq!(ghosts(&shown), [false, false, true]); + assert_eq!( + shown.sections[0].group, + Some(SectionGroup::Priority { + priority: Priority::Urgent + }) + ); + assert_eq!(shown.sections[0].key, NoteSectionKey::Priority); + } - /// A Note is quoted without its Markdown, found by the words it shows. - #[test] - fn quotes_a_note_without_its_markdown() { - let note = Note { + #[test] + fn by_format_snippets_come_by_language_then_the_other_kinds_the_create_card_last() { + let mut languages = [Language::Sql, Language::Py]; + languages.sort(); + let notes = vec![ + Note { + kind: NoteKind::Checklist, + ..titled("list", "a") + }, + Note { kind: NoteKind::Note, - content: "# Standup\n\n- [ ] ask about the **rollout** window".to_string(), - ..sample() - }; - - let hit = hit_for(note, "rollout").expect("a body match is worth quoting"); - assert_eq!(hit.excerpt, "☐ ask about the rollout window"); - } - - /// What a Note shows is what is searched: across a Markdown mark, and what the editor - /// escaped when it wrote the Markdown. - #[test] - fn finds_a_note_by_the_words_it_shows() { - for (stored, searched, quoted) in [ - ( - "ask about the **rollout** window", - "rollout window", - "ask about the rollout window", - ), - ("read list\\[0] first", "list[0]", "read list[0] first"), - ( - "def \\_\\_init\\_\\_(self)", - "__init__", - "def __init__(self)", - ), - ("call(\\*args)", "*args", "call(*args)"), - ] { - let note = Note { - kind: NoteKind::Note, - content: stored.to_string(), - ..sample() - }; - let hit = hit_for(note, searched); - assert_eq!( - hit.map(|hit| hit.excerpt).as_deref(), - Some(quoted), - "{searched}" - ); - } - } - - #[test] - fn says_nothing_when_the_title_is_what_matched() { - let note = Note { - title: "Rollout".to_string(), - content: "kubectl apply".to_string(), - ..sample() - }; - - // Quoting the title back would repeat the biggest thing on the card. - assert!(hit_for(note, "rollout").is_none()); - } - - #[test] - fn quotes_the_tag_and_the_item_the_card_does_not_show() { - let tagged = Note { - tags: vec!["urgent".to_string()], - ..sample() - }; - let hit = hit_for(tagged, "urgen").expect("a tag match is worth quoting"); - assert_eq!(hit.field, SearchField::Tag); - assert_eq!(hit.excerpt, "urgent"); - - let listed = Note { - items: vec![ - ChecklistItem { - text: "Bump the version".to_string(), - done: false, - }, - ChecklistItem { - text: "Push the tag".to_string(), - done: false, - }, - ], - ..sample() - }; - let hit = hit_for(listed, "push").expect("an item match is worth quoting"); - assert_eq!(hit.field, SearchField::Item); - assert_eq!(hit.excerpt, "Push the tag"); - } - - /// `PostgreSQL` found nothing, though the guide says the search reads the contexts (COD-21). - #[test] - fn quotes_the_context_when_nothing_else_matched() { - let note = Note { - source: "PostgreSQL / production".to_string(), - content: "psql -h db".to_string(), - ..sample() - }; - let hit = hit_for(note, "postgre").expect("a context match is worth quoting"); - assert_eq!(hit.field, SearchField::Source); - assert_eq!(hit.excerpt, "PostgreSQL / production"); - - let in_both = Note { - source: "Prettier".to_string(), - content: "npx prettier --write .".to_string(), - ..sample() - }; - assert_eq!( - hit_for(in_both, "prettier").map(|hit| hit.field), - Some(SearchField::Body), - "the code is the better quote" - ); - } - - #[test] - fn clips_a_line_long_enough_to_be_a_payload() { - let note = Note { - content: format!("{}needle", "x".repeat(400)), - ..sample() - }; + ..titled("prose", "b") + }, + Note { + language: Language::Sql, + ..titled("sql", "c") + }, + Note { + language: Language::Py, + ..titled("py", "d") + }, + ]; + let request = NotesQuery { + grouping: Grouping::Format, + ..query() + }; - let hit = hit_for(note, "needle").expect("it still matches"); - // 160 characters and the ellipsis that says there were more. - assert_eq!(hit.excerpt.chars().count(), EXCERPT_CHARS + 1); - assert!(hit.excerpt.ends_with('…')); - } + let shown = view(notes, &request); - #[test] - fn clips_on_characters_rather_than_bytes() { - let note = Note { - content: format!("{}needle", "é".repeat(400)), - ..sample() - }; + let expected: Vec = languages + .iter() + .map(|language| format!("format-{language}")) + .chain(["format-note".to_string(), "format-checklist".to_string()]) + .collect(); + let found: Vec = shown + .sections + .iter() + .map(|section| section.id.clone()) + .collect(); + assert_eq!(found, expected); + assert_eq!(ghosts(&shown), [false, false, false, true]); + assert!( + shown + .sections + .iter() + .all(|section| section.key == NoteSectionKey::Format) + ); + } - // A byte slice would have panicked in the middle of one of these. - let hit = hit_for(note, "needle").expect("an accented needle still matches"); - assert_eq!(hit.excerpt.chars().count(), EXCERPT_CHARS + 1); - } + #[test] + fn by_format_with_nothing_to_show_is_one_section_to_create_in() { + let request = NotesQuery { + grouping: Grouping::Format, + ..query() + }; - #[test] - fn carries_nothing_when_nothing_is_searched() { - let note = Note { - content: "kubectl apply".to_string(), - ..sample() - }; + let shown = view(vec![], &request); - assert!(hit_for(note, " ").is_none()); - } + assert_eq!(sections(&shown), [("all".to_string(), vec![])]); + assert_eq!(ghosts(&shown), [true]); } - mod sections { - use super::*; - use crate::notes::model::NoteLifecycle; + #[test] + fn ungrouped_the_list_is_one_section_its_pinned_notes_first() { + let notes = vec![ + edited("new", "2026-07-25T08:00:00.000Z"), + Note { + pinned: true, + ..edited("pinned", "2026-07-01T00:00:00.000Z") + }, + ]; + let request = NotesQuery { + grouping: Grouping::None, + ..query() + }; - fn utc() -> FixedOffset { - FixedOffset::east_opt(0).unwrap() - } + let shown = view(notes, &request); - fn now_at(_offset: FixedOffset) -> DateTime { - at(NOW) - } + assert_eq!( + sections(&shown), + [( + "all".to_string(), + vec!["pinned".to_string(), "new".to_string()] + )] + ); + assert_eq!(ghosts(&shown), [true]); + } - fn note(id: &str, created_at: &str) -> Note { + #[test] + fn hoisting_the_pinned_notes_keeps_the_order_among_each_side() { + let notes = vec![ Note { - id: id.to_string(), - created_at: at(created_at), - updated_at: at(created_at), - ..sample() - } - } + priority: Priority::High, + pinned: true, + ..edited("p-old", "2026-07-01T00:00:00.000Z") + }, + Note { + priority: Priority::High, + ..edited("new", "2026-07-25T08:00:00.000Z") + }, + Note { + priority: Priority::High, + pinned: true, + ..edited("p-new", "2026-07-24T00:00:00.000Z") + }, + Note { + priority: Priority::High, + ..edited("old", "2026-07-02T00:00:00.000Z") + }, + ]; + let request = NotesQuery { + grouping: Grouping::Priority, + ..query() + }; - fn keys(sections: &[NoteSection]) -> Vec { - sections.iter().map(|section| section.key).collect() - } + assert_eq!( + sections(&view(notes, &request))[0].1, + ["p-new", "p-old", "new", "old"] + ); + } - fn ids_in(sections: &[NoteSection], key: NoteSectionKey) -> Vec { - sections - .iter() - .filter(|section| section.key == key) - .flat_map(|section| section.cards.iter().map(|note| note.id.clone())) - .collect() - } + #[test] + fn a_search_or_a_rail_makes_one_flat_list_of_results_without_the_create_card() { + let request = NotesQuery { + tags: vec!["auth".into()], + grouping: Grouping::Priority, + ..query() + }; - #[test] - fn a_real_offset_keeps_its_sign_inverted() { - assert_eq!(offset_from_minutes(-120).local_minus_utc(), 2 * 3600); - assert_eq!(offset_from_minutes(300).local_minus_utc(), -5 * 3600); - assert_eq!(offset_from_minutes(0).local_minus_utc(), 0); - } + let shown = view(vec![note()], &request); - #[test] - fn an_absurd_offset_falls_back_to_utc_without_overflowing() { - // Negating i32::MIN or multiplying i32::MAX by 60 would panic under the connection - // mutex and poison it. - for absurd in [i32::MIN, i32::MAX, -100_000, 100_000, 841, -841] { - assert_eq!(offset_from_minutes(absurd).local_minus_utc(), 0); - } - } + assert_eq!( + sections(&shown), + [("results".to_string(), vec!["n-1".to_string()])] + ); + assert_eq!(ghosts(&shown), [false]); + assert!(shown.is_filtering); + assert_eq!(shown.matched, 1); + } - fn edited(id: &str, at_: &str) -> Note { - Note { - created_at: at("2019-01-01T08:00:00.000Z"), - updated_at: at(at_), - ..note(id, at_) - } - } + #[test] + fn an_opened_folder_alone_is_a_flat_list_to_create_in() { + let inside = NotesQuery { + folder_id: Some("f-1".into()), + ..query() + }; + let searched_inside = NotesQuery { + search: "content".into(), + ..inside.clone() + }; - /// Sorted by the last edit, the list is split on it too: the two cannot disagree. - #[test] - fn the_dated_sections_split_on_the_date_the_list_is_sorted_by() { - let offset = utc(); - let notes = vec![edited("touched today", "2026-07-25T08:00:00.000Z")]; - - let by_edit = build_sections( - notes.clone(), - Layout::Dated { by_creation: false }, - true, - now_at(offset), - offset, - ); - let by_creation = build_sections( - notes, - Layout::Dated { by_creation: true }, - true, - now_at(offset), - offset, - ); + let shown = view(vec![note()], &inside); - assert_eq!(ids_in(&by_edit, NoteSectionKey::Today), ["touched today"]); - assert_eq!( - ids_in(&by_creation, NoteSectionKey::Older), - ["touched today"] - ); - } + assert_eq!(shown.sections[0].key, NoteSectionKey::Results); + assert!(shown.is_filtering); + assert_eq!(ghosts(&shown), [true]); + assert_eq!(ghosts(&view(vec![note()], &searched_inside)), [false]); + } - #[test] - fn priorities_gather_from_the_most_pressing_down_pinned_first_in_each() { - let offset = utc(); - let with = |id: &str, priority: Priority, pinned: bool| Note { - pinned, - priority, - ..note(id, "2026-07-25T08:00:00.000Z") - }; - let notes = vec![ - with("low", Priority::Low, false), - with("urgent", Priority::Urgent, false), - with("urgent pinned", Priority::Urgent, true), - ]; - - let sections = build_sections(notes, Layout::ByPriority, true, now_at(offset), offset); - - let ids: Vec<&str> = sections.iter().map(|section| section.id.as_str()).collect(); - assert_eq!(ids, ["priority-urgent", "priority-low", "priority-none"]); - let urgent: Vec<&str> = sections[0] - .cards - .iter() - .map(|card| card.id.as_str()) - .collect(); - assert_eq!(urgent, ["urgent pinned", "urgent"]); - assert!(sections[2].cards.is_empty() && sections[2].show_create_ghost); - } + #[test] + fn the_quick_filter_keeps_the_sections() { + let request = NotesQuery { + filter: NoteFilter::Pinned, + ..query() + }; - #[test] - fn formats_gather_snippets_by_language_then_the_other_kinds() { - let offset = utc(); - let of = |id: &str, language: Language, kind: NoteKind| Note { - language, - kind, - ..note(id, "2026-07-25T08:00:00.000Z") - }; - let notes = vec![ - of("list", Language::Txt, NoteKind::Checklist), - of("sql", Language::Sql, NoteKind::Snippet), - of("prose", Language::Txt, NoteKind::Note), - of("json", Language::Json, NoteKind::Snippet), - ]; + let shown = view(vec![], &request); - let sections = build_sections(notes, Layout::ByFormat, true, now_at(offset), offset); + assert!(!shown.is_filtering); + assert_eq!(shown.sections[0].id, "week"); + } - let ids: Vec<&str> = sections.iter().map(|section| section.id.as_str()).collect(); - assert_eq!( - ids, - [ - "format-json", - "format-sql", - "format-note", - "format-checklist" - ] - ); - assert!( - sections - .iter() - .all(|section| section.key == NoteSectionKey::Format) - ); - let ghosts: Vec = sections.iter().map(|s| s.show_create_ghost).collect(); - assert_eq!(ghosts, [false, false, false, true]); - } + #[test] + fn a_search_keeps_only_the_notes_that_answer_and_counts_them() { + let notes = vec![ + titled("a", "psql"), + titled("b", "redis"), + titled("c", "psql 2"), + ]; - /// Without a grouping, and without a note, the create card still has a place. - #[test] - fn no_grouping_is_one_section_that_always_holds_the_create_card() { - let offset = utc(); + let shown = view(notes, &searching("PSQL")); - let empty = build_sections(Vec::new(), Layout::Whole, true, now_at(offset), offset); - let formats = - build_sections(Vec::new(), Layout::ByFormat, true, now_at(offset), offset); + assert_eq!(ids(&shown), ["a", "c"]); + assert_eq!(shown.matched, 2); + } - assert_eq!(keys(&empty), [NoteSectionKey::All]); - assert!(empty[0].show_create_ghost); - assert_eq!(keys(&formats), [NoteSectionKey::All]); - } + #[test] + fn a_search_that_finds_nothing_is_still_a_search_with_no_match() { + let shown = view(vec![note()], &searching("no-such-thing")); - #[test] - fn every_unpinned_note_lands_in_exactly_one_section() { - let offset = utc(); - let notes = vec![ - note("today", "2026-07-25T08:00:00.000Z"), - note("week", "2026-07-21T08:00:00.000Z"), - note("older", "2020-01-01T08:00:00.000Z"), - ]; - - let sections = build_sections( - notes, - Layout::Dated { by_creation: true }, - true, - now_at(offset), - offset, - ); + assert!(shown.is_filtering); + assert_eq!(shown.matched, 0); + assert!(!shown.offers_creation()); + } - let placed: Vec = sections - .iter() - .flat_map(|section| section.cards.iter().map(|note| note.id.clone())) - .collect(); - assert_eq!(placed.len(), 3); - assert_eq!(ids_in(§ions, NoteSectionKey::Today), ["today"]); - assert_eq!(ids_in(§ions, NoteSectionKey::Week), ["week"]); - assert_eq!(ids_in(§ions, NoteSectionKey::Older), ["older"]); - } + #[test] + fn a_card_is_cut_once_for_its_view_and_a_frame_only_reads_it() { + let shown = view(vec![note()], &query()); + let card = shown.cards().next().unwrap(); - #[test] - fn the_week_section_is_present_even_when_empty() { - let offset = utc(); + assert!(std::ptr::eq(shown.display(card), shown.display(card))); + } - let sections = build_sections( - Vec::new(), - Layout::Dated { by_creation: true }, - true, - now_at(offset), - offset, - ); + #[test] + fn a_section_says_it_holds_a_note_about_to_expire_but_results_do_not() { + let expiring = Note { + lifecycle: NoteLifecycle::Expires { at: at(NOW) }, + ..edited("x", "2026-07-25T08:00:00.000Z") + }; - assert_eq!(keys(§ions), [NoteSectionKey::Week]); - assert!(sections[0].show_create_ghost); - } + let dated = view( + vec![expiring.clone(), edited("y", "2026-07-01T00:00:00.000Z")], + &query(), + ); + let searched = view(vec![expiring], &searching("content")); - #[test] - fn only_the_week_section_carries_the_create_ghost() { - let offset = utc(); - let notes = vec![ - note("today", "2026-07-25T08:00:00.000Z"), - note("older", "2020-01-01T08:00:00.000Z"), - ]; - - let sections = build_sections( - notes, - Layout::Dated { by_creation: true }, - true, - now_at(offset), - offset, - ); + let flags: Vec<_> = dated + .sections + .iter() + .map(|section| (section.id.as_str(), section.has_expiring_notes)) + .collect(); + assert_eq!(flags, [("today", true), ("week", false), ("older", false)]); + assert!(!searched.sections[0].has_expiring_notes); + } - let with_ghost: Vec = sections - .iter() - .filter(|section| section.show_create_ghost) - .map(|section| section.key) - .collect(); - assert_eq!(with_ghost, [NoteSectionKey::Week]); - } + // --- Facets. - #[test] - fn pinned_notes_leave_the_chronological_sections() { - let offset = utc(); - let mut pinned = note("pinned", "2026-07-25T08:00:00.000Z"); - pinned.pinned = true; - - let sections = build_sections( - vec![pinned], - Layout::Dated { by_creation: true }, - true, - now_at(offset), - offset, - ); + #[test] + fn kinds_and_priorities_are_counted_each_in_its_order_zeros_included() { + let rows = [ + ("note".to_string(), 2), + ("kanban".to_string(), 9), + ("snippet".to_string(), 5), + ]; - assert_eq!(ids_in(§ions, NoteSectionKey::Pinned), ["pinned"]); - assert!(ids_in(§ions, NoteSectionKey::Today).is_empty()); - } + let kinds: Vec<_> = count_kinds(&rows) + .iter() + .map(|facet| (facet.value, facet.count)) + .collect(); + let priorities = count_priorities(&[("high".to_string(), 3)]); - #[test] - fn without_the_hoist_a_pinned_note_follows_its_date_like_any_other() { - let offset = utc(); - let mut pinned = note("pinned", "2026-07-25T08:00:00.000Z"); - pinned.pinned = true; - - let sections = build_sections( - vec![pinned], - Layout::Dated { by_creation: true }, - false, - now_at(offset), - offset, - ); + assert_eq!( + kinds, + [ + (NoteKind::Snippet, 5), + (NoteKind::Note, 2), + (NoteKind::Checklist, 0), + (NoteKind::Calc, 0), + (NoteKind::Drawing, 0), + ] + ); + assert_eq!(priorities.len(), Priority::ALL.len()); + assert_eq!( + priorities[3], + FacetCount { + value: Priority::High, + count: 3 + } + ); + } - assert!(!keys(§ions).contains(&NoteSectionKey::Pinned)); - assert_eq!(ids_in(§ions, NoteSectionKey::Today), ["pinned"]); - } + #[test] + fn tags_and_languages_are_counted_as_read_an_unknown_language_left_out() { + let tags = count_tags(vec![("ops".to_string(), 2), ("ci".to_string(), 1)]); + let languages = count_languages(&[ + ("sql".to_string(), 4), + ("brainfuck".to_string(), 1), + ("py".to_string(), 2), + ]); - #[test] - fn the_hoist_reaches_the_flat_list_too() { - let offset = utc(); - let mut pinned = note("pinned", "2019-05-05T08:00:00.000Z"); - pinned.pinned = true; - let notes = vec![note("recent", "2026-07-25T08:00:00.000Z"), pinned]; - - let hoisted = build_sections( - notes.clone(), - Layout::Flat { - create_ghost: false, + assert_eq!( + tags, + [ + FacetCount { + value: "ops".to_string(), + count: 2 }, - true, - now_at(offset), - offset, - ); - let untouched = build_sections( - notes, - Layout::Flat { - create_ghost: false, + FacetCount { + value: "ci".to_string(), + count: 1 }, - false, - now_at(offset), - offset, - ); - - assert_eq!( - ids_in(&hoisted, NoteSectionKey::Results), - ["pinned", "recent"] - ); - assert_eq!( - ids_in(&untouched, NoteSectionKey::Results), - ["recent", "pinned"] - ); - } - - #[test] - fn empty_sections_other_than_week_are_omitted() { - let offset = utc(); - - let sections = build_sections( - vec![note("today", "2026-07-25T08:00:00.000Z")], - Layout::Dated { by_creation: true }, - true, - now_at(offset), - offset, - ); - - assert_eq!( - keys(§ions), - [NoteSectionKey::Today, NoteSectionKey::Week] - ); - } - - #[test] - fn filtering_collapses_everything_into_a_single_flat_section() { - let offset = utc(); - let mut pinned = note("pinned", "2026-07-25T08:00:00.000Z"); - pinned.pinned = true; - let notes = vec![pinned, note("ancient", "2019-05-05T08:00:00.000Z")]; - - let sections = build_sections( - notes, - Layout::Flat { - create_ghost: false, + ] + ); + assert_eq!( + languages, + [ + FacetCount { + value: Language::Sql, + count: 4 }, - true, - now_at(offset), - offset, - ); - - assert_eq!(keys(§ions), [NoteSectionKey::Results]); - assert_eq!(sections[0].cards.len(), 2); - assert!(!sections[0].show_create_ghost); - } - - #[test] - fn a_section_reports_whether_any_of_its_notes_is_due_soon() { - let offset = utc(); - let mut expiring = note("expiring", "2026-07-25T08:00:00.000Z"); - expiring.lifecycle = NoteLifecycle::Expires { - at: at("2026-07-26T00:00:00.000Z"), - }; - - let sections = build_sections( - vec![expiring, note("plain", "2026-07-25T08:00:00.000Z")], - Layout::Dated { by_creation: true }, - true, - now_at(offset), - offset, - ); - - let today = sections - .iter() - .find(|s| s.key == NoteSectionKey::Today) - .unwrap(); - assert!(today.has_expiring_notes); - let week = sections - .iter() - .find(|s| s.key == NoteSectionKey::Week) - .unwrap(); - assert!(!week.has_expiring_notes); - } - - #[test] - fn a_distant_deadline_does_not_light_up_the_section_hint() { - let offset = utc(); - let mut expiring = note("expiring", "2026-07-25T08:00:00.000Z"); - expiring.lifecycle = NoteLifecycle::Expires { - at: at("2027-01-01T00:00:00.000Z"), - }; - - let sections = build_sections( - vec![expiring], - Layout::Dated { by_creation: true }, - true, - now_at(offset), - offset, - ); - - let today = sections - .iter() - .find(|s| s.key == NoteSectionKey::Today) - .unwrap(); - assert!(!today.has_expiring_notes); - } - - #[test] - fn the_day_boundary_follows_the_local_timezone_not_utc() { - let paris = offset_from_minutes(-120); - let now = at("2026-07-25T21:30:00.000Z"); + FacetCount { + value: Language::Py, + count: 2 + }, + ] + ); + } - let sections = build_sections( - vec![note("local-today", "2026-07-25T20:00:00.000Z")], - Layout::Dated { by_creation: true }, - true, - now, - paris, - ); + #[test] + fn a_view_offers_the_facets_of_the_space_not_of_its_results() { + let facets = Facets { + tags: count_tags(vec![("ops".to_string(), 2)]), + languages: count_languages(&[("sql".to_string(), 1)]), + ..Facets::default() + }; - assert_eq!(ids_in(§ions, NoteSectionKey::Today), ["local-today"]); - } + let shown = build(vec![], facets, &searching("nothing matches")); - #[test] - fn a_note_created_just_after_local_midnight_is_not_yesterday() { - let paris = offset_from_minutes(-120); - let now = at("2026-07-26T08:00:00.000Z"); + assert_eq!(shown.available_tags, ["ops"]); + assert_eq!(shown.available_languages, [Language::Sql]); + assert_eq!(shown.tag_counts[0].count, 2); + } - let sections = build_sections( - vec![note("after-midnight", "2026-07-25T22:10:00.000Z")], - Layout::Dated { by_creation: true }, - true, - now, - paris, - ); + // --- What a card draws. - assert_eq!(ids_in(§ions, NoteSectionKey::Today), ["after-midnight"]); + fn folder(id: &str) -> NoteFolder { + NoteFolder { + id: id.into(), + name: "Infra".into(), + colour: FolderColour::Blue, + path: vec!["Infra".into()], } + } - #[test] - fn a_note_created_in_the_future_is_not_swallowed() { - let offset = utc(); - - let sections = build_sections( - vec![note("future", "2030-01-01T00:00:00.000Z")], - Layout::Dated { by_creation: true }, - true, - now_at(offset), - offset, - ); + #[test] + fn decorations_give_a_card_its_attachments_its_folder_and_the_global_defaults() { + let filed = Note { + folder_id: Some("f-1".into()), + content: "{{host}}".into(), + ..note() + }; + let decorations = Decorations { + attachment_counts: [("n-1".to_string(), 3)].into(), + folders: [("f-1".to_string(), folder("f-1"))].into(), + globals: [("host".to_string(), "db".to_string())].into(), + }; + let mut shown = [ + model::decorate(filed, at(NOW)), + model::decorate(note(), at(NOW)), + ]; + shown[1].note.id = "n-2".into(); - assert_eq!(ids_in(§ions, NoteSectionKey::Older), ["future"]); - } + decorations.apply(&mut shown); - #[test] - fn the_order_received_is_preserved_inside_a_section() { - let offset = utc(); - let notes = vec![ - note("first", "2026-07-25T08:00:00.000Z"), - note("second", "2026-07-25T07:00:00.000Z"), - ]; - - let sections = build_sections( - notes, - Layout::Dated { by_creation: true }, - true, - now_at(offset), - offset, - ); - - assert_eq!( - ids_in(§ions, NoteSectionKey::Today), - ["first", "second"] - ); - } + assert_eq!(shown[0].attachment_count, 3); + assert_eq!(shown[0].folder.as_ref().map(|f| f.id.as_str()), Some("f-1")); + assert_eq!(shown[0].placeholders[0].default_value, "db"); + assert_eq!(shown[1].attachment_count, 0); + assert!(shown[1].folder.is_none()); } - mod criteria { - use super::*; - - fn tagged(id: &str, tags: &[&str]) -> Note { + #[test] + fn a_folder_the_decorations_do_not_know_gives_no_chip() { + let mut shown = [model::decorate( Note { - id: id.to_string(), - tags: tags.iter().map(ToString::to_string).collect(), - ..sample() - } - } + folder_id: Some("gone".into()), + ..note() + }, + at(NOW), + )]; - fn wanting(tags: &[&str]) -> Criteria { - let tags: Vec = tags.iter().map(ToString::to_string).collect(); - Criteria::new("", NoteFilter::All, &tags, &[], &[], &[]) - } + Decorations::default().apply(&mut shown); - /// `note_tags.tag` is `COLLATE NOCASE`, which folds ASCII and nothing else. - #[test] - fn a_tag_is_matched_the_way_the_column_compares_it() { - let criteria = wanting(&["étape"]); + assert!(shown[0].folder.is_none()); + } - assert!(criteria.passes(&tagged("a", &["étape"]))); - assert!(!criteria.passes(&tagged("c", &["Étape"]))); - assert!(wanting(&["urgent"]).passes(&tagged("d", &["URGENT"]))); - } + #[test] + fn a_card_keeps_its_folder_s_chip_unless_that_folder_is_the_one_opened() { + let opened = NotesQuery { + folder_id: Some("f-1".into()), + ..query() + }; - #[test] - fn a_tag_asked_for_with_its_hash_finds_the_stored_one() { - assert!(wanting(&["#urgent"]).passes(&tagged("a", &["urgent"]))); - } + assert!(query().keeps_chip(Some("f-1"))); + assert!(!opened.keeps_chip(Some("f-1"))); + assert!(opened.keeps_chip(Some("f-child"))); + assert!(!query().keeps_chip(None)); + } - #[test] - fn a_tag_that_normalises_to_nothing_narrows_nothing() { - let criteria = wanting(&[" # "]); + #[test] + fn a_card_draws_its_note_cut_its_quote_and_its_chip_as_the_view_says() { + let filed = |id: &str, folder_id: &str| Note { + id: id.into(), + folder_id: Some(folder_id.into()), + content: "1\n2\n3\n4\n5\n6 content".into(), + ..note() + }; + let request = NotesQuery { + folder_id: Some("f-1".into()), + search: "6 content".into(), + ..query() + }; + let mut shown = view(vec![filed("here", "f-1"), filed("below", "f-2")], &request); + shown.decorations = Arc::new(Decorations { + folders: [ + ("f-1".to_string(), folder("f-1")), + ("f-2".to_string(), folder("f-2")), + ] + .into(), + ..Decorations::default() + }); - assert!(!criteria.narrows()); - assert!(criteria.passes(&tagged("a", &[]))); - } + let drawn = |id: &str| { + let card = shown.cards().find(|card| card.id == id).expect("shown"); + shown.display(card).clone() + }; + let here = drawn("here"); - #[test] - fn the_quick_filter_decides_a_match_without_counting_as_narrowing() { - let criteria = Criteria::new("", NoteFilter::Pinned, &[], &[], &[], &[]); + assert_eq!(here.content, "1\n2\n3\n4\n5"); + assert!(here.truncated); + assert_eq!(here.search_hit.as_ref().unwrap().excerpt, "6 content"); + assert!(here.folder.is_none()); + assert_eq!(drawn("below").folder.unwrap().id, "f-2"); + } - assert!(!criteria.narrows()); - assert!(!criteria.passes(&sample())); - assert!(criteria.passes(&Note { - pinned: true, - ..sample() - })); - } + #[test] + fn sorted_by_creation_a_card_s_age_counts_from_its_creation() { + let request = NotesQuery { + order: NoteOrder { + key: SortKey::Created, + direction: SortDirection::Descending, + }, + ..query() + }; + let shown = view(vec![note()], &request); - #[test] - fn the_search_is_trimmed_and_folded_before_it_is_compared() { - let criteria = Criteria::new(" ÉTAPE ", NoteFilter::All, &[], &[], &[], &[]); + let card = shown.cards().next().unwrap(); - assert_eq!(criteria.needle(), "etape"); - assert!(criteria.passes(&Note { - title: "Étape suivante".to_string(), - ..sample() - })); - } + assert_eq!( + shown.display(card).footer, + model::NoteFooter::Created { at: at(NOW) } + ); } #[test] - fn a_card_is_cut_once_for_its_view_and_a_frame_only_reads_it() { - let view = build(vec![note("a", "Un")], Facets::default(), &request()); - let card = view.cards().next().unwrap(); - - let first: *const DisplayNote = view.display(card); - let second: *const DisplayNote = view.display(card); + fn a_selected_tag_is_brought_to_the_rule_of_a_stored_one() { + let request = NotesQuery { + tags: vec!["#Ops ".into(), "ops".into()], + ..query() + }; - assert!( - std::ptr::eq(first, second), - "the same preview, not cut again" - ); + assert_eq!(request.selected_tags(), ["Ops"]); } } From 690ba819fc2e03bcd050b6b6098e02e5face7fbf Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 00:52:27 +0100 Subject: [PATCH 04/95] Keep a drawing picture of exactly the size limit (#1724) The estimate before decoding counted base64 padding as bytes. --- crates/engine/src/notes/drawing.rs | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/notes/drawing.rs b/crates/engine/src/notes/drawing.rs index ac2488d22..4935ffbc3 100644 --- a/crates/engine/src/notes/drawing.rs +++ b/crates/engine/src/notes/drawing.rs @@ -62,8 +62,9 @@ fn png(field: &'static str, uri: &str) -> Result, ValidationError> { let payload = uri .strip_prefix(PNG) .ok_or_else(|| ValidationError::new(field, "not a PNG data URI"))?; - // Measured before decoding: base64 is four characters for three bytes. - if payload.len() / 4 * 3 > PICTURE_MAX_BYTES { + // Measured before decoding: base64 is four characters for three bytes, less its padding. + let padding = payload.len() - payload.trim_end_matches('=').len(); + if (payload.len() / 4 * 3).saturating_sub(padding) > PICTURE_MAX_BYTES { return Err(ValidationError::new(field, "too large")); } let bytes = BASE64 @@ -202,14 +203,29 @@ mod tests { } #[test] - fn a_picture_just_under_the_limit_is_kept() { - let largest = png_of(PICTURE_MAX_BYTES - 1); + fn a_picture_up_to_the_limit_is_kept() { + for size in [ + PICTURE_MAX_BYTES - 2, + PICTURE_MAX_BYTES - 1, + PICTURE_MAX_BYTES, + ] { + let largest = png_of(size); + + let decoded = pictures(&uri_of(&png_of(16)), &uri_of(&largest)).decoded(); + + assert_eq!(decoded.unwrap().unwrap().picture.len(), size); + } + } + + #[test] + fn a_picture_a_byte_past_the_limit_is_refused() { + let past = uri_of(&png_of(PICTURE_MAX_BYTES + 1)); - let decoded = pictures(&uri_of(&png_of(16)), &uri_of(&largest)).decoded(); + let refused = pictures(&uri_of(&png_of(16)), &past).decoded().unwrap_err(); assert_eq!( - decoded.unwrap().unwrap().picture.len(), - PICTURE_MAX_BYTES - 1 + refused, + ValidationError::new("pictures.picture", "too large") ); } From b001c2c39a2ec553baa0cc06fde90b55a631fc6e Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 00:59:24 +0100 Subject: [PATCH 05/95] Give no todo item for a line holding only its marker or box (#1725) --- crates/engine/src/notes/convert.rs | 35 +++++++++++++++++++----------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/notes/convert.rs b/crates/engine/src/notes/convert.rs index d84a634ad..f05ec5553 100644 --- a/crates/engine/src/notes/convert.rs +++ b/crates/engine/src/notes/convert.rs @@ -81,31 +81,32 @@ pub fn items_of(text: &str) -> Vec { checklist::normalize_items(&items) } +/// What follows `mark` at the start of `line`, when a space or the end of the line closes it: +/// `-a` is a word, `-` alone an empty item. +fn after<'a>(line: &'a str, mark: &str) -> Option<&'a str> { + let rest = line.strip_prefix(mark)?; + (rest.is_empty() || rest.starts_with(char::is_whitespace)).then(|| rest.trim_start()) +} + fn without_marker(line: &str) -> &str { - if let Some(rest) = line - .strip_prefix("- ") - .or_else(|| line.strip_prefix("* ")) - .or_else(|| line.strip_prefix("+ ")) - { - return rest.trim_start(); + if let Some(rest) = ["-", "*", "+"].iter().find_map(|mark| after(line, mark)) { + return rest; } let digits = line.len() - line.trim_start_matches(|c: char| c.is_ascii_digit()).len(); if digits > 0 - && let Some(rest) = line[digits..] - .strip_prefix(". ") - .or_else(|| line[digits..].strip_prefix(") ")) + && let Some(rest) = after(&line[digits..], ".").or_else(|| after(&line[digits..], ")")) { - return rest.trim_start(); + return rest; } line } fn without_box(line: &str) -> (bool, &str) { - for (mark, done) in [("[ ] ", false), ("[x] ", true), ("[X] ", true)] { - if let Some(rest) = line.strip_prefix(mark) { - return (done, rest.trim_start()); + for (mark, done) in [("[ ]", false), ("[x]", true), ("[X]", true)] { + if let Some(rest) = after(line, mark) { + return (done, rest); } } @@ -341,4 +342,12 @@ mod tests { assert!(items_of(text).is_empty(), "{text:?}"); } } + + /// The rich editor writes an empty task as `- [ ] `. + #[test] + fn a_line_with_only_a_marker_or_a_box_gives_no_item() { + let items = items_of("- [ ] \n- [x]\n-\n* \n+\n1.\n2)\n[ ]\n[X]\nkept"); + + assert_eq!(items, [item("kept", false)]); + } } From 76fd41fcf46ecdba51ef35371ec61bd0dc5577a9 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:19:33 +0100 Subject: [PATCH 06/95] Rewrite the tests of language detection around its rules (#1730) The confidence floor, ties, shebangs, the 64 KiB read and when a draft or a patch is read at all; the languages that write alike kept as one table beside the corpus. --- crates/engine/src/notes/language.rs | 480 +++++++++------------------- 1 file changed, 148 insertions(+), 332 deletions(-) diff --git a/crates/engine/src/notes/language.rs b/crates/engine/src/notes/language.rs index 44c6be398..9b4e76819 100644 --- a/crates/engine/src/notes/language.rs +++ b/crates/engine/src/notes/language.rs @@ -1418,43 +1418,20 @@ fn score_puppet(sample: &Sample<'_>) -> u32 { #[cfg(test)] mod tests { use super::*; + use crate::notes::fixtures::note; use crate::notes::kind::NoteKind; use crate::notes::model::NoteLifecycle; use crate::notes::priority::Priority; - #[test] - fn every_variant_round_trips_through_its_stored_form() { - for language in Language::ALL { - assert_eq!(language.as_str().parse(), Ok(language)); - } - } - - #[test] - fn an_unknown_value_is_refused_rather_than_guessed() { - assert_eq!("from-the-future".parse::(), Err(())); - assert_eq!("JSON".parse::(), Err(())); - } - - #[test] - fn the_default_is_the_one_detection_replaces() { - assert_eq!(Language::default(), Language::Txt); - } - - #[test] - fn the_serialized_form_matches_the_stored_one() { - for language in Language::ALL { - let json = serde_json::to_value(language).unwrap(); - assert_eq!(json, serde_json::json!(language.as_str())); - } - } + const RUST: &str = "fn main() {\n println!(\"hi\");\n}"; fn draft(language: Language, content: &str) -> NoteDraft { NoteDraft { - space_id: "s-1".to_string(), + space_id: "s-1".into(), folder_id: None, title: String::new(), language, - content: content.to_string(), + content: content.into(), source: String::new(), tags: Vec::new(), pinned: false, @@ -1465,366 +1442,205 @@ mod tests { } } - #[test] - fn a_draft_with_no_chosen_language_gets_the_detected_one() { - assert_eq!(for_draft(&draft(Language::Txt, "SELECT 1")), Language::Sql); - } - - #[test] - fn a_chosen_language_is_never_overwritten() { - assert_eq!(for_draft(&draft(Language::Md, "SELECT 1")), Language::Md); - } - - #[test] - fn an_empty_draft_stays_plain_text() { - assert_eq!(for_draft(&draft(Language::Txt, "")), Language::Txt); - } - - fn blank_snippet() -> Note { - Note { - language: Language::Txt, - content: String::new(), - ..crate::notes::fixtures::note() - } - } - - fn content_patch(content: &str) -> NotePatch { + fn filling(content: Option<&str>, language: Option) -> NotePatch { NotePatch { - content: Some(content.to_string()), + content: content.map(str::to_string), + language, ..NotePatch::default() } } #[test] - fn an_empty_snippet_receiving_its_first_content_gets_a_language() { - let detected = after_patch( - &blank_snippet(), - &content_patch("interface A { id: string }"), - ); - - assert_eq!(detected, Some(Language::Ts)); - } - - #[test] - fn a_snippet_that_already_had_content_keeps_its_language() { - let note = Note { - content: "some prose".to_string(), - ..blank_snippet() - }; - - assert!(after_patch(¬e, &content_patch("SELECT 1")).is_none()); + fn nothing_written_is_plain_text() { + for content in ["", " \n\t "] { + assert_eq!(from_content(content), Language::Txt, "{content:?}"); + } } #[test] - fn a_chosen_language_is_never_corrected_by_a_later_paste() { - let note = Note { - language: Language::Md, - ..blank_snippet() - }; - - assert!(after_patch(¬e, &content_patch("SELECT 1")).is_none()); + fn prose_is_plain_text() { + assert_eq!(from_content("Hello there, world."), Language::Txt); } #[test] - fn a_patch_setting_the_language_itself_is_left_alone() { - let patch = NotePatch { - language: Some(Language::Md), - ..content_patch("SELECT 1") - }; - - assert!(after_patch(&blank_snippet(), &patch).is_none()); + fn a_shebang_settles_the_language_whatever_follows_it() { + for (content, language) in [ + ("#!/usr/bin/env python3\nSELECT 1;", Language::Py), + (" #!/usr/bin/ruby\n", Language::Rb), + ("#!/usr/bin/node", Language::Js), + ("#!/usr/bin/env -S node --no-warnings", Language::Js), + ("#!/usr/bin/env pwsh", Language::Ps1), + ("#!/usr/local/bin/Rscript", Language::R), + ("#!/bin/bash\n{\"a\": 1}", Language::Sh), + ("#!", Language::Sh), + ] { + assert_eq!(from_content(content), language, "{content:?}"); + } } #[test] - fn a_patch_carrying_no_content_detects_nothing() { - let patch = NotePatch { - title: Some("Title".to_string()), - ..NotePatch::default() - }; - - assert!(after_patch(&blank_snippet(), &patch).is_none()); + fn one_weak_marker_is_no_answer_and_two_are() { + assert_eq!(from_content("a | b"), Language::Txt); + assert_eq!(from_content("$ a | b"), Language::Sh); } #[test] - fn clearing_the_content_does_not_detect() { - assert!(after_patch(&blank_snippet(), &content_patch(" ")).is_none()); + fn two_languages_scoring_alike_are_no_answer() { + assert_eq!(from_content("echo hi\n> note"), Language::Txt); + assert_eq!(from_content("echo hi\n> note\n$ x"), Language::Sh); } #[test] - fn every_detected_language_is_one_the_editor_accepts() { - let samples = [ - "", - "#!/bin/bash\necho hi", - "{\"a\": 1}", - "", - "hi", - "SELECT 1", - "[package]\nname = \"x\"", - "def f():\n pass", - "interface A { }", - "const a = 1", - ".a { color: red; }", - "$a: 1px;\n.b { margin: $a; }", - "query { a }", - "key: value", - "# Title\n\n- item", - "git status", - "just some prose", - ]; - - for sample in samples { - assert!( - Language::ALL.contains(&from_content(sample)), - "sample: {sample}" - ); - } - } + fn only_the_first_64_kib_are_read() { + let past = format!("{}\n{RUST}", "word ".repeat(14_000)); + let within = format!("{}\n{RUST}", "word ".repeat(100)); - #[test] - fn an_empty_or_blank_content_stays_plain_text() { - assert_eq!(from_content(""), Language::Txt); - assert_eq!(from_content(" \n "), Language::Txt); + assert_eq!(from_content(&past), Language::Txt); + assert_eq!(from_content(&within), Language::Rs); } #[test] - fn prose_stays_plain_text() { - assert_eq!( - from_content("Penser à relancer Marc au sujet du certificat"), - Language::Txt - ); - } + fn the_limit_falling_inside_a_character_is_moved_before_it() { + let straddling = format!("a{}", "é".repeat(40_000)); - #[test] - fn a_json_object_or_array_is_recognized() { - assert_eq!(from_content("{\n \"id\": 42\n}"), Language::Json); - assert_eq!(from_content("[1, 2, 3]"), Language::Json); - assert_eq!(from_content(" {\"a\": [1]} "), Language::Json); + assert_eq!(from_content(&straddling), Language::Txt); } #[test] - fn a_shebang_wins_over_everything_that_follows() { - assert_eq!( - from_content("#!/usr/bin/env python3\nconsole.log(1)"), - Language::Py - ); - assert_eq!(from_content("#!/usr/bin/perl -w\nprint 1;"), Language::Perl); - assert_eq!( - from_content("#!/usr/bin/env -S node --no-warnings\n1"), - Language::Js - ); - assert_eq!(from_content("#!/bin/zsh\nprint -l *"), Language::Sh); - assert_eq!(from_content("#!/usr/bin/env tclsh\nputs 1"), Language::Sh); + fn a_draft_keeps_the_language_chosen_and_one_left_plain_is_detected() { + assert_eq!(for_draft(&draft(Language::Sql, RUST)), Language::Sql); + assert_eq!(for_draft(&draft(Language::Txt, RUST)), Language::Rs); + assert_eq!(for_draft(&draft(Language::Txt, "")), Language::Txt); } #[test] - fn markup_splits_between_html_and_xml() { - assert_eq!( - from_content("\n"), - Language::Html - ); - assert_eq!(from_content("
hi
"), Language::Html); - assert_eq!( - from_content("\n"), - Language::Xml - ); - assert_eq!(from_content(""), Language::Xml); - } + fn a_patch_filling_an_empty_plain_snippet_detects_its_language() { + let empty = Note { + content: " ".into(), + language: Language::Txt, + ..note() + }; - #[test] - fn sql_is_recognized_whatever_its_case() { - assert_eq!(from_content("SELECT * FROM notes"), Language::Sql); - assert_eq!(from_content("select 1"), Language::Sql); assert_eq!( - from_content("CREATE TABLE notes (id TEXT PRIMARY KEY)"), - Language::Sql + after_patch(&empty, &filling(Some(RUST), None)), + Some(Language::Rs) ); } #[test] - fn toml_needs_both_a_section_and_an_assignment() { - assert_eq!( - from_content("[package]\nname = \"devnotes\""), - Language::Toml - ); - assert_ne!(from_content("[1, 2]\nx = 3"), Language::Toml); - } + fn a_patch_does_not_detect_over_a_choice_or_an_existing_body() { + let empty = Note { + content: String::new(), + language: Language::Txt, + ..note() + }; + let chosen = Note { + language: Language::Sql, + ..empty.clone() + }; + let written = Note { + content: "already".into(), + ..empty.clone() + }; - #[test] - fn python_is_told_apart_from_typescript_by_its_colon() { - assert_eq!(from_content("def run():\n return 1"), Language::Py); - assert_eq!(from_content("class Note:\n pass"), Language::Py); - assert_eq!(from_content("from os import path"), Language::Py); + for (before, patch) in [ + (&empty, filling(Some(RUST), Some(Language::Sh))), + (&chosen, filling(Some(RUST), None)), + (&written, filling(Some(RUST), None)), + (&empty, filling(None, None)), + (&empty, filling(Some(" \n "), None)), + ] { + assert_eq!(after_patch(before, &patch), None, "{patch:?}"); + } } - /// `class Note { }` is written the same way in Java, C#, PHP, Dart, TypeScript and - /// JavaScript: one weak marker is not an answer. #[test] - fn one_weak_marker_is_not_an_answer() { - assert_eq!(from_content("class Note { }"), Language::Txt); - assert_eq!(from_content("x => x + 1"), Language::Txt); + fn plain_text_is_never_detected_and_each_language_is_scored_once() { + let detected: Vec = detectable().collect(); + let mut unique = detected.clone(); + unique.sort(); + unique.dedup(); + + assert!(!detected.contains(&Language::Txt)); + assert_eq!(unique.len(), detected.len()); } + /// The corpus holds one snippet a language; these are the pairs that write alike. #[test] - fn a_compiled_language_is_not_taken_for_javascript() { - assert_eq!( - from_content( - "fn main() { - println!(\"hi\"); -}" + fn languages_that_write_alike_are_told_apart_by_their_own_markers() { + for (content, language) in [ + ("\n", Language::Html), + ("
hi
", Language::Html), + ("\n", Language::Xml), + ("", Language::Xml), + (" a + b", Language::Js), + ("console.log('hi')", Language::Js), + ( + "match value {\n Some(x) => x,\n}\nlet mut total = 0;", + Language::Rs, ), - Language::Rs - ); - assert_eq!( - from_content( - "match value { - Some(x) => x, -} -let mut total = 0;" + ( + "package main\n\nfunc main() {\n fmt.Println(\"hi\")\n}", + Language::Go, ), - Language::Rs - ); - assert_eq!( - from_content( - "package main - -func main() { - fmt.Println(\"hi\") -}" + ("import java.util.List;\n\nclass Note { }", Language::Java), + ( + "using System;\n\nvar greet = () => Console.WriteLine(\"hi\");", + Language::Cs, ), - Language::Go - ); - assert_eq!( - from_content( - "import java.util.List; - -class Note { }" + ( + "#include \n\nint main(void) { return 0; }", + Language::C, ), - Language::Java - ); - assert_eq!( - from_content( - "using System; - -var greet = () => Console.WriteLine(\"hi\");" + (".card {\n color: red;\n}", Language::Css), + ("@media print {\n a { color: #000; }\n}", Language::Css), + ("$gap: 8px;\n.card {\n padding: $gap;\n}", Language::Scss), + ( + "@use 'mixins' as *;\n.card {\n @include surface;\n}", + Language::Scss, ), - Language::Cs - ); - assert_eq!( - from_content( - "#include - -int main(void) { return 0; }" + ( + ".card {\n color: red;\n &:hover {\n color: blue;\n }\n}", + Language::Scss, ), - Language::C - ); - } - - /// `"), Language::Xml); - } - - #[test] - fn the_languages_detected_before_them_are_left_alone() { - assert_eq!(from_content("export enum Kind { A }"), Language::Ts); - assert_eq!(from_content("interface Note { id: string }"), Language::Ts); - assert_eq!( - from_content( - "def run(): - return 1" + ( + "type Note {\n id: ID!\n tags: [String!]!\n}", + Language::Graphql, ), - Language::Py - ); - assert_eq!(from_content("select 1"), Language::Sql); - assert_eq!(from_content("const add = (a, b) => a + b"), Language::Js); - } - - #[test] - fn typescript_wins_over_javascript_on_its_own_markers() { - assert_eq!(from_content("interface Note { id: string }"), Language::Ts); - assert_eq!(from_content("export type Id = string"), Language::Ts); - assert_eq!(from_content("const a: number = 1"), Language::Ts); - assert_eq!(from_content("const add = (a, b) => a + b"), Language::Js); - assert_eq!(from_content("console.log('hi')"), Language::Js); - } - - #[test] - fn css_needs_a_selector_and_a_declaration() { - assert_eq!(from_content(".card {\n color: red;\n}"), Language::Css); - assert_eq!( - from_content("@media print {\n a { color: #000; }\n}"), - Language::Css - ); - } - - #[test] - fn scss_is_css_with_a_variable_a_mixin_or_nesting() { - assert_eq!( - from_content("$gap: 8px;\n.card {\n padding: $gap;\n}"), - Language::Scss - ); - assert_eq!( - from_content("@use 'mixins' as *;\n.card {\n @include surface;\n}"), - Language::Scss - ); - assert_eq!( - from_content(".card {\n color: red;\n &:hover {\n color: blue;\n }\n}"), - Language::Scss - ); - assert_eq!(from_content(".card {\n color: red;\n}"), Language::Css); - } - - #[test] - fn graphql_is_told_apart_from_typescript_by_its_non_null_types() { - assert_eq!( - from_content("query GetUser($id: ID!) {\n user(id: $id) {\n name\n }\n}"), - Language::Graphql - ); - assert_eq!( - from_content("fragment Card on Note {\n id\n title\n}"), - Language::Graphql - ); - assert_eq!( - from_content("type Note {\n id: ID!\n tags: [String!]!\n}"), - Language::Graphql - ); - assert_eq!( - from_content("type Note = {\n id: string;\n}"), - Language::Ts - ); - assert_ne!(from_content("the query ran twice"), Language::Graphql); - } - - #[test] - fn yaml_is_recognized_by_its_mappings_and_lists() { - assert_eq!(from_content("name: devnotes\nversion: 1"), Language::Yml); - assert_eq!(from_content("---\nsteps:\n - build"), Language::Yml); - } - - #[test] - fn a_bare_url_is_not_read_as_a_yaml_mapping() { - assert_ne!(from_content("https://example.com/a/b"), Language::Yml); - } - - #[test] - fn markdown_is_recognized_by_its_headings_and_fences() { - assert_eq!(from_content("# Heading\n\nA paragraph."), Language::Md); - assert_eq!(from_content("Voir ```code``` ici"), Language::Md); - assert_eq!(from_content("Un [lien](https://x.dev)"), Language::Md); + ("name: devnotes\nversion: 1", Language::Yml), + ("---\nsteps:\n - build", Language::Yml), + ("# Heading\n\nA paragraph.", Language::Md), + ("Un [lien](https://x.dev)", Language::Md), + ("git status\ngit push", Language::Sh), + ] { + assert_eq!(from_content(content), language, "{content:?}"); + } } #[test] - fn shell_commands_are_the_last_resort() { - assert_eq!(from_content("git status\ngit push"), Language::Sh); - assert_eq!(from_content("docker run -p 8080:80 nginx"), Language::Sh); + fn a_near_miss_is_not_taken_for_the_language_it_resembles() { + for (content, not) in [ + ("[1, 2]\nx = 3", Language::Toml), + ("https://example.com/a/b", Language::Yml), + ("the query ran twice", Language::Graphql), + ("class Note { }", Language::Java), + ("x => x + 1", Language::Js), + ] { + assert_ne!(from_content(content), not, "{content:?}"); + } } } From ec7cc02a1e7fa47d68272b96825d8936ca531377 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:27:50 +0100 Subject: [PATCH 07/95] Calcul: unit tests rewritten through what each line gives (#1726) * Rewrite the tests of Calcul sheets through what a line gives The grammar held through evaluate, rule by rule; the lexer's and maths' own tests go, the word and unit tables keep the rules on their spellings. * Reach the Calcul branches the old tests reached * Hold an unfinished proportion as unreadable --- crates/engine/src/notes/calc.rs | 1815 +++++++++++------------ crates/engine/src/notes/calc/lexer.rs | 148 -- crates/engine/src/notes/calc/maths.rs | 93 -- crates/engine/src/notes/calc/summary.rs | 140 +- crates/engine/src/notes/calc/units.rs | 38 +- crates/engine/src/notes/calc/words.rs | 20 - 6 files changed, 987 insertions(+), 1267 deletions(-) diff --git a/crates/engine/src/notes/calc.rs b/crates/engine/src/notes/calc.rs index 73f920045..4cfc9226b 100644 --- a/crates/engine/src/notes/calc.rs +++ b/crates/engine/src/notes/calc.rs @@ -814,278 +814,280 @@ pub fn card_lines(sheet: &str, today: NaiveDate) -> Vec { mod tests { use super::*; - /// On a stack overflow the process stops, the whole test binary with it. - #[test] - fn a_line_nested_past_reason_is_an_error_not_a_crash() { - for line in ["(".repeat(5_000) + "1", "-".repeat(50_000) + "1"] { - let sheet = evaluate(&line, today()); - assert_eq!(sheet.rows.len(), 1); + fn today() -> NaiveDate { + NaiveDate::from_ymd_opt(2026, 7, 25).expect("a day") + } + + /// A row as one short text: `12.5 Euro`, `25 %`, `error: DivisionByZero`. + fn written(line: &CalcLine) -> String { + match line { + CalcLine::Blank => "blank".into(), + CalcLine::Heading { title } => format!("# {title}"), + CalcLine::Comment => "comment".into(), + CalcLine::Text => "text".into(), + CalcLine::Error { error } => format!("error: {error:?}"), + CalcLine::Value { value, .. } => value_text(value), } - let nested = format!("{}2{}", "(".repeat(100), ")".repeat(100)); - assert_eq!(value(&nested), number("2", None)); } - fn today() -> NaiveDate { - NaiveDate::from_ymd_opt(2026, 10, 16).unwrap() + fn unit_text(unit: CalcUnit) -> String { + match unit.per { + Some(per) => format!("{:?}/{per:?}", unit.unit), + None => format!("{:?}", unit.unit), + } } - fn lines(sheet: &str) -> Vec { + fn value_text(value: &CalcValue) -> String { + match value { + CalcValue::Number { value, unit: None } => value.clone(), + CalcValue::Number { + value, + unit: Some(unit), + } => format!("{value} {}", unit_text(*unit)), + CalcValue::Percent { value, signed } => { + format!("{}{value} %", if *signed { "change " } else { "" }) + } + CalcValue::Date { date } => date.to_string(), + CalcValue::Span { parts } => parts + .iter() + .map(|part| format!("{} {:?}", part.value, part.unit)) + .collect::>() + .join(" "), + CalcValue::Base { + digits, + radix, + negative, + } => format!("{}{digits} base {radix}", if *negative { "-" } else { "" }), + CalcValue::Scientific { mantissa, exponent } => format!("{mantissa}e{exponent}"), + CalcValue::Fraction { + numerator, + denominator, + negative, + } => format!( + "{}{numerator}/{denominator}", + if *negative { "-" } else { "" } + ), + CalcValue::Multiplier { value } => format!("×{value}"), + } + } + + fn lines(sheet: &str) -> Vec { evaluate(sheet, today()) .rows - .into_iter() - .map(|row| row.line) + .iter() + .map(|row| written(&row.line)) .collect() } - fn value(line: &str) -> CalcValue { - match lines(line).pop() { - Some(CalcLine::Value { value, .. }) => value, - other => panic!("{line}: {other:?}"), - } + fn last(sheet: &str) -> String { + lines(sheet).pop().expect("a line") } - fn number(value: &str, unit: Option) -> CalcValue { - CalcValue::Number { - value: value.to_string(), - unit: unit.map(|unit| CalcUnit { unit, per: None }), + /// Each line alone on a sheet, against what it gives. + fn check(cases: &[(&str, &str)]) { + for (line, expected) in cases { + assert_eq!(last(line), *expected, "{line:?}"); } } - fn percent(value: &str, signed: bool) -> CalcValue { - CalcValue::Percent { - value: value.to_string(), - signed, - } + // --- Numbers. + + #[test] + fn a_number_takes_a_comma_or_a_point_and_spaces_between_thousands() { + check(&[ + ("42", "42"), + ("1,5", "1.5"), + ("1.5", "1.5"), + ("-3", "-3"), + ("1 578,13", "1578.13"), + ("1\u{a0}578,13", "1578.13"), + ("1\u{202f}578,13", "1578.13"), + ("12 345 678", "12345678"), + ]); } - fn error(line: &str) -> CalcError { - match lines(line).pop() { - Some(CalcLine::Error { error }) => error, - other => panic!("{line}: {other:?}"), - } + #[test] + fn arithmetic_is_exact_in_decimals() { + check(&[ + ("0,1 + 0,2", "0.3"), + ("1 / 3 * 3", "1"), + ("10 / 4", "2.5"), + ("2 ^ 10", "1024"), + ("2 + 3 * 4", "14"), + ("(2 + 3) * 4", "20"), + ("(2 ^ 3) ^ 2", "64"), + ("2 ^ (3 ^ 2)", "512"), + ]); } #[test] - fn the_five_questions_of_the_percentages_tool() { - assert_eq!(value("20 % de 340"), number("68", None)); - assert_eq!(value("30 sur 120 en %"), percent("25", false)); - assert_eq!(value("de 80 à 100"), percent("25", true)); - assert_eq!(value("250 + 20 %"), number("300", None)); - assert_eq!(value("300 hors 20 %"), number("250", None)); + fn a_scale_after_a_number_multiplies_it_m_staying_a_metre() { + check(&[ + ("5 k", "5000"), + ("2 M", "2000000"), + ("1 Md", "1000000000"), + ("1 bn", "1000000000"), + ("1 T", "1000000000000"), + ("3 mille", "3000"), + ("3 thousand", "3000"), + ("2 MILLION", "2000000"), + ("1 milliard", "1000000000"), + ("1 billion", "1000000000"), + ("1 trillion", "1000000000000"), + ("5 m", "5 Metre"), + ]); } #[test] - fn english_words_read_the_same_whatever_the_language_on_screen() { - assert_eq!(value("20 % of 340"), number("68", None)); - assert_eq!(value("from 80 to 100"), percent("25", true)); - assert_eq!(value("5 km in m"), number("5000", Some(UnitId::Metre))); + fn a_base_or_an_exponent_writes_a_number_too() { + check(&[ + ("0xFF", "255"), + ("0b1010", "10"), + ("0o377", "255"), + ("5,3e+3", "5300"), + ("2e-2", "0.02"), + ]); } + // --- Operators. + #[test] - fn units_convert_within_their_kind() { - assert_eq!( - value("38 °C en °F"), - number("100.4", Some(UnitId::Fahrenheit)) - ); - assert_eq!(value("2,5 kg en g"), number("2500", Some(UnitId::Gram))); - assert_eq!( - value("3 h 20 min en min"), - number("200", Some(UnitId::Minute)) - ); - assert_eq!(value("1 Go en Mo"), number("1000", Some(UnitId::Megabyte))); - let CalcValue::Number { value: miles, .. } = value("5 km en mi") else { - panic!() - }; - assert!(miles.starts_with("3.10685")); + fn operators_are_symbols_or_words_in_either_language() { + check(&[ + ("2 plus 3", "5"), + ("2 et 3", "5"), + ("2 and 3", "5"), + ("2 avec 3", "5"), + ("2 with 3", "5"), + ("5 moins 3", "2"), + ("5 minus 3", "2"), + ("5 sans 3", "2"), + ("5 without 3", "2"), + ("2 fois 3", "6"), + ("2 times 3", "6"), + ("2 multiplié par 3", "6"), + ("2 multiplied by 3", "6"), + ("2 mul 3", "6"), + ("6 divisé par 3", "2"), + ("6 divided by 3", "2"), + ("6 × 3", "18"), + ("6 ÷ 3", "2"), + ]); } #[test] - fn a_size_at_a_rate_is_a_duration() { - assert_eq!(value("1,44 To à 100 Mo/s"), number("4", Some(UnitId::Hour))); + fn a_remainder_takes_the_divisor_s_sign() { + check(&[("7 mod 3", "1"), ("-7 mod 3", "2"), ("7 mod -3", "-2")]); } #[test] - fn the_places_a_line_asks_for_travel_with_its_result() { - let places = |sheet: &str| match lines(sheet).pop() { - Some(CalcLine::Value { places, .. }) => places, - other => panic!("no value: {other:?}"), - }; - assert_eq!(places("pi à 5 chiffres"), Some(5)); - assert_eq!(places("1,236 km à 2 décimales"), Some(2)); - assert_eq!(places("pi"), None); - assert_eq!(card_lines("pi à 5 chiffres", today())[0].places, Some(5)); + fn a_parenthesis_right_after_a_value_multiplies_it() { + check(&[("6 (3)", "18"), ("2 (1 + 1)", "4")]); } #[test] - fn a_price_per_hour_times_hours_is_euros() { - let sheet = "prix = 0,045 €/h\nserveurs = 3\ncoût = prix × 730 h × serveurs"; - assert_eq!( - lines(sheet).pop(), - Some(CalcLine::Value { - value: number("98.55", Some(UnitId::Euro)), - name: Some("coût".into()), - aggregate: false, - dimension: Dimension::Euro, - places: None, - }) - ); - assert_eq!( - value("0,045 €/h"), - CalcValue::Number { - value: "0.045".into(), - unit: Some(CalcUnit { - unit: UnitId::Euro, - per: Some(UnitId::Hour) - }) - } - ); + fn bit_operations_take_whole_numbers_below_the_sums() { + check(&[ + ("6 & 3", "2"), + ("6 | 3", "7"), + ("6 xor 3", "5"), + ("1 << 4", "16"), + ("256 >> 4", "16"), + ("1 + 1 << 2", "8"), + ("1,5 & 1", "error: NotWhole"), + ]); } #[test] - fn a_percentage_taken_off_then_added_is_a_share_each_time() { - let sheet = "coût = 98,55 €\nremise = 15 %\nttc = coût − remise + 20 %"; - assert_eq!( - match lines(sheet).pop() { - Some(CalcLine::Value { value, .. }) => value, - _ => panic!(), - }, - number("100.521", Some(UnitId::Euro)) - ); + fn a_division_by_zero_is_an_error_of_its_own() { + check(&[ + ("1 / 0", "error: DivisionByZero"), + ("5 mod 0", "error: DivisionByZero"), + ]); } + // --- Words around the figures. + #[test] - fn dates_move_by_days_weeks_and_months_and_subtract_into_days() { - assert_eq!( - value("aujourd'hui + 45 jours"), - CalcValue::Date { - date: NaiveDate::from_ymd_opt(2026, 11, 30).unwrap() - } - ); - assert_eq!( - value("today + 2 wk"), - CalcValue::Date { - date: NaiveDate::from_ymd_opt(2026, 10, 30).unwrap() - } - ); - assert_eq!( - value("31/01/2026 + 1 mois"), - CalcValue::Date { - date: NaiveDate::from_ymd_opt(2026, 2, 28).unwrap() - } - ); - assert_eq!( - value("16/10/2026 − 01/01/2026"), - number("288", Some(UnitId::Day)) - ); - assert_eq!(error("aujourd'hui + 3 h"), CalcError::DateShift); + fn a_label_before_a_colon_is_read_past() { + check(&[("Prix : 11 € + 34,45 €", "45.45 Euro")]); + } + + #[test] + fn words_leading_up_to_a_result_and_quoted_text_are_read_past() { + check(&[ + ("275 € pour le \"Modèle 227\"", "275 Euro"), + ("999 € (pour l'iPhone)", "999 Euro"), + ]); + } + + #[test] + fn words_alone_after_a_result_are_an_error_not_prose() { + assert!(last("5 jours ouvrés").starts_with("error:")); + } + + #[test] + fn a_line_with_no_figure_and_no_name_is_a_sentence() { + check(&[("Les courses de la semaine", "text")]); } #[test] - fn a_duration_into_weeks_keeps_the_days_left() { + fn a_comment_line_and_a_heading_compute_nothing() { assert_eq!( - value("45 jours en sem"), - CalcValue::Span { - parts: vec![ - SpanPart { - value: "6".into(), - unit: UnitId::Week - }, - SpanPart { - value: "3".into(), - unit: UnitId::Day - }, - ] - } + lines("// note\n# Budget\n"), + ["comment", "# Budget", "blank"] ); - let sheet = "livraison = aujourd'hui + 45 jours\nlivraison − aujourd'hui en sem"; - assert!(matches!( - lines(sheet).pop(), - Some(CalcLine::Value { - value: CalcValue::Span { .. }, - .. - }) - )); } #[test] - fn total_and_mean_read_the_block_above_and_a_heading_starts_another() { - let sheet = - "# Budget\na = 100 €\nb = 26 €\nmensuel = total\nmensuel × 12\n\nc = 3 €\nmoyenne"; - let found = lines(sheet); + fn a_comment_after_an_expression_is_read_past() { + check(&[("2 + 2 // 4", "4")]); + } + + // --- Names and the lines above. + + #[test] + fn a_name_holds_its_result_from_its_line_down() { assert_eq!( - found[3], - CalcLine::Value { - value: number("126", Some(UnitId::Euro)), - name: Some("mensuel".into()), - aggregate: true, - dimension: Dimension::Euro, - places: None, - } - ); - assert!( - matches!(&found[4], CalcLine::Value { value, .. } if *value == number("1512", Some(UnitId::Euro))) + lines("prix = 120 €\nprix * 2\nprix = 10 €\nprix * 2"), + ["120 Euro", "240 Euro", "10 Euro", "20 Euro"] ); - assert!( - matches!(&found[7], CalcLine::Value { value, .. } if *value == number("3", Some(UnitId::Euro))) - ); - assert_eq!(error("total"), CalcError::NothingAbove); } #[test] - fn an_error_stays_on_its_line_and_says_why() { - let sheet = "distance = 5 km\ndistance + 3 Go\ndistance en m"; - let found = lines(sheet); + fn a_name_used_before_it_is_given_is_unknown() { assert_eq!( - found[1], - CalcLine::Error { - error: CalcError::Mismatch { - expected: Dimension::Length, - found: Dimension::Data, - unit: Some(CalcUnit { - unit: UnitId::Gigabyte, - per: None - }), - } - } + lines("taux * 2\ntaux = 3"), + ["error: UnknownName { name: \"taux\" }", "3"] ); - assert!(matches!(found[2], CalcLine::Value { .. })); - assert_eq!(error("x + 1"), CalcError::UnknownName { name: "x".into() }); - assert_eq!(error("4 / 0"), CalcError::DivisionByZero); } #[test] - fn a_conversion_between_currencies_is_refused_offline() { - assert_eq!(error("100 € en $"), CalcError::Currency); - assert!(matches!(error("100 € + 3 $"), CalcError::Mismatch { .. })); - assert_eq!(value("100 € × 3"), number("300", Some(UnitId::Euro))); + fn a_word_of_the_grammar_cannot_be_a_name() { + check(&[("en = 5", "error: Reserved { word: \"en\" }")]); } #[test] - fn headings_comments_and_sentences_have_no_result_and_no_error() { + fn a_name_defined_above_hides_a_value_word_from_its_line_down() { assert_eq!( - lines("# Planning\n// une remarque\nLe serveur de recette\n"), - [ - CalcLine::Heading { - title: "Planning".into() - }, - CalcLine::Comment, - CalcLine::Text, - CalcLine::Blank, - ] + lines("1\n2\ntotal\ntotal = 7\ntotal + 1"), + ["1", "2", "3", "7", "8"] ); } #[test] - fn a_copied_sheet_reads_back_with_its_results_as_comments() { + fn previous_is_the_last_result_above() { assert_eq!( - value("prix = 120 € // 120,00 €"), - number("120", Some(UnitId::Euro)) + lines("10\nphrase sans chiffre\npréc * 2\nprev + 1"), + ["10", "text", "20", "21"] ); + check(&[("préc", "error: NoPrevious")]); } #[test] - fn a_variable_says_where_it_is_given_and_read() { - let sheet = evaluate("a = 2\nb = a × 3\na = 5\na + b", today()); + fn the_variables_say_where_each_name_was_given_and_which_lines_read_it() { + let sheet = evaluate("a = 2\nb = a * a\na = 5\na + b", today()); + let found: Vec<_> = sheet .variables .iter() @@ -1095,860 +1097,833 @@ mod tests { found, [("a", 0, vec![1]), ("b", 1, vec![3]), ("a", 2, vec![3])] ); + assert_eq!(value_text(&sheet.variables[1].value), "4"); } + // --- Blocks. + #[test] - fn the_editor_is_told_what_kind_is_being_converted_and_where_the_words_are() { - let sheet = evaluate("3 h 20 min en ", today()); - let row = &sheet.rows[0]; - assert_eq!(row.converting, Some(Dimension::Time)); - assert!(matches!( - row.line, - CalcLine::Error { - error: CalcError::Unreadable { .. } - } - )); - let kinds: Vec<_> = row.spans.iter().map(|span| span.kind).collect(); + fn total_and_mean_read_the_quantities_above_in_their_block() { assert_eq!( - kinds, + lines("10 €\n20 €\ntotal\nmoyenne\n\n5 €\ntotal"), [ - TokenKind::Number, - TokenKind::Unit, - TokenKind::Number, - TokenKind::Unit, - TokenKind::Keyword + "10 Euro", "20 Euro", "30 Euro", "15 Euro", "blank", "5 Euro", "5 Euro" ] ); } #[test] - fn a_card_shows_the_last_four_lines_that_gave_something() { - let sheet = "a = 1\nb = 2\n// c\nc = 3\nd = 4\ne = 5 // 5\nnope +"; - let card = card_lines(sheet, today()); - let expressions: Vec<_> = card.iter().map(|line| line.expression.as_str()).collect(); - assert_eq!(expressions, ["b = 2", "c = 3", "d = 4", "e = 5"]); + fn a_heading_starts_a_block_as_a_blank_line_does() { + assert_eq!(lines("10\n# Next\n3\ntotal"), ["10", "# Next", "3", "3"]); + assert_eq!(lines("10\n# Next\n3\nsum")[3], "3"); } #[test] - fn a_syntax_word_is_no_name_and_says_so_on_its_line_alone() { - let found = lines("a = 2\nen = 5\nDe = 1\na × 3"); - assert_eq!( - found[1], - CalcLine::Error { - error: CalcError::Reserved { word: "en".into() } - } - ); - assert_eq!( - found[2], - CalcLine::Error { - error: CalcError::Reserved { word: "De".into() } - } - ); - assert!(matches!(&found[3], CalcLine::Value { value, .. } if *value == number("6", None))); - let row = &evaluate("en = 5", today()).rows[0]; + fn a_total_with_nothing_above_in_its_block_is_an_error() { + assert_eq!(lines("5\n\ntotal"), ["5", "blank", "error: NothingAbove"]); + } + + #[test] + fn a_total_is_marked_as_an_aggregate_and_not_added_again() { + let sheet = evaluate("1\n2\ntotal\ntotal", today()); + + let aggregates: Vec<_> = sheet + .rows + .iter() + .map(|row| { + matches!( + row.line, + CalcLine::Value { + aggregate: true, + .. + } + ) + }) + .collect(); + assert_eq!(aggregates, [false, false, true, true]); + assert_eq!(written(&sheet.rows[3].line), "3"); + } + + // --- Units. + + #[test] + fn quantities_of_one_kind_add_up_in_the_unit_written_first() { + check(&[ + ("1 km + 500 m", "1.5 Kilometre"), + ("500 g + 1 kg", "1500 Gram"), + ("1 Go + 512 Mo", "1.512 Gigabyte"), + ("2 € + 3 €", "5 Euro"), + ]); + } + + #[test] + fn quantities_written_side_by_side_add_up() { + check(&[ + ("3 h 20 min en min", "200 Minute"), + ("1 m 20 cm", "1.2 Metre"), + ]); + } + + #[test] + fn en_or_a_conversion_word_writes_a_quantity_in_another_unit() { + check(&[ + ("1 km en m", "1000 Metre"), + ("1 mile in km", "1.609344 Kilometre"), + ("2 h to min", "120 Minute"), + ("1 kg as g", "1000 Gram"), + ("1 Gio en Mio", "1024 Mebibyte"), + ("12 pt en px", "16 Pixel"), + ]); + } + + #[test] + fn a_temperature_is_converted_by_formula() { + check(&[ + ("100 °C en °F", "212 Fahrenheit"), + ("32 °F en °C", "0 Celsius"), + ("0 °C en K", "273.15 Kelvin"), + ("38 °C en °F", "100.4 Fahrenheit"), + ("0 K en °C", "-273.15 Celsius"), + ]); + } + + #[test] + fn quantities_of_different_kinds_do_not_mix() { + assert!(last("1 km + 3 Go").starts_with("error: Mismatch")); + assert!(last("1 € + 1 $").starts_with("error: Mismatch")); + assert!(last("1 kg en m").starts_with("error: NotConvertible")); + } + + #[test] + fn euros_and_dollars_are_never_converted_into_each_other() { + check(&[ + ("100 € en $", "error: Currency"), + ("100 $ en €", "error: Currency"), + ]); + } + + #[test] + fn a_quantity_carries_its_dimensions_through_a_product_or_a_quotient() { + check(&[ + ("20 €/h * 3 h", "60 Euro"), + ("100 km / 2 h", "50 Kilometre/Hour"), + ("1 / 2 s", "0.5 Hertz"), + ("60 Hz * 2 s", "120"), + ("1 Go / 1 Mo/s en s", "1000 Second"), + ]); + } + + #[test] + fn a_rate_kept_as_a_fraction_reads_back_exactly() { + check(&[("0,045 €/h * 1 h", "0.045 Euro")]); + } + + #[test] + fn a_duration_of_no_unit_written_is_shown_in_the_largest_unit_it_fills() { + check(&[ + ("100 km / 50 km/h", "2 Hour"), + ("86400 m / 1 m/s", "1 Day"), + ("1 m / 4 m/s", "250 Millisecond"), + ]); + } + + #[test] + fn a_duration_converted_keeps_the_whole_units_and_what_is_left() { + check(&[ + ("45 jours en sem", "6 Week 3 Day"), + ("90 min en h", "1 Hour 30 Minute"), + ("14 jours en sem", "2 Week"), + ]); + } + + // --- Screen units. + + #[test] + fn a_pixel_an_em_and_a_rem_follow_the_sheet_s_settings_from_their_line_down() { assert_eq!( - row.spans, - [CalcSpan { - start: 0, - end: 2, - kind: TokenKind::Error - }] + lines( + "3 in en px\nppi = 326\n1 in en px\n2 em en px\nem = 20 px\n2 em en px\nrem = 18\n1 rem en px" + ), + [ + "288 Pixel", + "326", + "326 Pixel", + "32 Pixel", + "20 Pixel", + "40 Pixel", + "18 Pixel", + "18 Pixel" + ] ); } #[test] - fn a_name_hides_a_value_word_from_its_line_down() { - let found = - lines("a = 2\nb = 3\ntotal\ntotal = 10\ntotal + 1\naujourd'hui = 4\naujourd'hui × 2"); - assert!( - matches!(&found[2], CalcLine::Value { value, aggregate: true, .. } if *value == number("5", None)) - ); - assert!(matches!( - &found[3], - CalcLine::Value { name: Some(name), aggregate: false, .. } if name == "total" - )); - assert!( - matches!(&found[4], CalcLine::Value { value, aggregate: false, .. } if *value == number("11", None)) - ); - assert!(matches!(&found[6], CalcLine::Value { value, .. } if *value == number("8", None))); + fn a_setting_is_above_zero_and_no_name_for_total() { + assert_eq!(lines("ppi = 0"), ["error: NotPositive"]); + assert_eq!(lines("ppi = 200\ntotal"), ["200", "error: NothingAbove"]); + assert!(last("ppi = 3 kg").starts_with("error: Mismatch")); + } + + #[test] + fn in_is_an_inch_after_a_number_and_a_conversion_before_a_notation() { + check(&[ + ("2 in en cm", "5.08 Centimetre"), + ("255 in hex", "FF base 16"), + ]); + } + + // --- Functions and constants. + + #[test] + fn functions_take_their_argument_with_or_without_parentheses() { + check(&[ + ("sqrt 16", "4"), + ("racine(16)", "4"), + ("racine 3 (8)", "2"), + ("cbrt 27", "3"), + ("log 2 (8)", "3"), + ("log 1000", "3"), + ("abs -3", "3"), + ("arrondi(2,5)", "3"), + ("round 2,4", "2"), + ("plafond 2,1", "3"), + ("ceil 2,1", "3"), + ("plancher 2,9", "2"), + ("floor -2,1", "-3"), + ]); + } + + #[test] + fn a_root_or_a_logarithm_outside_its_domain_is_an_error_of_its_own() { + check(&[ + ("sqrt -4", "error: NegativeRoot"), + ("log 0", "error: LogDomain"), + ("ln -1", "error: LogDomain"), + ("log 1 (8)", "error: LogDomain"), + ]); + } + + #[test] + fn constants_are_named_and_a_name_hides_them() { + assert!(last("pi").starts_with("3.14159265358979")); + assert!(last("τ").starts_with("6.28318530717958")); + assert!(last("e").starts_with("2.71828182845904")); + assert!(last("phi").starts_with("1.61803398874989")); + assert_eq!(lines("pi = 3\npi * 2"), ["3", "6"]); + } + + #[test] + fn the_largest_or_smallest_of_numbers_of_one_kind() { + check(&[ + ("le plus grand de 100 et 200", "200"), + ("larger of 3 and 9 and 4", "9"), + ("le plus petit de 3 et 1", "1"), + ("le plus grand de 2 m et 150 cm", "2 Metre"), + ]); + } + + // --- Rounding. - let found = lines("a = 2\ntotal = total\ntotal"); + #[test] + fn a_line_rounds_its_own_value_and_says_its_places() { + let sheet = evaluate("1 / 3 à 2 décimales\npréc * 3", today()); + + assert_eq!(written(&sheet.rows[0].line), "0.33"); assert!(matches!( - &found[1], + sheet.rows[0].line, CalcLine::Value { - aggregate: true, + places: Some(2), .. } )); - assert!( - matches!(&found[2], CalcLine::Value { value, aggregate: false, .. } if *value == number("2", None)) - ); + assert_eq!(written(&sheet.rows[1].line), "0.99"); } #[test] - fn a_form_of_several_words_wins_over_a_name_of_one() { - assert_eq!( - cents("mensualité = 100 €\nmensualité de 10 000 € sur 6 ans à 6 %"), - number("165.73", Some(UnitId::Euro)) - ); - assert_eq!( - value("mensualité = 100 €\nmensualité + 1 €"), - number("101", Some(UnitId::Euro)) - ); - assert_eq!( - cents("total = $2\ntotal cost of $10,000 over 6 years at 6%"), - number("11932.48", Some(UnitId::Dollar)) - ); - assert_eq!( - value("racine = 5\nracine carrée(16) + racine"), - number("9", None) - ); + fn rounding_words_round_half_away_up_down_or_to_a_step() { + check(&[ + ("2 / 3 to 3 dp", "0.667"), + ("1 / 7 à 5 chiffres", "0.14286"), + ("2,5 arrondi", "3"), + ("-2,5 rounded", "-3"), + ("2,1 arrondi supérieur", "3"), + ("2,9 arrondi inférieur", "2"), + ("1234 au 10 près", "1230"), + ("1235 to nearest 10", "1240"), + ("1234 au millier près", "1000"), + ("1251 à la centaine près", "1300"), + ("11 arrondi supérieur au 5 près", "15"), + ]); } #[test] - fn each_concept_reads_in_french_and_in_english() { - let date = |days: u64| CalcValue::Date { - date: today().checked_add_days(chrono::Days::new(days)).unwrap(), - }; - let pairs = [ - ("5 km en m", "5 km in m"), - ("5 km vers m", "5 km as m"), - ("1,44 To à 100 Mo/s", "1,44 To at 100 Mo/s"), - ("20 % de 340", "20 % of 340"), - ("de 80 à 100", "from 80 to 100"), - ("30 sur 120 en %", "30 over 120 as %"), - ("300 hors 20 %", "300 excluding 20 %"), - ("300 ex 20 %", "300 excl 20 %"), - ("a = 1\nb = 3\nsomme", "a = 1\nb = 3\nsum"), - ("a = 1\nb = 3\nmoyenne", "a = 1\nb = 3\navg"), - ("demain", "tomorrow"), - ]; - for (french, english) in pairs { - assert_eq!(value(french), value(english), "{french} / {english}"); - } - assert_eq!(value("demain"), date(1)); - assert_eq!(value("Aujourd'hui"), date(0)); + fn a_quantity_rounds_in_the_unit_it_is_shown_in() { + check(&[("1 km / 3 en m à 1 décimale", "333.3 Metre")]); } + // --- Notations. + #[test] - fn a_sheet_written_before_the_table_reads_the_same() { - let sheet = "# Budget\nhébergement = 100,521 €\ndomaines = 4,99 €\nmensuel = total\nmensuel × 12\n3 h 20 min en min\n20 % of 340\n100 € en $"; - let found = lines(sheet); - assert_eq!(found.len(), 8); - assert_eq!( - found[0], - CalcLine::Heading { - title: "Budget".into() - } - ); - assert!( - matches!(&found[3], CalcLine::Value { value, aggregate: true, .. } if *value == number("105.511", Some(UnitId::Euro))) - ); - assert!( - matches!(&found[4], CalcLine::Value { value, .. } if *value == number("1266.132", Some(UnitId::Euro))) - ); + fn a_plain_number_is_written_in_the_notation_the_line_asks() { + check(&[ + ("255 en hex", "FF base 16"), + ("10 en base 2", "1010 base 2"), + ("8 en oct", "10 base 8"), + ("hex(255)", "FF base 16"), + ("bin(5)", "101 base 2"), + ("-255 en hex", "-FF base 16"), + ("int(0xFF)", "255"), + ("5300 en sci", "5.3e3"), + ("2 / 10 en fraction", "1/5"), + ("-1 / 3 en fraction", "-1/3"), + ("20 / 5 en multiple", "×4"), + ("20 % en décimal", "0.2"), + ]); + } + + #[test] + fn a_fraction_in_a_base_is_an_error() { + check(&[("1,5 en hex", "error: NotWhole")]); + } + + // --- Percentages. + + #[test] + fn the_five_questions_of_the_percentages_tool_are_lines() { + check(&[ + ("20 % de 340", "68"), + ("30 sur 120 en %", "25 %"), + ("de 80 à 100", "change 25 %"), + ("250 + 20 %", "300"), + ("300 hors 20 %", "250"), + ]); + } + + #[test] + fn a_share_is_taken_against_what_the_words_say() { + check(&[ + ("5 % de plus sur 200", "210"), + ("5 % de moins sur 200", "190"), + ("5% on 200", "210"), + ("5% off 200", "190"), + ("5 % de combien font 6", "120"), + ("5% of what is 6", "120"), + ("50 en % de 100", "50 %"), + ("70 as a % on 20", "250 %"), + ("180 c'est combien de % de moins que 200", "10 %"), + ("50 à 75 c'est combien de %", "change 50 %"), + ("40 to 90 as %", "change 125 %"), + ]); + } + + #[test] + fn a_percentage_added_to_a_quantity_is_a_share_of_it() { + check(&[("100 € + 20 %", "120 Euro"), ("2 h - 50 %", "1 Hour")]); + } + + #[test] + fn a_proportion_solves_for_its_unknown() { + check(&[ + ("6 est à 60 ce que 8 est à combien", "80"), + ("6 is to 60 as 8 is to what", "80"), + ]); + } + + // --- Finance. + + #[test] + fn money_grows_compounded_yearly_unless_the_line_says_otherwise() { + check(&[ + ("1 000 € après 3 ans à 7 %", "1225.043 Euro"), + ("$1,000 after 2 years @ 10%", "1210 Dollar"), + ("intérêts sur 1 000 € après 2 ans à 10 %", "210 Euro"), + ]); + assert!(last("1 000 € après 1 an à 12 % composés mensuellement").starts_with("1126.82")); + } + + #[test] + fn a_return_a_present_value_and_a_loan_are_lines() { + check(&[ + ("500 € investis 1 500 € récupérés", "×3"), + ("valeur actuelle de 1 210 € dans 2 ans à 10 %", "1000 Euro"), + ]); + assert!(last("mensualité de 10 000 € sur 1 an à 12 %").starts_with("888.48")); assert!( - matches!(&found[5], CalcLine::Value { value, .. } if *value == number("200", Some(UnitId::Minute))) - ); - assert!(matches!(&found[6], CalcLine::Value { value, .. } if *value == number("68", None))); - assert_eq!( - found[7], - CalcLine::Error { - error: CalcError::Currency - } + last("rendement annuel sur 100 € investis 200 € récupérés en 1 an").starts_with("100") ); } #[test] - fn operators_are_written_in_words_in_both_languages() { - let cases = [ - ("10 plus 5", "15"), - ("10 et 5", "15"), - ("10 and 5", "15"), - ("10 avec 5", "15"), - ("10 with 5", "15"), - ("10 moins 4", "6"), - ("10 minus 4", "6"), - ("10 subtract 4", "6"), - ("200 sans 30", "170"), - ("200 without 30", "170"), - ("8 fois 9", "72"), - ("8 times 9", "72"), - ("6 multiplié par 7", "42"), - ("6 multiplied by 7", "42"), - ("6 mul 7", "42"), - ("42 divisé par 6", "7"), - ("42 divided by 6", "7"), - ("42 divide by 6", "7"), - ("17 mod 5", "2"), - ("17 modulo 5", "2"), - ("-7 mod 3", "2"), - ("2 + 3 fois 4", "14"), - ]; - for (line, result) in cases { - assert_eq!(value(line), number(result, None), "{line}"); - } - assert_eq!( - value("17 km mod 5 km"), - number("2", Some(UnitId::Kilometre)) - ); - assert_eq!(error("5 mod 0"), CalcError::DivisionByZero); - assert!(matches!(error("17 km mod 5"), CalcError::Mismatch { .. })); - assert_eq!( - error("fois = 3"), - CalcError::Reserved { - word: "fois".into() - } - ); + fn a_yearly_rate_is_a_percentage() { + check(&[("1 000 € après 3 ans à 7", "error: RateExpected")]); } + // --- Dates. + #[test] - fn without_subtracts_and_hors_still_takes_a_share_back_off() { - assert_eq!(value("300 sans 20 %"), number("240", None)); - assert_eq!(value("300 without 20 %"), number("240", None)); - assert_eq!(value("300 hors 20 %"), number("250", None)); - assert_eq!(value("300 excluding 20 %"), number("250", None)); + fn today_tomorrow_and_yesterday_are_the_day_given() { + check(&[ + ("aujourd'hui", "2026-07-25"), + ("aujourd’hui", "2026-07-25"), + ("today", "2026-07-25"), + ("demain", "2026-07-26"), + ("yesterday", "2026-07-24"), + ]); } #[test] - fn a_parenthesis_after_a_value_multiplies_it() { - assert_eq!(value("6 (3)"), number("18", None)); - assert_eq!(value("2 (3 + 4)"), number("14", None)); - assert_eq!(value("(1 + 2)(3 + 1)"), number("12", None)); - assert_eq!(value("a = 4\n3 (a)"), number("12", None)); + fn a_date_moves_by_days_and_by_calendar_months_and_years() { + check(&[ + ("aujourd'hui + 10 jours", "2026-08-04"), + ("aujourd'hui + 2 sem", "2026-08-08"), + ("aujourd'hui + 1 mois", "2026-08-25"), + ("aujourd'hui - 12 mois", "2025-07-25"), + ("aujourd'hui + 3 h", "error: DateShift"), + ]); } #[test] - fn the_previous_result_is_the_last_line_above_that_gave_one() { - assert_eq!(value("10 + 5\npréc × 2"), number("30", None)); - assert_eq!(value("10 + 5\n// double\n\nprev × 2"), number("30", None)); - assert_eq!( - value("a = 3 €\nx +\nprécédent + 1 €"), - number("4", Some(UnitId::Euro)) - ); - assert_eq!(error("préc + 1"), CalcError::NoPrevious); - assert_eq!(value("préc = 2\npréc × 3"), number("6", None)); + fn two_dates_subtract_into_days() { + check(&[("demain - hier", "2 Day")]); } + // --- Errors. + #[test] - fn a_label_a_quote_and_a_remark_are_left_out_of_the_computation() { - assert_eq!( - value("Prix : 11 € + 34,45 €"), - number("45.45", Some(UnitId::Euro)) - ); - assert_eq!(value("Mensuel : 1200 / 12"), number("100", None)); - assert_eq!(value("Price HT : ht = 100\nht × 2"), number("200", None)); - assert_eq!( - value("275 € pour le \"Modèle 227\""), - number("275", Some(UnitId::Euro)) - ); - assert_eq!(value("275 for the « Model 227 »"), number("275", None)); - assert_eq!( - value("\"Loyer\" 800 € + 50 €"), - number("850", Some(UnitId::Euro)) - ); - assert_eq!( - value("999 € (pour l'iPhone, en promo)"), - number("999", Some(UnitId::Euro)) - ); - assert_eq!( - value("999 € (for iPhone) + 1 €"), - number("1000", Some(UnitId::Euro)) - ); - assert_eq!(value("2 × (3 + 4)"), number("14", None)); - assert!(matches!( - error("5 jours ouvrés"), - CalcError::Unreadable { .. } - )); + fn an_error_stays_on_its_line_and_the_others_go_on() { + assert_eq!(lines("1 / 0\n2 + 2"), ["error: DivisionByZero", "4"]); + } - let row = &evaluate("Prix : 11 € \"x\"", today()).rows[0]; - let kinds: Vec<_> = row.spans.iter().map(|span| span.kind).collect(); - assert_eq!( - kinds, - [ - TokenKind::Comment, - TokenKind::Number, - TokenKind::Unit, - TokenKind::Comment - ] - ); - assert_eq!((row.spans[0].start, row.spans[0].end), (0, 6)); - assert_eq!(lines("Prix :"), [CalcLine::Text]); + #[test] + fn an_unreadable_line_says_where_in_utf_16_units() { + check(&[("2 € + * 3", "error: Unreadable { at: 6 }")]); } #[test] - fn large_numbers_are_written_with_their_scale() { - let cases = [ - ("2k", "2000"), - ("3M", "3000000"), - ("1,5 milliard", "1500000000"), - ("2 Md", "2000000000"), - ("2 bn", "2000000000"), - ("1 T", "1000000000000"), - ("1 tn", "1000000000000"), - ("10 mille", "10000"), - ("10 thousand", "10000"), - ("2 millions", "2000000"), - ("1 billion", "1000000000"), - ("1 trillion", "1000000000000"), - ("1 mille milliards", "1000000000000"), - ]; - for (line, result) in cases { - assert_eq!(value(line), number(result, None), "{line}"); - } - assert_eq!(value("2k €"), number("2000", Some(UnitId::Euro))); - assert_eq!(value("3 m"), number("3", Some(UnitId::Metre))); - assert_eq!(value("2 K"), number("2", Some(UnitId::Kelvin))); - assert_eq!(value("k = 5\n2k"), number("2000", None)); + fn a_result_past_what_a_decimal_holds_overflows() { + check(&[("10 ^ 40", "error: Overflow")]); } + // --- The sheet. + #[test] - fn thousands_grouped_by_a_space_read_back_as_the_front_writes_them() { - assert_eq!(value("5 300"), number("5300", None)); + fn a_sheet_is_one_row_a_line_windows_endings_included() { + assert_eq!(lines("1\r\n2\r\n"), ["1", "2", "blank"]); + assert_eq!(lines(""), ["blank"]); + } + + #[test] + fn a_result_is_tidied_to_25_figures() { + check(&[("2 / 3", "0.6666666666666666666666667")]); + } + + #[test] + fn the_spans_colour_each_token_in_utf_16_units() { + let sheet = evaluate("a = 1 km\né = 2 km + a // x", today()); + + let spans: Vec<_> = sheet.rows[1] + .spans + .iter() + .map(|span| (span.start, span.end, span.kind)) + .collect(); assert_eq!( - value("1\u{202f}578,13 € + 1 €"), - number("1579.13", Some(UnitId::Euro)) + spans, + [ + (0, 1, TokenKind::Name), + (2, 3, TokenKind::Operator), + (4, 5, TokenKind::Number), + (6, 8, TokenKind::Unit), + (9, 10, TokenKind::Operator), + (11, 12, TokenKind::Name), + (13, 17, TokenKind::Comment), + ] ); + } + + #[test] + fn a_label_and_a_setting_are_coloured_apart_from_names() { + let kinds = |line: &str| -> Vec { + evaluate(line, today()).rows[0] + .spans + .iter() + .map(|span| span.kind) + .collect() + }; + assert_eq!( - value("1\u{a0}578,13 €"), - number("1578.13", Some(UnitId::Euro)) + kinds("Prix : 3")[..2], + [TokenKind::Comment, TokenKind::Number] ); + assert_eq!(kinds("ppi = 300")[0], TokenKind::Keyword); + assert_eq!(kinds("Une phrase"), []); + assert_eq!(kinds("en = 5")[0], TokenKind::Error); } - fn starts(line: &str, figures: &str) { - match value(line) { - CalcValue::Number { value, .. } => { - assert!(value.starts_with(figures), "{line}: {value}"); - } - other => panic!("{line}: {other:?}"), - } + #[test] + fn after_en_or_a_the_row_says_what_kind_is_being_converted() { + let converting = |line: &str| evaluate(line, today()).rows[0].converting; + + assert_eq!(converting("5 km en"), Some(Dimension::Length)); + assert_eq!(converting("3 h en min"), Some(Dimension::Time)); + assert_eq!(converting("5 km"), None); } - fn based(digits: &str, radix: u32) -> CalcValue { - CalcValue::Base { - digits: digits.into(), - radix, - negative: false, - } + #[test] + fn a_line_says_the_dimension_of_its_result() { + let dimension = |line: &str| match evaluate(line, today()).rows[0].line { + CalcLine::Value { dimension, .. } => dimension, + _ => panic!("a value"), + }; + + assert_eq!(dimension("3 km"), Dimension::Length); + assert_eq!(dimension("3"), Dimension::Number); + assert_eq!(dimension("aujourd'hui"), Dimension::Date); + assert_eq!(dimension("20 €/h"), Dimension::Rate); } + // --- A card. + #[test] - fn a_line_rounds_its_own_value_in_both_languages() { - let cases = [ - ("1/3 à 2 décimales", "0.33"), - ("1/3 to 2 dp", "0.33"), - ("2/3 à 1 décimale", "0.7"), - ("pi à 5 chiffres", "3.14159"), - ("pi to 5 digits", "3.14159"), - ("5,5 arrondi", "6"), - ("5,5 rounded", "6"), - ("-5,5 arrondi", "-6"), - ("5,5 arrondi inférieur", "5"), - ("5,5 rounded down", "5"), - ("5,2 arrondi supérieur", "6"), - ("5,2 rounded up", "6"), - ("37 au 10 près", "40"), - ("37 to nearest 10", "40"), - ("2100 au millier près", "2000"), - ("2100 to nearest thousand", "2000"), - ("490 à la centaine près", "500"), - ("490 to the nearest hundred", "500"), - ("21 arrondi supérieur au 5 près", "25"), - ("21 rounded up to nearest 5", "25"), - ]; - for (line, result) in cases { - assert_eq!(value(line), number(result, None), "{line}"); - } - assert_eq!(value("x = 1/3 à 2 décimales\nx × 3"), number("0.99", None)); + fn a_card_shows_the_last_four_lines_that_gave_something() { + let sheet = "1\n2\nnot read\n3\n# h\n4 // four\n5\n1 / 0"; + + let shown: Vec<_> = card_lines(sheet, today()) + .iter() + .map(|line| (line.expression.clone(), value_text(&line.value))) + .collect(); + + assert_eq!( + shown, + [ + ("2".to_string(), "2".to_string()), + ("3".to_string(), "3".to_string()), + ("4".to_string(), "4".to_string()), + ("5".to_string(), "5".to_string()), + ] + ); + } + + #[test] + fn a_card_line_carries_its_aggregate_and_its_places() { + let shown = card_lines("1\n2\ntotal\n1 / 3 à 2 décimales", today()); + + let found: Vec<_> = shown + .iter() + .map(|line| (line.aggregate, line.places)) + .collect(); assert_eq!( - value("1,236 km à 2 décimales"), - number("1.24", Some(UnitId::Kilometre)) + found, + [(false, None), (false, None), (true, None), (false, Some(2))] ); - assert_eq!(value("33,333 % à 1 décimale"), percent("33.3", false)); - assert_eq!(value("1,44 To à 100 Mo/s"), number("4", Some(UnitId::Hour))); } #[test] - fn functions_read_with_or_without_parentheses() { - let cases = [ - ("sqrt(16)", "4"), - ("sqrt 16", "4"), - ("racine 16", "4"), - ("racine carrée(16) + 1", "5"), - ("cbrt 8", "2"), - ("racine cubique(27)", "3"), - ("log(100)", "2"), - ("log 2 (8)", "3"), - ("ln(e)", "1"), - ("abs(-42)", "42"), - ("valeur absolue(-42)", "42"), - ("round(3.7)", "4"), - ("round 3.45", "3"), - ("arrondi(3,7)", "4"), - ("ceil(3.2)", "4"), - ("plafond(3,2)", "4"), - ("floor(3.9)", "3"), - ("plancher(3,9)", "3"), - ]; - for (line, result) in cases { - assert_eq!(value(line), number(result, None), "{line}"); + fn a_sheet_with_no_result_gives_a_card_nothing() { + assert!(card_lines("", today()).is_empty()); + assert!(card_lines("des mots", today()).is_empty()); + } + + // --- Kept from the tests before. + + /// On a stack overflow the process stops, the whole test binary with it. + #[test] + fn a_line_nested_past_reason_is_an_error_not_a_crash() { + for line in ["(".repeat(5_000) + "1", "-".repeat(50_000) + "1"] { + assert_eq!(evaluate(&line, today()).rows.len(), 1); } - starts("racine 2 (8)", "2.82842712474619"); - starts("root 2 (8)", "2.82842712474619"); - starts("sqrt 2", "1.41421356237309504880168"); - starts("pi", "3.14159265358979"); - starts("π × 2", "6.28318530717958"); - starts("tau", "6.28318530717958"); - starts("τ", "6.28318530717958"); - starts("e", "2.71828182845904"); - starts("phi", "1.61803398874989"); - assert_eq!(value("e = 5\ne × 2"), number("10", None)); - assert_eq!(value("abs(-3 km)"), number("3", Some(UnitId::Kilometre))); - assert_eq!(error("sqrt(-4)"), CalcError::NegativeRoot); - assert_eq!(error("log(0)"), CalcError::LogDomain); - assert_eq!(error("ln(-1)"), CalcError::LogDomain); - assert_eq!(value("cbrt -8"), number("-2", None)); - let found = lines("a = 2\nsqrt(-4)\na × 2"); - assert!(matches!(&found[2], CalcLine::Value { value, .. } if *value == number("4", None))); + let nested = format!("{}2{}", "(".repeat(100), ")".repeat(100)); + assert_eq!(last(&nested), "2"); } #[test] fn a_root_of_any_degree_is_computed_within_a_moment() { let started = std::time::Instant::now(); - starts("racine 4000000000 (2)", "1.000000000173286795"); - starts("racine 10000000000 (2)", "1.000000000069314"); - assert_eq!(value("racine 4000000000 (1)"), number("1", None)); - assert_eq!(value("racine 64 (18446744073709551616)"), number("2", None)); - assert_eq!(error("racine 10000000000 (-2)"), CalcError::NegativeRoot); - assert_eq!(value("racine 10000000001 (-1)"), number("-1", None)); - assert_eq!(value("racine 10000000000 (0)"), number("0", None)); - assert_eq!(error("racine 2,5 (8)"), CalcError::Unsupported); - starts("log 1,0000001 (2)", "6931472.15"); - match value("rendement annuel sur 1 € investis 2 € récupérés en 4000000000 ans") { - CalcValue::Percent { value, .. } => { - assert!(value.starts_with("0.0000000173286795"), "{value}"); - } - other => panic!("{other:?}"), - } + + assert!(last("racine 4000000000 (2)").starts_with("1.000000000173286795")); + assert!(last("racine 10000000000 (2)").starts_with("1.000000000069314")); + check(&[ + ("racine 4000000000 (1)", "1"), + ("racine 64 (18446744073709551616)", "2"), + ("racine 10000000000 (-2)", "error: NegativeRoot"), + ("racine 10000000001 (-1)", "-1"), + ("racine 10000000000 (0)", "0"), + ("racine 2,5 (8)", "error: Unsupported"), + ]); + assert!(last("log 1,0000001 (2)").starts_with("6931472.15")); + assert!( + last("rendement annuel sur 1 € investis 2 € récupérés en 4000000000 ans") + .starts_with("0.0000000173286795") + ); assert!(started.elapsed() < std::time::Duration::from_secs(1)); } #[test] - fn numbers_are_read_and_written_in_other_bases() { - assert_eq!(value("255 en hex"), based("FF", 16)); - assert_eq!(value("255 in hex"), based("FF", 16)); - assert_eq!(value("10 en bin"), based("1010", 2)); - assert_eq!(value("255 en oct"), based("377", 8)); - assert_eq!(value("0xFF"), number("255", None)); - assert_eq!(value("0b1010"), number("10", None)); - assert_eq!(value("0o377"), number("255", None)); - assert_eq!(value("0b101101 en base 8"), based("55", 8)); - assert_eq!(value("0xFF as base 2"), based("11111111", 2)); - assert_eq!(value("0xFF en base 10"), number("255", None)); - assert_eq!(value("hex(99)"), based("63", 16)); - assert_eq!(value("bin(0x73)"), based("1110011", 2)); - assert_eq!(value("int(0o55)"), number("45", None)); - assert_eq!( - value("-10 en bin"), - CalcValue::Base { - digits: "1010".into(), - radix: 2, - negative: true - } - ); - assert_eq!( - value("5300 en sci"), - CalcValue::Scientific { - mantissa: "5.3".into(), - exponent: 3 - } - ); - assert_eq!(value("5,3e+3"), number("5300", None)); - assert_eq!(error("2,5 en hex"), CalcError::NotWhole); - assert!(matches!(error("5 km en hex"), CalcError::Mismatch { .. })); - assert_eq!(error("255 en base 3"), CalcError::Unsupported); + fn a_sheet_copied_with_its_results_as_comments_computes_the_same() { + check(&[("prix = 120 € // 120,00 €", "120 Euro")]); } #[test] - fn bits_combine_whole_numbers_only() { - let cases = [ - ("5 & 3", "1"), - ("5 | 3", "7"), - ("5 xor 3", "6"), - ("1 << 4", "16"), - ("16 >> 2", "4"), - ("2 + 3 << 1", "10"), - ("0xF0 | 0x0F", "255"), - ]; - for (line, result) in cases { - assert_eq!(value(line), number(result, None), "{line}"); + fn each_concept_reads_alike_in_french_and_in_english() { + for (french, english) in [ + ("5 km en m", "5 km in m"), + ("5 km vers m", "5 km as m"), + ("1,44 To à 100 Mo/s", "1,44 To at 100 Mo/s"), + ("20 % de 340", "20 % of 340"), + ("de 80 à 100", "from 80 to 100"), + ("30 sur 120 en %", "30 over 120 as %"), + ("300 hors 20 %", "300 excluding 20 %"), + ("300 ex 20 %", "300 excl 20 %"), + ("a = 1\nb = 3\nsomme", "a = 1\nb = 3\nsum"), + ("a = 1\nb = 3\nmoyenne", "a = 1\nb = 3\navg"), + ("demain", "tomorrow"), + ] { + assert_eq!(last(french), last(english), "{french} / {english}"); } - assert_eq!(error("1,5 & 1"), CalcError::NotWhole); - assert!(matches!(error("1 < 4"), CalcError::Unreadable { .. })); } #[test] - fn the_larger_or_the_smaller_of_numbers_named_on_a_line() { - assert_eq!(value("le plus grand de 100 et 200"), number("200", None)); - assert_eq!(value("larger of 100 and 200"), number("200", None)); - assert_eq!(value("le plus petit de 5 et 10"), number("5", None)); - assert_eq!(value("smaller of 5 and 10"), number("5", None)); - assert_eq!(value("le plus grand de 1, 5 et 3"), number("5", None)); + fn a_sheet_written_before_the_word_table_reads_the_same() { + let sheet = "# Budget\nhébergement = 100,521 €\ndomaines = 4,99 €\nmensuel = total\nmensuel × 12\n3 h 20 min en min\n20 % of 340\n100 € en $"; + assert_eq!( - value("le plus grand de 3 km et 500 m"), - number("3", Some(UnitId::Kilometre)) + lines(sheet), + [ + "# Budget", + "100.521 Euro", + "4.99 Euro", + "105.511 Euro", + "1266.132 Euro", + "200 Minute", + "68", + "error: Currency" + ] ); - assert!(matches!( - error("larger of 3 km and 2 kg"), - CalcError::Mismatch { .. } - )); - assert_eq!(value("le plus grand de 1 et 2 + 3"), number("5", None)); } #[test] - fn screen_units_follow_the_sheet_settings_from_their_line_down() { - assert_eq!(value("12 pt en px"), number("16", Some(UnitId::Pixel))); - assert_eq!(value("1 rem en px"), number("16", Some(UnitId::Pixel))); - assert_eq!( - value("em = 20 px\n1,2 em en px"), - number("24", Some(UnitId::Pixel)) - ); - assert_eq!( - value("em = 20\n1,2 em en px"), - number("24", Some(UnitId::Pixel)) + fn a_form_of_several_words_wins_over_a_name_of_one() { + assert!( + last("mensualité = 100 €\nmensualité de 10 000 € sur 6 ans à 6 %") + .starts_with("165.72887893") ); - assert_eq!( - value("rem = 18 px\n2 rem en px"), - number("36", Some(UnitId::Pixel)) + assert_eq!(last("mensualité = 100 €\nmensualité + 1 €"), "101 Euro"); + assert!( + last("total = $2\ntotal cost of $10,000 over 6 years at 6%") + .starts_with("11932.479283") ); - let found = lines("1 cm en px\nppi = 326\n1 cm en px"); - let figures = |line: &CalcLine| match line { - CalcLine::Value { - value: CalcValue::Number { value, .. }, - .. - } => value.clone(), - other => panic!("{other:?}"), - }; - assert!(figures(&found[0]).starts_with("37.795275590551181")); - assert!(figures(&found[2]).starts_with("128.346456692913385")); - assert!(matches!( - &found[1], - CalcLine::Value { name: Some(name), value, .. } if name == "ppi" && *value == number("326", None) - )); - assert!(evaluate("ppi = 326\nem = 20", today()).variables.is_empty()); - assert_eq!(error("ppi = 0"), CalcError::NotPositive); - assert!(matches!(error("ppi = 5 kg"), CalcError::Mismatch { .. })); + assert_eq!(last("racine = 5\nracine carrée(16) + racine"), "9"); } #[test] - fn a_setting_line_is_no_figure_for_total_or_previous() { - starts("ppi = 326\n1 cm en px\ntotal", "128.346456692913385"); - assert_eq!( - value("10 €\n20 €\nem = 20 px\ntotal"), - number("30", Some(UnitId::Euro)) - ); - assert_eq!( - value("10 €\nppi = 326\npréc + 5 €"), - number("15", Some(UnitId::Euro)) + fn a_length_named_above_is_read_after_apres_as_a_number_is() { + let named = "capital = 1 000 €\ndurée = 3 ans\ntaux = 7 %\n"; + + assert!(last(&format!("{named}capital après durée à taux")).starts_with("1225.04")); + assert!(last(&format!("{named}capital pendant durée à taux")).starts_with("1225.04")); + assert!( + last("principal = $1,000\nterm = 3 years\nprincipal after term @ 7%") + .starts_with("1225.04") ); + assert_eq!(last("prix = 275 €\nprix for the \"Model 227\""), "275 Euro"); + } + + #[test] + fn commas_group_thousands_only_where_no_french_decimal_could_be_meant() { + check(&[ + ("$1,000", "1000 Dollar"), + ("$1,000.50", "1000.5 Dollar"), + ("1,000,000", "1000000"), + ("1,578.13", "1578.13"), + ("1,000", "1"), + ("0,045", "0.045"), + ("1,5 $", "1.5 Dollar"), + ]); + } + + #[test] + fn a_date_is_read_before_its_digits_are_taken_for_a_division() { + check(&[ + ("16/10/2026", "2026-10-16"), + ("2026-10-16", "2026-10-16"), + ("16/10", "1.6"), + ("16/10/2026 + 1 j", "2026-10-17"), + ]); + } + + #[test] + fn a_short_date_before_a_wide_character_is_cut_on_characters() { + for line in [ + "2026-10-5é", + "RDV le 5/11/24 à 10h", + "12/01/25 équipe", + "3/4/26 – note", + "10/10/26 → livraison", + "1/2/24€", + ] { + assert_eq!(evaluate(line, today()).rows.len(), 1, "{line}"); + } + } + + #[test] + fn quoted_text_in_any_quotes_is_read_past() { + check(&[("275 € « Modèle 227 » \"x\" “y”", "275 Euro")]); } #[test] fn frequencies_and_the_prefixes_a_developer_reads() { - assert_eq!(value("2 MHz en Hz"), number("2000000", Some(UnitId::Hertz))); - assert_eq!( - value("1 GHz en MHz"), - number("1000", Some(UnitId::Megahertz)) - ); - assert_eq!(value("1 / 2 s"), number("0.5", Some(UnitId::Hertz))); - assert_eq!(value("60 Hz × 2 s"), number("120", None)); - assert_eq!( - value("1 µs en ns"), - number("1000", Some(UnitId::Nanosecond)) - ); - assert_eq!( - value("1 us en ns"), - number("1000", Some(UnitId::Nanosecond)) - ); - assert_eq!( - value("5 nm en µm"), - number("0.005", Some(UnitId::Micrometre)) - ); - assert_eq!(value("1 EB en PB"), number("1000", Some(UnitId::Petabyte))); - assert_eq!( - value("1 YiB en ZiB"), - number("1024", Some(UnitId::Zebibyte)) - ); - assert_eq!( - value("1 Pbit en Tbit"), - number("1000", Some(UnitId::Terabit)) - ); - assert!(matches!(error("2 MHz + 3 s"), CalcError::Mismatch { .. })); - } - - fn rounded(line: &str, places: u32) -> CalcValue { - match value(line) { - CalcValue::Number { value, unit } => CalcValue::Number { - value: value - .parse::() - .unwrap() - .round_dp(places) - .normalize() - .to_string(), - unit, - }, - CalcValue::Percent { value, signed } => CalcValue::Percent { - value: value - .parse::() - .unwrap() - .round_dp(places) - .normalize() - .to_string(), - signed, - }, - other => other, + check(&[ + ("2 MHz en Hz", "2000000 Hertz"), + ("1 GHz en MHz", "1000 Megahertz"), + ("1 µs en ns", "1000 Nanosecond"), + ("1 us en ns", "1000 Nanosecond"), + ("5 nm en µm", "0.005 Micrometre"), + ("1 EB en PB", "1000 Petabyte"), + ("1 YiB en ZiB", "1024 Zebibyte"), + ("1 Pbit en Tbit", "1000 Terabit"), + ]); + assert!(last("2 MHz + 3 s").starts_with("error: Mismatch")); + } + + #[test] + fn a_size_at_a_rate_is_a_duration() { + check(&[("1,44 To à 100 Mo/s en h", "4 Hour")]); + } + + #[test] + fn a_scale_is_read_in_its_case_and_a_scale_word_in_any() { + check(&[ + ("1 Mille milliards", "1000000000000"), + ("5 K", "5 Kelvin"), + ("5 k", "5000"), + ]); + } + + #[test] + fn a_syntax_word_is_reserved_in_any_case_and_a_value_word_is_not() { + check(&[ + ("De = 5", "error: Reserved { word: \"De\" }"), + ("total = 5", "5"), + ("aujourd'hui = 5", "5"), + ]); + } + + // --- Branches the list above did not reach. + + #[test] + fn a_function_or_a_bit_operation_refuses_a_quantity() { + for line in ["3 km & 1", "hex(3 km)", "7 km mod 2"] { + assert!(last(line).starts_with("error: Mismatch"), "{line}"); } } #[test] - fn a_share_is_added_or_taken_off_and_the_whole_solved_for() { - assert_eq!(value("5 % de plus sur 200"), number("210", None)); - assert_eq!(value("5% on 200"), number("210", None)); - assert_eq!(value("5 % de moins sur 200"), number("190", None)); - assert_eq!(value("5% off 200"), number("190", None)); - assert_eq!(value("5 % de combien font 6"), number("120", None)); - assert_eq!(value("5% of what is 6"), number("120", None)); - assert_eq!( - rounded("5 % de plus sur combien font 6", 2), - number("5.71", None) - ); - assert_eq!(rounded("5% on what is 6", 2), number("5.71", None)); - assert_eq!( - rounded("5 % de moins sur combien font 6", 2), - number("6.32", None) - ); - assert_eq!(rounded("5% off what is 6", 2), number("6.32", None)); - assert_eq!( - value("5 % de combien font 6 €"), - number("120", Some(UnitId::Euro)) - ); - assert_eq!(error("0 % de combien font 6"), CalcError::DivisionByZero); + fn a_remark_in_parentheses_may_hold_punctuation_or_a_quote() { + check(&[ + ("999 € (pour l'iPhone !)", "999 Euro"), + ("999 € (\"iPhone\")", "999 Euro"), + ]); } #[test] - fn a_value_as_a_share_of_another_and_a_change_between_two() { - assert_eq!(value("50 en % de 100"), percent("50", false)); - assert_eq!(value("50 as a % of 100"), percent("50", false)); - assert_eq!(value("70 en % de plus que 20"), percent("250", false)); - assert_eq!(value("70 as a % on 20"), percent("250", false)); - assert_eq!( - rounded("20 en % de moins que 70", 2), - percent("71.43", false) - ); - assert_eq!(rounded("20 as a % off 70", 2), percent("71.43", false)); - assert_eq!(value("50 à 75 c'est combien de %"), percent("50", true)); - assert_eq!(value("50 to 75 is what %"), percent("50", true)); - assert_eq!(value("40 à 90 en %"), percent("125", true)); - assert_eq!(value("40 to 90 as %"), percent("125", true)); - assert_eq!( - value("180 c'est combien de % de moins que 200"), - percent("10", false) - ); - assert_eq!(value("180 is what % off 200"), percent("10", false)); - assert_eq!( - value("180 c'est combien de % de plus que 150"), - percent("20", false) - ); - assert_eq!(value("180 is what % on 150"), percent("20", false)); - assert_eq!(value("20 c'est combien de % de 200"), percent("10", false)); - assert_eq!(value("20 is what % of 200"), percent("10", false)); - assert_eq!(value("1,44 To à 100 Mo/s"), number("4", Some(UnitId::Hour))); + fn a_percentage_rounds_as_a_percentage_and_a_date_does_not_round() { + check(&[ + ("33,333 % à 1 décimale", "33.3 %"), + ("aujourd'hui arrondi", "error: Unsupported"), + ]); } #[test] - fn fractions_multipliers_and_decimals() { - let fraction = |numerator: &str, denominator: &str| CalcValue::Fraction { - numerator: numerator.into(), - denominator: denominator.into(), - negative: false, - }; - let times = |value: &str| CalcValue::Multiplier { - value: value.into(), - }; - assert_eq!(value("2/10 en fraction"), fraction("1", "5")); - assert_eq!(value("2/10 as fraction"), fraction("1", "5")); - assert_eq!(value("50 % en fraction"), fraction("1", "2")); - assert_eq!(value("0,25 en fraction"), fraction("1", "4")); - assert_eq!(value("1/3 en fraction"), fraction("1", "3")); - assert_eq!(value("20/5 en multiple"), times("4")); - assert_eq!(value("20/5 as multiplier"), times("4")); - assert_eq!(value("50 en multiple de 5"), times("10")); - assert_eq!(value("50 as x of 5"), times("10")); - assert_eq!(value("50 à 75 c'est combien de fois"), times("1.5")); - assert_eq!(value("50 to 75 is what x"), times("1.5")); - assert_eq!(value("0,35 en %"), percent("35", false)); - assert_eq!(value("20/200 en %"), percent("10", false)); - assert_eq!(value("20 % en décimal"), number("0.2", None)); - assert_eq!(value("20 % as dec"), number("0.2", None)); - assert_eq!(value("50 % to decimal"), number("0.5", None)); - assert_eq!(value("1/3 to 2 decimal"), number("0.33", None)); - assert_eq!(value("x = 4\nx × 2"), number("8", None)); - assert_eq!(value("a = 50\na as a % of 100"), percent("50", false)); + fn a_change_asked_as_a_multiplier_and_a_proportion_s_third_term() { + check(&[ + ("40 to 90 is what x", "×2.25"), + ("5 is to 10 as what is to 80", "40"), + ( + "6 est à 60 ce que combien est à combien", + "error: Unreadable { at: 39 }", + ), + ("6 est à 60 8 est à combien", "error: Unreadable { at: 11 }"), + ("6 est à 60 ce que 8", "error: Unreadable { at: 19 }"), + ]); } #[test] - fn a_proportion_solves_for_its_unknown() { - assert_eq!( - value("6 est à 60 ce que 8 est à combien"), - number("80", None) - ); - assert_eq!(value("6 is to 60 as 8 is to what"), number("80", None)); - assert_eq!( - value("5 est à 10 ce que combien est à 80"), - number("40", None) - ); - assert_eq!(value("5 is to 10 as what is to 80"), number("40", None)); - assert_eq!( - value("2 h est à 120 km ce que 3 h est à combien"), - number("180", Some(UnitId::Kilometre)) - ); - assert!(matches!( - error("6 est à 60 ce que 8"), - CalcError::Unreadable { .. } - )); + fn a_number_written_as_a_multiple_of_another_a_base_ten_or_a_percentage() { + check(&[ + ("20 en multiple de 5", "×4"), + ("255 en base 10", "255"), + ("255 en base 3", "error: Unsupported"), + ("0,25 en %", "25 %"), + ("20 % en %", "20 %"), + ( + "3 km en %", + "error: NotConvertible { from: Length, to: None }", + ), + ]); } #[test] - fn the_five_questions_of_the_percentages_tool_read_as_before() { - assert_eq!(value("20 % de 340"), number("68", None)); - assert_eq!(value("30 sur 120 en %"), percent("25", false)); - assert_eq!(value("de 80 à 100"), percent("25", true)); - assert_eq!(value("250 + 20 %"), number("300", None)); - assert_eq!(value("300 hors 20 %"), number("250", None)); - assert_eq!(value("20 % of 340"), number("68", None)); + fn a_line_ending_on_an_operator_is_unreadable_at_its_end() { + check(&[("2 +", "error: Unreadable { at: 3 }")]); } - fn cents(line: &str) -> CalcValue { - rounded(line, 2) + #[test] + fn a_number_times_a_quantity_keeps_its_unit() { + check(&[("2 * 3 km", "6 Kilometre")]); } #[test] - fn compound_interest_keeps_the_amount_s_currency() { - let euros = |value: &str| number(value, Some(UnitId::Euro)); - let dollars = |value: &str| number(value, Some(UnitId::Dollar)); - assert_eq!(cents("1 000 € après 3 ans à 7 %"), euros("1225.04")); - assert_eq!(cents("$1,000 after 3 years at 7%"), dollars("1225.04")); - assert_eq!(cents("$1,000 after 3 years @ 7%"), dollars("1225.04")); - assert_eq!( - cents("1 000 € pendant 3 ans à 7 % composés mensuellement"), - euros("1232.93") - ); - assert_eq!( - cents("$1,000 for 3 years at 7% compounding monthly"), - dollars("1232.93") - ); - assert_eq!( - cents("1 000 € pendant 3 ans à 7 % composés trimestriellement"), - euros("1231.44") - ); - assert_eq!( - cents("$1,000 after 3 years at 7% compounded quarterly"), - dollars("1231.44") - ); - assert_eq!( - cents("intérêts sur 1 000 € après 3 ans à 7 %"), - euros("225.04") - ); - assert_eq!( - cents("interest on $1,000 after 3 years @ 7%"), - dollars("225.04") - ); - assert_eq!(cents("1 000 € après 36 mois à 7 %"), euros("1225.04")); - assert_eq!(error("1 000 € après 3 ans à 7"), CalcError::RateExpected); - assert!(matches!( - error("1 000 € après 3 km à 7 %"), - CalcError::Mismatch { .. } - )); + fn the_largest_or_smallest_of_a_list_by_commas_of_dates_percentages_or_temperatures() { + check(&[ + ("le plus grand de 3, 9, 4", "9"), + ("le plus grand de aujourd'hui et demain", "2026-07-26"), + ("le plus petit de 20 % et 10 %", "10 %"), + ("le plus grand de 0 °C et 30 °F", "0 Celsius"), + ]); + assert!(last("le plus grand de 2 m et 3 kg").starts_with("error: Mismatch")); } #[test] - fn a_length_named_above_is_read_after_apres_as_a_number_is() { - let euros = |value: &str| number(value, Some(UnitId::Euro)); - let named = "capital = 1 000 €\ndurée = 3 ans\ntaux = 7 %\n"; - assert_eq!( - cents(&format!("{named}capital après durée à taux")), - euros("1225.04") - ); - assert_eq!( - cents(&format!("{named}capital pendant durée à taux")), - euros("1225.04") - ); - assert_eq!( - cents("principal = $1,000\nterm = 3 years\nprincipal after term @ 7%"), - number("1225.04", Some(UnitId::Dollar)) - ); - assert_eq!( - value("prix = 275 €\nprix for the \"Model 227\""), - number("275", Some(UnitId::Euro)) - ); + fn a_finance_line_says_what_it_could_not_read() { + check(&[ + ( + "1 000 € après 3 ans à 7 % composés bizarrement", + "error: Unreadable { at: 35 }", + ), + ( + "valeur actuelle de 1 000 € 20 ans à 10 %", + "error: Unreadable { at: 27 }", + ), + ( + "rendement annuel sur 100 € investis 200 € récupérés en 0 an", + "error: DivisionByZero", + ), + ]); + assert!(last("1 000 € après 3 kg à 7 %").starts_with("error: Mismatch { expected: Time")); } #[test] - fn a_return_a_present_value_and_a_loan() { - let euros = |value: &str| number(value, Some(UnitId::Euro)); - let dollars = |value: &str| number(value, Some(UnitId::Dollar)); - let times = CalcValue::Multiplier { value: "3".into() }; - assert_eq!(value("500 € investis 1 500 € récupérés"), times); - assert_eq!(value("$500 invested $1,500 returned"), times); - assert_eq!( - cents("rendement annuel sur 1 000 € investis 2 500 € récupérés en 7 ans"), - percent("13.99", false) - ); - assert_eq!( - cents("annual return on $1,000 invested $2,500 returned after 7 years"), - percent("13.99", false) - ); - assert_eq!( - cents("valeur actuelle de 1 000 € dans 20 ans à 10 %"), - euros("148.64") - ); - assert_eq!( - cents("present value of $1,000 after 20 years at 10%"), - dollars("148.64") - ); - assert_eq!( - cents("mensualité de 10 000 € sur 6 ans à 6 %"), - euros("165.73") - ); - assert_eq!( - cents("monthly repayment on $10,000 over 6 years at 6%"), - dollars("165.73") - ); - assert_eq!( - cents("coût total de 10 000 € sur 6 ans à 6 %"), - euros("11932.48") - ); - assert_eq!( - cents("total repayment on $10,000 over 6 years at 6%"), - dollars("11932.48") - ); - assert_eq!( - cents("intérêts totaux de 10 000 € sur 6 ans à 6 %"), - euros("1932.48") - ); - assert_eq!( - cents("total interest on $10,000 over 6 years at 6%"), - dollars("1932.48") - ); - assert_eq!(cents("mensualité de 1 200 € sur 1 an à 0 %"), euros("100")); - assert_eq!(value("30 sur 120 en %"), percent("25", false)); - assert_eq!(value("a = 1\nb = 3\ntotal"), number("4", None)); + fn a_loan_s_interest_and_a_loan_at_no_rate() { + assert!(last("intérêts totaux de 10 000 € sur 1 an à 12 %").starts_with("661.85464140")); + check(&[("mensualité de 1 200 € sur 1 an à 0 %", "100 Euro")]); + } + + #[test] + fn a_natural_logarithm_is_whole_where_it_is() { + check(&[("ln e", "1"), ("ln 1", "0")]); + } + + #[test] + fn zero_and_a_whole_mantissa_in_scientific_notation() { + check(&[("0 en sci", "0e0"), ("5000 en sci", "5e3")]); } #[test] - fn powers_parentheses_and_signs() { - assert_eq!(value("2 ^ 10"), number("1024", None)); - assert_eq!(value("(1 + 2) × -3"), number("-9", None)); - assert_eq!(value("1 / 4"), number("0.25", None)); + fn an_exponent_or_a_base_prefix_followed_by_a_letter_is_not_a_number() { + check(&[ + ("1e3", "1000"), + ("1e3x", "error: Unreadable { at: 1 }"), + ("2e", "error: Unreadable { at: 1 }"), + ("0xFG", "error: Unreadable { at: 1 }"), + ]); } } diff --git a/crates/engine/src/notes/calc/lexer.rs b/crates/engine/src/notes/calc/lexer.rs index e53815e1d..410d92478 100644 --- a/crates/engine/src/notes/calc/lexer.rs +++ b/crates/engine/src/notes/calc/lexer.rs @@ -321,151 +321,3 @@ pub(super) fn tokens(line: &str) -> Vec { } tokens } - -#[cfg(test)] -mod tests { - use super::*; - - fn toks(line: &str) -> Vec { - tokens(line).into_iter().map(|token| token.tok).collect() - } - - #[test] - fn a_comma_or_a_point_marks_the_decimals() { - assert_eq!(toks("0,045"), [Tok::Number("0.045".parse().unwrap())]); - assert_eq!(toks("1.5"), [Tok::Number("1.5".parse().unwrap())]); - } - - #[test] - fn thousands_grouped_by_a_space_are_one_number() { - let number = |text: &str| Tok::Number(text.parse().unwrap()); - assert_eq!(toks("5 300"), [number("5300")]); - assert_eq!(toks("1 000 000"), [number("1000000")]); - assert_eq!( - toks("1\u{202f}578,13 €"), - [number("1578.13"), Tok::Symbol('€')] - ); - assert_eq!(toks("1\u{a0}578,13"), [number("1578.13")]); - assert_eq!(toks("1234 567"), [number("1234"), number("567")]); - assert_eq!(toks("5 3000"), [number("5"), number("3000")]); - assert_eq!( - toks("3 h 20 min"), - [ - number("3"), - Tok::Word("h".into()), - number("20"), - Tok::Word("min".into()) - ] - ); - } - - #[test] - fn a_number_is_read_in_another_base_and_in_scientific_notation() { - let number = |text: &str| Tok::Number(text.parse().unwrap()); - assert_eq!(toks("0xFF"), [number("255")]); - assert_eq!(toks("0b1010"), [number("10")]); - assert_eq!(toks("0o377"), [number("255")]); - assert_eq!(toks("0b"), [number("0"), Tok::Word("b".into())]); - assert_eq!(toks("5,3e+3"), [number("5300")]); - assert_eq!(toks("1e-9"), [number("0.000000001")]); - assert_eq!(toks("2e"), [number("2"), Tok::Word("e".into())]); - assert_eq!( - toks("1 << 4"), - [number("1"), Tok::Symbol('<'), Tok::Symbol('<'), number("4")] - ); - } - - #[test] - fn commas_group_thousands_only_where_no_french_decimal_could_be_meant() { - let number = |text: &str| Tok::Number(text.parse().unwrap()); - assert_eq!(toks("$1,000"), [Tok::Symbol('$'), number("1000")]); - assert_eq!(toks("$1,000.50"), [Tok::Symbol('$'), number("1000.50")]); - assert_eq!(toks("1,000,000"), [number("1000000")]); - assert_eq!(toks("1,578.13"), [number("1578.13")]); - assert_eq!(toks("1,000"), [number("1.000")]); - assert_eq!(toks("0,045"), [number("0.045")]); - assert_eq!(toks("$ 1,5"), [Tok::Symbol('$'), number("1.5")]); - assert_eq!(toks("@"), [Tok::Symbol('@')]); - } - - #[test] - fn a_quoted_text_is_one_token_and_a_stray_character_another() { - assert_eq!( - toks("275 € « Modèle 227 » \"x\" “y” ?"), - [ - Tok::Number(Decimal::from(275)), - Tok::Symbol('€'), - Tok::Quoted, - Tok::Quoted, - Tok::Quoted, - Tok::Other('?') - ] - ); - assert_eq!(toks("\"open"), [Tok::Other('"'), Tok::Word("open".into())]); - } - - #[test] - fn a_date_is_read_before_its_digits_are_taken_for_a_division() { - let date = NaiveDate::from_ymd_opt(2026, 10, 16).unwrap(); - assert_eq!(toks("16/10/2026"), [Tok::Date(date)]); - assert_eq!(toks("2026-10-16"), [Tok::Date(date)]); - assert_eq!( - toks("16/10"), - [ - Tok::Number(Decimal::from(16)), - Tok::Symbol('/'), - Tok::Number(Decimal::from(10)) - ] - ); - } - - #[test] - fn a_short_date_before_a_wide_character_is_cut_on_characters() { - for line in [ - "2026-10-5é", - "RDV le 5/11/24 à 10h", - "12/01/25 équipe", - "3/4/26 – note", - "10/10/26 → livraison", - "1/2/24€", - "2026-10-5é", - ] { - assert!(!tokens(line).is_empty(), "{line}"); - } - let date = NaiveDate::from_ymd_opt(2024, 11, 5).unwrap(); - assert_eq!(toks("5/11/2024 à")[0], Tok::Date(date)); - } - - #[test] - fn a_unit_with_a_slash_and_no_space_stays_one_rate() { - let line = tokens("0,045 €/h"); - assert_eq!(line[1].tok, Tok::Symbol('€')); - assert!(!line[2].spaced); - assert_eq!(line[3].tok, Tok::Word("h".into())); - } - - #[test] - fn an_apostrophe_inside_a_word_keeps_it_whole_and_a_comment_is_left_out() { - assert_eq!( - toks("aujourd'hui + 2 // ven."), - [ - Tok::Word("aujourd'hui".into()), - Tok::Symbol('+'), - Tok::Number(Decimal::from(2)), - ] - ); - } - - #[test] - fn offsets_are_counted_in_utf16_units() { - let line = tokens("😀 = 2"); - assert_eq!( - (line[0].tok.clone(), line[0].end, line[1].start), - (Tok::Other('😀'), 2, 3) - ); - let line = tokens("é = 2"); - assert_eq!((line[2].start, line[2].end), (4, 5)); - let line = tokens("°C"); - assert_eq!(line[0].tok, Tok::Word("°C".into())); - } -} diff --git a/crates/engine/src/notes/calc/maths.rs b/crates/engine/src/notes/calc/maths.rs index fa3975236..3275ec5f5 100644 --- a/crates/engine/src/notes/calc/maths.rs +++ b/crates/engine/src/notes/calc/maths.rs @@ -359,96 +359,3 @@ pub(super) fn scientific(value: Decimal) -> (String, i32) { }; (mantissa, exponent) } - -#[cfg(test)] -mod tests { - use super::*; - - fn d(text: &str) -> Decimal { - text.parse().unwrap() - } - - #[test] - fn a_root_is_exact_where_one_exists_and_refused_where_none_does() { - assert_eq!(root(d("16"), 2), Ok(d("4"))); - assert_eq!(root(d("8"), 3), Ok(d("2"))); - assert_eq!(root(d("-8"), 3), Ok(d("-2"))); - assert_eq!(root(d("0.25"), 2), Ok(d("0.5"))); - assert_eq!(root(d("-4"), 2), Err(CalcError::NegativeRoot)); - let two = root(d("2"), 2).unwrap(); - assert!(two.to_string().starts_with("1.41421356237309504880168872")); - let eight = root(d("8"), 2).unwrap(); - assert!( - eight - .to_string() - .starts_with("2.828427124746190097603377448") - ); - } - - #[test] - fn a_logarithm_is_whole_where_it_is_and_refused_at_zero_or_below() { - assert_eq!(log(d("100"), None), Ok(d("2"))); - assert_eq!(log(d("8"), Some(d("2"))), Ok(d("3"))); - assert_eq!(ln(Decimal::E), Ok(d("1"))); - assert_eq!(log(d("0"), None), Err(CalcError::LogDomain)); - assert_eq!(ln(d("-1")), Err(CalcError::LogDomain)); - assert_eq!(log(d("8"), Some(d("1"))), Err(CalcError::LogDomain)); - } - - #[test] - fn rounding_takes_a_half_away_from_zero() { - assert_eq!(round_to(d("5.5"), d("1"), Rounding::Nearest), Ok(d("6"))); - assert_eq!(round_to(d("-5.5"), d("1"), Rounding::Nearest), Ok(d("-6"))); - assert_eq!(round_to(d("5.5"), d("1"), Rounding::Down), Ok(d("5"))); - assert_eq!(round_to(d("21"), d("5"), Rounding::Up), Ok(d("25"))); - assert_eq!(round_to(d("37"), d("10"), Rounding::Nearest), Ok(d("40"))); - assert_eq!(round_places(d("3.14159265"), 5), d("3.14159")); - assert_eq!(round_places(d("0.125"), 2), d("0.13")); - } - - #[test] - fn bits_and_bases_read_whole_numbers_only() { - assert_eq!(bits(d("5"), d("3"), Bits::And), Ok(d("1"))); - assert_eq!(bits(d("5"), d("3"), Bits::Or), Ok(d("7"))); - assert_eq!(bits(d("5"), d("3"), Bits::Xor), Ok(d("6"))); - assert_eq!(bits(d("1"), d("4"), Bits::Left), Ok(d("16"))); - assert_eq!(bits(d("16"), d("2"), Bits::Right), Ok(d("4"))); - assert_eq!(bits(d("1.5"), d("1"), Bits::And), Err(CalcError::NotWhole)); - assert_eq!(digits(d("255"), 16), Ok((false, "FF".into()))); - assert_eq!(digits(d("-10"), 2), Ok((true, "1010".into()))); - assert_eq!(digits(d("255"), 8), Ok((false, "377".into()))); - assert_eq!(digits(d("2.5"), 16), Err(CalcError::NotWhole)); - } - - #[test] - fn money_grows_is_returned_and_is_repaid() { - assert_eq!(grown(d("0.07"), d("1"), d("3")), Ok(d("1.225043"))); - let monthly = grown(d("0.07"), d("12"), d("3")).unwrap(); - assert!(monthly.to_string().starts_with("1.23292")); - let return_ = yearly(d("2.5"), d("7")).unwrap(); - assert!(return_.to_string().starts_with("0.1398"), "{return_}"); - let payment = payment(d("0.005"), d("72")).unwrap(); - assert!(payment.to_string().starts_with("0.0165728"), "{payment}"); - assert_eq!(power_of(d("2"), d("-2")), Ok(d("0.25"))); - assert_eq!(yearly(d("2"), d("0")), Err(CalcError::DivisionByZero)); - } - - #[test] - fn a_decimal_is_written_as_its_simplest_fraction() { - assert_eq!(fraction(d("0.2")), (false, 1, 5)); - assert_eq!(fraction(d("0.25")), (false, 1, 4)); - assert_eq!(fraction(d("-1.5")), (true, 3, 2)); - assert_eq!(fraction(d("3")), (false, 3, 1)); - assert_eq!(fraction(d("1") / d("3")), (false, 1, 3)); - assert_eq!(fraction(d("22") / d("7")), (false, 22, 7)); - assert_eq!(fraction(d("0")), (false, 0, 1)); - } - - #[test] - fn a_number_is_written_as_a_mantissa_and_its_exponent() { - assert_eq!(scientific(d("5300")), ("5.3".into(), 3)); - assert_eq!(scientific(d("0.000123")), ("1.23".into(), -4)); - assert_eq!(scientific(d("-7")), ("-7".into(), 0)); - assert_eq!(scientific(Decimal::ZERO), ("0".into(), 0)); - } -} diff --git a/crates/engine/src/notes/calc/summary.rs b/crates/engine/src/notes/calc/summary.rs index e684b70c0..a63940e87 100644 --- a/crates/engine/src/notes/calc/summary.rs +++ b/crates/engine/src/notes/calc/summary.rs @@ -64,23 +64,80 @@ fn figures(values: &[&str]) -> Option<(String, String)> { mod tests { use chrono::NaiveDate; - use super::super::evaluate; use super::*; + use crate::notes::calc::evaluate; + use crate::notes::calc::units::UnitId; - fn sheet(text: &str) -> CalcSheet { - evaluate(text, NaiveDate::from_ymd_opt(2026, 10, 16).unwrap()) + fn summed(sheet: &str, lines: &[u32]) -> CalcSummary { + let today = NaiveDate::from_ymd_opt(2026, 7, 25).expect("a day"); + summary(&evaluate(sheet, today), lines) } - fn sum_and_mean(values: &[&str]) -> (String, String) { - figures(values).unwrap() + fn figures(sum: &str, mean: &str, unit: Option) -> CalcSummary { + let unit = unit.map(|unit| CalcUnit { unit, per: None }); + CalcSummary::Figures { + sum: CalcValue::Number { + value: sum.into(), + unit, + }, + mean: CalcValue::Number { + value: mean.into(), + unit, + }, + } + } + + #[test] + fn the_lines_chosen_add_up_and_average_exactly_in_their_unit() { + assert_eq!( + summed("0,1 €\n0,2 €\n5 €", &[0, 1]), + figures("0.3", "0.15", Some(UnitId::Euro)) + ); + assert_eq!( + summed("1\n2\n4", &[0, 1, 2]), + figures("7", "2.333333333333333333333333", None) + ); + } + + #[test] + fn a_line_that_gave_no_number_is_left_out() { + let sheet = "3\ndes mots\n1 / 0\n20 %\naujourd'hui\n\n5"; + + assert_eq!( + summed(sheet, &[0, 1, 2, 3, 4, 5, 6, 99]), + figures("8", "4", None) + ); } - /// A sheet's sum and mean (`golden/calc-format`). + #[test] + fn lines_without_a_number_have_nothing_to_add() { + assert_eq!(summed("des mots\n20 %", &[0, 1]), CalcSummary::NothingToAdd); + assert_eq!(summed("3", &[]), CalcSummary::NothingToAdd); + } + + #[test] + fn numbers_in_different_units_or_with_and_without_one_do_not_add_up() { + assert_eq!(summed("3 €\n2 $", &[0, 1]), CalcSummary::MixedUnits); + assert_eq!(summed("3 €\n2", &[0, 1]), CalcSummary::MixedUnits); + assert_eq!(summed("1 km\n2 m", &[0, 1]), CalcSummary::MixedUnits); + } + + #[test] + fn a_sum_past_what_a_decimal_holds_overflows() { + let huge = "79228162514264337593543950335"; + + assert_eq!( + summed(&format!("{huge}\n{huge}"), &[0, 1]), + CalcSummary::Overflow + ); + } + + /// The sums and means the front's footer was checked against (`golden/calc-format`). #[test] fn the_footer_gives_what_the_golden_cases_say() { let cases: Vec = serde_json::from_str(include_str!("../../../../../golden/calc-format/cases.json")) - .unwrap(); + .expect("the golden cases"); let mut checked = 0; for case in &cases { let Some(footer) = case["options"]["footer"].as_str() else { @@ -88,73 +145,26 @@ mod tests { }; let input: Vec<&str> = case["input"] .as_array() - .unwrap() + .expect("an input") .iter() - .map(|value| value.as_str().unwrap()) + .map(|value| value.as_str().expect("a number")) .collect(); - let (sum, mean) = sum_and_mean(&input); + let all: Vec = (0..u32::try_from(input.len()).expect("a few")).collect(); + let CalcSummary::Figures { sum, mean } = summed(&input.join("\n"), &all) else { + panic!("{input:?} adds up"); + }; let got = if footer == "sum" { sum } else { mean }; + assert_eq!( got, - case["output"].as_str().unwrap(), + CalcValue::Number { + value: case["output"].as_str().expect("an output").into(), + unit: None + }, "{footer} of {input:?}" ); checked += 1; } assert_eq!(checked, 6); } - - #[test] - fn the_decimals_add_up_without_a_float_in_between() { - assert_eq!(sum_and_mean(&["0.1", "0.2"]).0, "0.3"); - assert_eq!(sum_and_mean(&["100.521", "4.99", "26"]).0, "131.511"); - assert_eq!(sum_and_mean(&["-1.5", "0.5"]).0, "-1"); - assert_eq!(sum_and_mean(&["1", "2"]).1, "1.5"); - assert!(sum_and_mean(&["1", "1", "2"]).1.starts_with("1.333333")); - } - - #[test] - fn numbers_in_one_unit_are_summed_in_it() { - let sheet = sheet("100,521 €\n4,99 €\n# Titre"); - - let CalcSummary::Figures { sum, mean } = summary(&sheet, &[0, 1, 2]) else { - panic!("figures"); - }; - let CalcValue::Number { value, unit } = sum else { - panic!("a number"); - }; - assert_eq!(value, "105.511"); - assert!(unit.is_some()); - assert!(matches!(mean, CalcValue::Number { value, .. } if value == "52.7555")); - } - - #[test] - fn a_line_with_no_number_is_left_out_and_with_none_nothing_adds_up() { - let sheet = sheet("# Titre\n12\n25 %\n01/02/2026 + 1 jour"); - - assert_eq!(summary(&sheet, &[0]), CalcSummary::NothingToAdd); - assert_eq!(summary(&sheet, &[0, 2]), CalcSummary::NothingToAdd); - assert_eq!(summary(&sheet, &[]), CalcSummary::NothingToAdd); - assert_eq!(summary(&sheet, &[99]), CalcSummary::NothingToAdd); - let CalcSummary::Figures { sum, .. } = summary(&sheet, &[0, 1, 2]) else { - panic!("figures"); - }; - assert!(matches!(sum, CalcValue::Number { value, .. } if value == "12")); - } - - #[test] - fn different_units_do_not_add_up_nor_a_unit_and_none() { - let sheet = sheet("3 €\n4 Go\n5"); - - assert_eq!(summary(&sheet, &[0, 1]), CalcSummary::MixedUnits); - assert_eq!(summary(&sheet, &[0, 2]), CalcSummary::MixedUnits); - } - - #[test] - fn a_sum_past_what_a_decimal_holds_says_so() { - let huge = "70000000000000000000000000000"; - let sheet = sheet(&format!("{huge}\n{huge}")); - - assert_eq!(summary(&sheet, &[0, 1]), CalcSummary::Overflow); - } } diff --git a/crates/engine/src/notes/calc/units.rs b/crates/engine/src/notes/calc/units.rs index 03cd60289..b8267c32f 100644 --- a/crates/engine/src/notes/calc/units.rs +++ b/crates/engine/src/notes/calc/units.rs @@ -632,9 +632,8 @@ mod tests { #[test] fn no_symbol_names_two_units() { - let table = table(); let mut seen = std::collections::HashSet::new(); - for unit in &table { + for unit in &table() { for symbol in unit.symbols { assert!(seen.insert(*symbol), "{symbol} names two units"); } @@ -642,24 +641,21 @@ mod tests { } #[test] - fn a_rate_is_one_base_over_another() { - assert_eq!( - Dim::EURO.over(Dim::TIME).as_rate(), - Some((Dim::EURO, Dim::TIME)) - ); - assert_eq!(Dim::LENGTH.times(Dim::LENGTH).as_rate(), None); - assert_eq!(Dim::EURO.over(Dim::TIME).dimension(), Dimension::Rate); - } - - #[test] - fn a_temperature_goes_through_celsius_exactly() { - assert_eq!( - from_celsius(Decimal::from(38), UnitId::Fahrenheit), - "100.4".parse().unwrap() - ); - assert_eq!( - to_celsius(Decimal::ZERO, UnitId::Kelvin), - "-273.15".parse().unwrap() - ); + fn the_catalogue_offers_each_unit_once_with_what_it_measures() { + let catalogue = catalogue(); + let mut ids: Vec<_> = catalogue + .iter() + .map(|entry| format!("{:?}", entry.id)) + .collect(); + ids.sort(); + ids.dedup(); + + assert_eq!(ids.len(), catalogue.len()); + assert_eq!(catalogue.len(), table().len()); + let euro = catalogue + .iter() + .find(|entry| entry.id == UnitId::Euro) + .expect("euros"); + assert_eq!(euro.dimension, Dimension::Euro); } } diff --git a/crates/engine/src/notes/calc/words.rs b/crates/engine/src/notes/calc/words.rs index abde2bda2..f274717c6 100644 --- a/crates/engine/src/notes/calc/words.rs +++ b/crates/engine/src/notes/calc/words.rs @@ -468,17 +468,6 @@ mod tests { assert_eq!(shared, declared); } - #[test] - fn a_scale_is_read_in_its_case_and_a_word_in_any() { - assert_eq!(spelled(CalcWord::Mega, &tokens("m"), 0), None); - assert_eq!(spelled(CalcWord::Kilo, &tokens("K"), 0), None); - assert_eq!(scale_at(&tokens("Md"), 0), Some((1_000_000_000, 1))); - assert_eq!( - scale_at(&tokens("Mille milliards"), 0), - Some((1_000_000_000_000, 2)) - ); - } - #[test] fn a_spelling_is_written_folded_and_one_space_apart() { for word in CalcWord::ALL { @@ -504,13 +493,4 @@ mod tests { .collect(); assert_eq!(both, BTreeSet::from(["in", "em", "rem"])); } - - #[test] - fn only_syntax_words_are_reserved() { - assert!(reserved("en")); - assert!(reserved("De")); - assert!(!reserved("total")); - assert!(!reserved("aujourd'hui")); - assert!(!reserved("prix")); - } } From d4a8d298ee17ebb222dc61dde42d8b251df8da4e Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:23:30 +0100 Subject: [PATCH 08/95] Calcul: a date moved by years moves by years, not months (#1727) --- crates/engine/src/notes/calc.rs | 11 +++++++++++ crates/engine/src/notes/calc/eval.rs | 6 +++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/notes/calc.rs b/crates/engine/src/notes/calc.rs index 4cfc9226b..55207409f 100644 --- a/crates/engine/src/notes/calc.rs +++ b/crates/engine/src/notes/calc.rs @@ -1482,6 +1482,17 @@ mod tests { ]); } + #[test] + fn a_date_moved_by_years_moves_by_calendar_years() { + check(&[ + ("aujourd'hui - 1 an", "2025-07-25"), + ("aujourd'hui + 2 ans", "2028-07-25"), + ("today - 1 year", "2025-07-25"), + ("29/02/2028 + 1 an", "2029-02-28"), + ("aujourd'hui + 0,5 an", "2027-01-25"), + ]); + } + #[test] fn two_dates_subtract_into_days() { check(&[("demain - hier", "2 Day")]); diff --git a/crates/engine/src/notes/calc/eval.rs b/crates/engine/src/notes/calc/eval.rs index de7076f3b..4ae67232c 100644 --- a/crates/engine/src/notes/calc/eval.rs +++ b/crates/engine/src/notes/calc/eval.rs @@ -1218,11 +1218,11 @@ fn add(left: Value, right: Value, plus: bool) -> Answer { } } -/// By calendar months for months and years, by whole days otherwise. +/// By calendar months for months and years, by whole days otherwise. A year is counted in its +/// twelve months, so half of one moves a date by six. fn shift_date(date: NaiveDate, shift: &Quantity, plus: bool) -> Answer { let (unit, count) = match shift.unit { - Some(Shown::One(UnitId::Month)) => (Decimal::from(2_629_746), true), - Some(Shown::One(UnitId::Year)) => (Decimal::from(2_629_746 * 12), true), + Some(Shown::One(UnitId::Month | UnitId::Year)) => (Decimal::from(2_629_746), true), _ => (Decimal::from(86_400), false), }; let steps = shift.amount.checked_div(unit).ok_or_else(overflow)?; From 224e31701beb952eebd873514eb16d8405f9c3ae Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:23:38 +0100 Subject: [PATCH 09/95] Calcul: a chain of powers such as 2 ^ 3 ^ 2 is read (#1728) --- crates/engine/src/notes/calc.rs | 10 ++++++++++ crates/engine/src/notes/calc/eval.rs | 10 ++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/notes/calc.rs b/crates/engine/src/notes/calc.rs index 55207409f..658df24fb 100644 --- a/crates/engine/src/notes/calc.rs +++ b/crates/engine/src/notes/calc.rs @@ -920,6 +920,16 @@ mod tests { ]); } + #[test] + fn a_chain_of_powers_is_read_from_the_right() { + check(&[ + ("2 ^ 3 ^ 2", "512"), + ("2 ^ 2 ^ 2 ^ 2", "65536"), + ("2 ^ -1 ^ 2", "2"), + ]); + assert_eq!(evaluate(&"2 ^ ".repeat(50_000), today()).rows.len(), 1); + } + #[test] fn a_scale_after_a_number_multiplies_it_m_staying_a_metre() { check(&[ diff --git a/crates/engine/src/notes/calc/eval.rs b/crates/engine/src/notes/calc/eval.rs index 4ae67232c..56b2e6b91 100644 --- a/crates/engine/src/notes/calc/eval.rs +++ b/crates/engine/src/notes/calc/eval.rs @@ -908,8 +908,14 @@ impl<'a> Parser<'a> { return Ok(base); } self.take(TokenKind::Operator); - let exponent = self.unary()?; - power(base, exponent).map_err(|error| self.blame(error)) + // From the right, as mathematics reads `2 ^ 3 ^ 2`; a nesting like a bracket's, counted. + if self.depth == MAX_NESTING { + return Err(self.unreadable()); + } + self.depth += 1; + let exponent = self.power(); + self.depth -= 1; + power(base, exponent?).map_err(|error| self.blame(error)) } /// Every nesting goes through here: a bracket reads its inside down to a sign or a value. From 51670212704611535b3b7bdfaab2ff3ed8200775 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:23:45 +0100 Subject: [PATCH 10/95] Calcul: an inch is exactly 96 pixels, and back (#1729) An inch is exactly 96 pixels at the default setting, and back. --- crates/engine/src/notes/calc.rs | 52 ++++++++++++++++++------ crates/engine/src/notes/calc/eval.rs | 57 ++++++++++++++++----------- crates/engine/src/notes/calc/units.rs | 20 +++++----- 3 files changed, 85 insertions(+), 44 deletions(-) diff --git a/crates/engine/src/notes/calc.rs b/crates/engine/src/notes/calc.rs index 658df24fb..3abed2c89 100644 --- a/crates/engine/src/notes/calc.rs +++ b/crates/engine/src/notes/calc.rs @@ -268,22 +268,26 @@ impl Units { } } - /// A pixel's and an `em`'s size follow the sheet's settings. - fn unit(&self, unit: UnitId, css: &Css) -> Option<(Decimal, Dim)> { + /// Base units in one, as above over below: a pixel's and an `em`'s size follow the sheet's + /// settings. + fn unit(&self, unit: UnitId, css: &Css) -> Option<(Decimal, Decimal, Dim)> { let &(factor, dim) = self.factors.get(&unit)?; - Some((css.factor(unit).unwrap_or(factor), dim)) + let (above, below) = css.factor(unit).unwrap_or((factor, Decimal::ONE)); + Some((above, below, dim)) } /// Base units in one, as above over below, and what it measures. fn factor(&self, shown: Shown, css: &Css) -> Option<(Decimal, Decimal, Dim)> { match shown { - Shown::One(unit) => self - .unit(unit, css) - .map(|(factor, dim)| (factor, Decimal::ONE, dim)), + Shown::One(unit) => self.unit(unit, css), Shown::Per(above, below) => { - let (top, top_dim) = self.unit(above, css)?; - let (bottom, bottom_dim) = self.unit(below, css)?; - Some((top, bottom, top_dim.over(bottom_dim))) + let (top, top_below, top_dim) = self.unit(above, css)?; + let (bottom, bottom_below, bottom_dim) = self.unit(below, css)?; + Some(( + top.checked_mul(bottom_below)?, + top_below.checked_mul(bottom)?, + top_dim.over(bottom_dim), + )) } } } @@ -665,7 +669,7 @@ impl Walk { /// `ppi = 326`, `em = 20 px`: the sheet's setting from this line down. A size in pixels /// may be written bare. fn set(&mut self, setting: CalcWord, value: &Value) -> Result { - let pixel = self.css.factor(UnitId::Pixel).ok_or(CalcError::Overflow)?; + let (inch, ppi) = self.css.factor(UnitId::Pixel).ok_or(CalcError::Overflow)?; let pixels = match value { Value::Quantity(quantity) if quantity.dim.is_none() => quantity.amount, Value::Quantity(quantity) @@ -673,7 +677,8 @@ impl Walk { { quantity .amount - .checked_div(pixel) + .checked_mul(ppi) + .and_then(|product| product.checked_div(inch)) .ok_or(CalcError::Overflow)? } other => { @@ -702,7 +707,10 @@ impl Walk { _ => self.css.rem = pixels, } Ok(Value::Quantity(Quantity { - amount: pixels.checked_mul(pixel).ok_or(CalcError::Overflow)?, + amount: pixels + .checked_mul(inch) + .and_then(|product| product.checked_div(ppi)) + .ok_or(CalcError::Overflow)?, dim: Dim::LENGTH, unit: Some(Shown::One(UnitId::Pixel)), spans: false, @@ -1267,6 +1275,26 @@ mod tests { ); } + #[test] + fn an_inch_is_exactly_its_pixels_both_ways() { + let sheet = "1 in en px\n96 px en in\n2,54 cm en px\n20 px en px\nppi = 326\n1 in en px\n326 px en in\nem = 20 px\n1 em en px"; + + assert_eq!( + lines(sheet), + [ + "96 Pixel", + "1 Inch", + "96 Pixel", + "20 Pixel", + "326", + "326 Pixel", + "1 Inch", + "20 Pixel", + "20 Pixel" + ] + ); + } + #[test] fn a_setting_is_above_zero_and_no_name_for_total() { assert_eq!(lines("ppi = 0"), ["error: NotPositive"]); diff --git a/crates/engine/src/notes/calc/eval.rs b/crates/engine/src/notes/calc/eval.rs index 56b2e6b91..44c7ef55c 100644 --- a/crates/engine/src/notes/calc/eval.rs +++ b/crates/engine/src/notes/calc/eval.rs @@ -41,12 +41,25 @@ pub(super) struct Factor { } impl Factor { + const ONE: Self = Self { + above: Decimal::ONE, + below: Decimal::ONE, + }; + fn apply(self, number: Decimal) -> Result { number .checked_mul(self.above) .and_then(|product| product.checked_div(self.below)) .ok_or(CalcError::Overflow) } + + /// One unit's over another's: `€/h`. + fn over(self, other: Self) -> Option { + Some(Self { + above: self.above.checked_mul(other.below)?, + below: self.below.checked_mul(other.above)?, + }) + } } /// An amount in base units — but a temperature's in its own degrees, converted by formula. @@ -372,16 +385,22 @@ impl<'a> Parser<'a> { } /// A screen unit's size follows the sheet's `ppi`, `em` and `rem`. - fn factor_of(&self, unit: &UnitDef) -> Decimal { - self.context.css.factor(unit.id).unwrap_or(unit.factor) + fn factor_of(&self, unit: &UnitDef) -> Factor { + match self.context.css.factor(unit.id) { + Some((above, below)) => Factor { above, below }, + None => Factor { + above: unit.factor, + below: Decimal::ONE, + }, + } } - fn unit_factor(&self, unit: UnitId) -> Decimal { + fn unit_factor(&self, unit: UnitId) -> Factor { self.context .units .iter() .find(|def| def.id == unit) - .map_or(Decimal::ONE, |def| self.factor_of(def)) + .map_or(Factor::ONE, |def| self.factor_of(def)) } fn unit_at(&self, index: usize) -> Option<&'a UnitDef> { @@ -407,21 +426,14 @@ impl<'a> Parser<'a> { { self.take(TokenKind::Unit); self.take(TokenKind::Unit); - let factor = Factor { - above: self.factor_of(first), - below: self.factor_of(second), - }; + let factor = self.factor_of(first).over(self.factor_of(second))?; return Some(( Shown::Per(first.id, second.id), first.dim.over(second.dim), factor, )); } - let factor = Factor { - above: self.factor_of(first), - below: Decimal::ONE, - }; - Some((Shown::One(first.id), first.dim, factor)) + Some((Shown::One(first.id), first.dim, self.factor_of(first))) } fn conversion(&mut self) -> Answer { @@ -566,13 +578,14 @@ impl<'a> Parser<'a> { ) -> Answer { match value { Value::Quantity(quantity) => { - let (above, below) = match quantity.unit { - _ if quantity.dim.has_temperature() => (Decimal::ONE, Decimal::ONE), - Some(Shown::One(unit)) => (self.unit_factor(unit), Decimal::ONE), - Some(Shown::Per(top, bottom)) => { - (self.unit_factor(top), self.unit_factor(bottom)) - } - None => (Decimal::ONE, Decimal::ONE), + let Factor { above, below } = match quantity.unit { + _ if quantity.dim.has_temperature() => Factor::ONE, + Some(Shown::One(unit)) => self.unit_factor(unit), + Some(Shown::Per(top, bottom)) => self + .unit_factor(top) + .over(self.unit_factor(bottom)) + .ok_or_else(overflow)?, + None => Factor::ONE, }; let shown = quantity .amount @@ -1048,9 +1061,7 @@ impl<'a> Parser<'a> { .ok_or_else(overflow)?; } Ok(Value::Quantity(Quantity { - amount: number - .checked_mul(self.factor_of(unit)) - .ok_or_else(overflow)?, + amount: self.factor_of(unit).apply(number)?, dim: unit.dim, unit: Some(Shown::One(unit.id)), spans: false, diff --git a/crates/engine/src/notes/calc/units.rs b/crates/engine/src/notes/calc/units.rs index b8267c32f..c368ff2f8 100644 --- a/crates/engine/src/notes/calc/units.rs +++ b/crates/engine/src/notes/calc/units.rs @@ -580,15 +580,17 @@ impl Default for Css { } impl Css { - /// Metres in one pixel, `em` or `rem`; `None` for a unit the settings do not size. - pub fn factor(&self, unit: UnitId) -> Option { - let pixel = Decimal::new(254, 4).checked_div(self.ppi)?; - match unit { - UnitId::Pixel => Some(pixel), - UnitId::Em => self.em.checked_mul(pixel), - UnitId::Rem => self.rem.checked_mul(pixel), - _ => None, - } + /// Metres in one pixel, `em` or `rem`, as inches over the `ppi`: their quotient is not a + /// decimal, and an inch must read back as its 96 pixels. `None` for a unit the settings do + /// not size. + pub fn factor(&self, unit: UnitId) -> Option<(Decimal, Decimal)> { + let pixels = match unit { + UnitId::Pixel => Decimal::ONE, + UnitId::Em => self.em, + UnitId::Rem => self.rem, + _ => return None, + }; + Some((Decimal::new(254, 4).checked_mul(pixels)?, self.ppi)) } } From ab09b9971092b0ea3a001692f9af7fd46ce42484 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:24:12 +0100 Subject: [PATCH 11/95] Notes index: unit tests rewritten for filling, writes and reads (#1734) * Rewrite the tests of the notes index around its rules Slices newest first, a list while it fills, what a declared write re-reads, what an undeclared one leaves different, selection, facets and search. * Hold an undeclared decoration as told by name --- crates/engine/src/index.rs | 637 +++++++++++++++++++++++++++++++------ 1 file changed, 532 insertions(+), 105 deletions(-) diff --git a/crates/engine/src/index.rs b/crates/engine/src/index.rs index acd0f38ee..026ab377f 100644 --- a/crates/engine/src/index.rs +++ b/crates/engine/src/index.rs @@ -475,171 +475,596 @@ pub async fn fill(engine: Arc) { } } +#[cfg(test)] +mod oracle; + #[cfg(test)] mod tests { - use chrono::TimeDelta; + use chrono::{DateTime, TimeDelta, Utc}; use super::*; + use crate::attachments::model::Attachment; use crate::db::open_in_memory; - use crate::notes::fixtures::{NOW, at, note}; + use crate::notes::fixtures::{NOW, at}; + use crate::notes::language::Language; + use crate::notes::model::{NoteDraft, NoteLifecycle, NotePatch}; + use crate::notes::priority::Priority; + use crate::notes::view::{Grouping, NoteFilter, NoteOrder}; + + struct Shelf { + library: Library, + space: String, + } - /// `count` notes, the one numbered highest edited last. - fn library(count: u32) -> Library { + fn shelf() -> Shelf { let mut library = open_in_memory().unwrap(); - let space_id = crate::spaces::store::create(&mut library, "Perso") + let space = crate::spaces::store::create(&mut library, "Work") .unwrap() .id; - for n in 0..count { - let note = Note { - id: format!("n-{n:02}"), - space_id: space_id.clone(), - title: format!("Écrite n°{n}"), - content: format!("Corps {n}"), - tags: vec!["auth".to_string()], - updated_at: at(NOW) + TimeDelta::minutes(i64::from(n)), - ..note() - }; - store::insert_imported(&mut library, ¬e).unwrap(); + Shelf { library, space } + } + + fn minutes(n: i64) -> DateTime { + at(NOW) + TimeDelta::minutes(n) + } + + fn draft(space: &str, title: &str) -> NoteDraft { + NoteDraft { + space_id: space.into(), + folder_id: None, + title: title.into(), + language: Language::Sh, + content: format!("echo {title}"), + source: String::new(), + tags: Vec::new(), + pinned: false, + lifecycle: NoteLifecycle::Permanent, + kind: NoteKind::Snippet, + priority: Priority::None, + items: Vec::new(), + } + } + + impl Shelf { + /// A note edited `minutes` after the reference instant: the higher, the newer. + fn note(&mut self, title: &str, minute: i64) -> String { + let space = self.space.clone(); + store::create(&mut self.library, draft(&space, title), minutes(minute)) + .unwrap() + .id + } + + fn written(&mut self, draft: NoteDraft) -> String { + store::create(&mut self.library, draft, minutes(0)) + .unwrap() + .id + } + + fn full_index(&mut self) -> NoteIndex { + let mut index = NoteIndex::default(); + index.ready(&mut self.library).unwrap(); + index + } + } + + fn titles(index: &NoteIndex) -> Vec { + let mut titles: Vec = index + .notes + .values() + .map(|entry| entry.note.title.clone()) + .collect(); + titles.sort(); + titles + } + + fn query(space: Option<&str>) -> NotesQuery { + NotesQuery { + space_id: space.map(str::to_owned), + folder_id: None, + search: String::new(), + filter: NoteFilter::All, + tags: Vec::new(), + languages: Vec::new(), + kinds: Vec::new(), + priorities: Vec::new(), + order: NoteOrder::default(), + grouping: Grouping::default(), + ranked: false, + now: at(NOW), + tz_offset_minutes: 0, + pinned_first: true, } - library } + fn selected( + index: &NoteIndex, + request: &NotesQuery, + folders: Option<&HashSet>, + ) -> Vec { + index + .select(request, folders) + .0 + .iter() + .map(|entry| entry.note.title.clone()) + .collect() + } + + // --- Filling. + #[test] - fn it_fills_a_slice_at_a_time_from_the_note_edited_last() { - let mut library = library(7); + fn starting_reads_the_decorations_and_no_note_yet() { + let mut shelf = shelf(); + shelf.note("a", 0); + store::replace_global_placeholder_values( + &mut shelf.library, + &[("host".to_string(), "db".to_string())].into(), + ) + .unwrap(); let mut index = NoteIndex::default(); - index.start(&mut library).unwrap(); - assert!(index.next_slice(&mut library).unwrap()); - let mut first: Vec<&str> = index.notes.keys().map(String::as_str).collect(); - first.sort_unstable(); - assert_eq!(first, ["n-04", "n-05", "n-06"]); - assert!(!index.is_complete()); + index.start(&mut shelf.library).unwrap(); - assert!(index.next_slice(&mut library).unwrap()); - assert!(!index.next_slice(&mut library).unwrap()); - assert!(index.is_complete()); - assert_eq!(index.len(), 7); - assert!(!index.next_slice(&mut library).unwrap()); + assert!(index.is_empty()); + assert!(!index.is_complete()); + assert_eq!(index.decorations().globals["host"], "db"); } #[test] - fn an_entry_holds_the_note_as_the_store_reads_it_and_its_folded_text() { - let mut library = library(4); + fn slices_read_the_newest_notes_first_until_one_comes_short() { + let mut shelf = shelf(); + for minute in 1..=7 { + shelf.note(&format!("n{minute}"), minute); + } let mut index = NoteIndex::default(); - index.start(&mut library).unwrap(); - while index.next_slice(&mut library).unwrap() {} + index.start(&mut shelf.library).unwrap(); - for id in ["n-00", "n-01", "n-02", "n-03"] { - let entry = index.get(id).unwrap(); - assert_eq!(entry.note, store::get(&mut library, id).unwrap()); - assert_eq!( - entry.folded.title, - crate::notes::view::fold(&entry.note.title) - ); - } - assert!( - index - .get("n-01") - .unwrap() - .folded - .title - .starts_with("ecrite") - ); + assert!(index.next_slice(&mut shelf.library).unwrap()); + assert_eq!(titles(&index), ["n5", "n6", "n7"]); + assert!(index.next_slice(&mut shelf.library).unwrap()); + assert_eq!(index.len(), 6); + assert!(!index.next_slice(&mut shelf.library).unwrap()); + assert_eq!(index.len(), 7); + assert!(index.is_complete()); + assert!(!index.next_slice(&mut shelf.library).unwrap()); } #[test] - fn a_slice_read_for_one_library_stops_once_another_is_open() { - let (mut first, mut second) = (library(5), library(5)); + fn a_library_of_whole_slices_ends_on_an_empty_one() { + let mut shelf = shelf(); + for minute in 1..=6 { + shelf.note(&format!("n{minute}"), minute); + } let mut index = NoteIndex::default(); - index.start(&mut first).unwrap(); - index.next_slice(&mut first).unwrap(); + index.start(&mut shelf.library).unwrap(); - assert!(!index.next_slice(&mut second).unwrap()); - assert!(!index.is_complete()); + let answers: Vec = (0..3) + .map(|_| index.next_slice(&mut shelf.library).unwrap()) + .collect(); - index.start(&mut second).unwrap(); - assert!(index.is_empty(), "started over on the other one"); - assert!(index.next_slice(&mut second).unwrap()); + assert_eq!(answers, [true, true, false]); + assert!(index.is_complete()); + assert_eq!(index.len(), 6); } #[test] - fn starting_again_on_the_same_library_keeps_what_was_read() { - let mut library = library(5); - let mut index = NoteIndex::default(); - index.start(&mut library).unwrap(); - index.next_slice(&mut library).unwrap(); + fn notes_edited_in_the_same_instant_are_each_read_once() { + let mut shelf = shelf(); + for n in 0..5 { + shelf.note(&format!("n{n}"), 0); + } - index.start(&mut library).unwrap(); + let index = shelf.full_index(); - assert_eq!(index.len(), 3); + assert_eq!(titles(&index), ["n0", "n1", "n2", "n3", "n4"]); + } + + #[test] + fn a_trashed_note_is_not_indexed() { + let mut shelf = shelf(); + let gone = shelf.note("gone", 0); + shelf.note("kept", 1); + store::trash::trash(&mut shelf.library, &gone, minutes(2)).unwrap(); + + assert_eq!(titles(&shelf.full_index()), ["kept"]); } #[test] - fn a_list_takes_the_first_slice_while_a_fill_brings_the_rest() { - let mut library = library(5); + fn an_index_reads_nothing_of_a_library_it_was_not_started_on() { + let mut first = shelf(); + let mut second = shelf(); + second.note("elsewhere", 0); let mut index = NoteIndex::default(); - index.start(&mut library).unwrap(); - index.filling = true; + index.start(&mut first.library).unwrap(); - index.enough_to_list(&mut library).unwrap(); - assert_eq!(index.len(), 3); + assert!(!index.next_slice(&mut second.library).unwrap()); + assert!(index.is_empty()); + } - index.enough_to_list(&mut library).unwrap(); - assert_eq!(index.len(), 3); + #[test] + fn starting_again_keeps_the_same_library_and_drops_another() { + let mut first = shelf(); + first.note("a", 0); + let mut second = shelf(); + let mut index = first.full_index(); + + index.start(&mut first.library).unwrap(); + assert_eq!(index.len(), 1); + + index.start(&mut second.library).unwrap(); + assert!(index.is_empty()); } #[test] - fn a_list_reads_everything_when_no_fill_is_coming() { - let mut library = library(5); + fn a_list_asked_while_filling_answers_with_the_first_slice_alone() { + let mut shelf = shelf(); + for minute in 1..=5 { + shelf.note(&format!("n{minute}"), minute); + } let mut index = NoteIndex::default(); + index.start(&mut shelf.library).unwrap(); + index.filling = true; - index.enough_to_list(&mut library).unwrap(); + index.enough_to_list(&mut shelf.library).unwrap(); + assert_eq!(index.len(), 3); + index.enough_to_list(&mut shelf.library).unwrap(); + assert_eq!(index.len(), 3); + index.filling = false; + index.enough_to_list(&mut shelf.library).unwrap(); assert_eq!(index.len(), 5); } #[test] - fn the_last_slice_ends_the_fill() { - let mut library = library(2); + fn the_last_slice_ends_the_filling() { + let mut shelf = shelf(); + shelf.note("a", 0); let mut index = NoteIndex::default(); - index.start(&mut library).unwrap(); + index.start(&mut shelf.library).unwrap(); index.filling = true; - index.next_slice(&mut library).unwrap(); + index.next_slice(&mut shelf.library).unwrap(); assert!(!index.filling); } + // --- Kept true after a write. + #[test] - fn a_count_follows_a_note_that_changes() { - let mut library = library(2); - let mut index = NoteIndex::default(); - index.ready(&mut library).unwrap(); - assert_eq!(index.facets(None).tags[0].count, 2); + fn a_note_named_as_changed_is_read_again_or_dropped() { + let mut shelf = shelf(); + let edited = shelf.note("before", 0); + let trashed = shelf.note("trashed", 0); + let mut index = shelf.full_index(); + let retitle = NotePatch { + title: Some("after".into()), + ..NotePatch::default() + }; + store::update(&mut shelf.library, &edited, &retitle, minutes(1)).unwrap(); + store::trash::trash(&mut shelf.library, &trashed, minutes(1)).unwrap(); + let created = shelf.note("new", 2); - store::trash::trash(&mut library, "n-00", at(NOW)).unwrap(); - index - .refresh(&mut library, &Changed::notes(["n-00".to_string()])) + let changed = Changed::notes([edited, trashed, created]); + index.refresh(&mut shelf.library, &changed).unwrap(); + + assert_eq!(titles(&index), ["after", "new"]); + assert_eq!(index.matches(&mut shelf.library), Ok(())); + } + + #[test] + fn the_decorations_named_as_changed_are_read_again() { + let mut shelf = shelf(); + let id = shelf.note("a", 0); + let mut index = shelf.full_index(); + let space = shelf.space.clone(); + crate::folders::store::create(&mut shelf.library, &space, None, "Infra", minutes(1)) .unwrap(); + store::replace_global_placeholder_values( + &mut shelf.library, + &[("host".to_string(), "db".to_string())].into(), + ) + .unwrap(); + let attachment = Attachment { + id: "a-1".into(), + note_id: id.clone(), + file_name: "x.txt".into(), + mime_type: "text/plain".into(), + byte_size: 1, + created_at: minutes(1), + }; + let (db, vault) = shelf.library.split(); + crate::attachments::store::create(db, vault, &attachment).unwrap(); + + let changed = Changed { + attachments: true, + folders: true, + globals: true, + ..Changed::default() + }; + index.refresh(&mut shelf.library, &changed).unwrap(); - assert_eq!(index.facets(None).tags[0].count, 1); + let decorations = index.decorations(); + assert_eq!(decorations.attachment_counts[&id], 1); + assert_eq!(decorations.folders.len(), 1); + assert_eq!(decorations.globals["host"], "db"); + assert_eq!(index.matches(&mut shelf.library), Ok(())); } #[test] - fn cleared_it_holds_nothing_and_no_library() { - let mut library = library(2); - let mut index = NoteIndex::default(); - index.start(&mut library).unwrap(); - index.next_slice(&mut library).unwrap(); + fn a_change_too_wide_to_name_empties_the_index_for_the_next_read() { + let mut shelf = shelf(); + shelf.note("a", 0); + let mut index = shelf.full_index(); - index.clear(); + index + .refresh(&mut shelf.library, &Changed::everything()) + .unwrap(); assert!(index.is_empty()); - assert!(!index.next_slice(&mut library).unwrap()); + assert!(!index.is_complete()); + } + + #[test] + fn a_change_to_another_library_is_none_of_its_business() { + let mut first = shelf(); + first.note("a", 0); + let mut second = shelf(); + let mut index = first.full_index(); + + index + .refresh(&mut second.library, &Changed::everything()) + .unwrap(); + + assert_eq!(index.len(), 1); + } + + #[test] + fn a_write_left_undeclared_is_told_by_its_first_difference() { + let mut shelf = shelf(); + let id = shelf.note("before", 0); + let index = shelf.full_index(); + let retitle = NotePatch { + title: Some("after".into()), + ..NotePatch::default() + }; + store::update(&mut shelf.library, &id, &retitle, minutes(1)).unwrap(); + let mut other = self::shelf(); + + assert_eq!( + index.matches(&mut shelf.library), + Err(format!("note {id} differs")) + ); + assert_eq!(index.matches(&mut other.library), Ok(())); + } + + #[test] + fn a_decoration_left_undeclared_is_told_by_name() { + let mut shelf = shelf(); + let id = shelf.note("a", 0); + let space = shelf.space.clone(); + + let index = shelf.full_index(); + crate::folders::store::create(&mut shelf.library, &space, None, "Infra", minutes(1)) + .unwrap(); + assert_eq!( + index.matches(&mut shelf.library), + Err("folders differ".to_string()) + ); + + let index = shelf.full_index(); + store::replace_global_placeholder_values( + &mut shelf.library, + &[("host".to_string(), "db".to_string())].into(), + ) + .unwrap(); + assert_eq!( + index.matches(&mut shelf.library), + Err("global values differ".to_string()) + ); + + let index = shelf.full_index(); + let attachment = Attachment { + id: "a-1".into(), + note_id: id, + file_name: "x.txt".into(), + mime_type: "text/plain".into(), + byte_size: 1, + created_at: minutes(1), + }; + let (db, vault) = shelf.library.split(); + crate::attachments::store::create(db, vault, &attachment).unwrap(); + assert_eq!( + index.matches(&mut shelf.library), + Err("attachment counts differ".to_string()) + ); + } + + #[test] + fn a_note_missing_from_the_index_is_told_too() { + let mut shelf = shelf(); + shelf.note("a", 0); + let index = shelf.full_index(); + shelf.note("b", 1); + + assert!( + index + .matches(&mut shelf.library) + .unwrap_err() + .starts_with("notes ") + ); + } + + // --- Reading it. + + #[test] + fn a_selection_keeps_the_space_and_runs_from_the_last_edit_then_the_id() { + let mut shelf = shelf(); + shelf.note("old", 0); + let mut tie = [ + (shelf.note("b-new", 5), "b-new"), + (shelf.note("a-new", 5), "a-new"), + ]; + let elsewhere = crate::spaces::store::create(&mut shelf.library, "Home") + .unwrap() + .id; + shelf.written(draft(&elsewhere, "home")); + let index = shelf.full_index(); + let space = shelf.space.clone(); + tie.sort(); + + let expected: Vec<&str> = tie.iter().map(|(_, title)| *title).chain(["old"]).collect(); + assert_eq!(selected(&index, &query(Some(&space)), None), expected); + assert_eq!(selected(&index, &query(None), None).len(), 4); } - /// S4: sorting itself, SQLite read every sealed body before the first row (1.76 s). + #[test] + fn a_selection_keeps_the_notes_filed_in_the_folders_given_and_the_rails() { + let mut shelf = shelf(); + let space = shelf.space.clone(); + let folder = + crate::folders::store::create(&mut shelf.library, &space, None, "Infra", minutes(0)) + .unwrap() + .id; + shelf.written(NoteDraft { + folder_id: Some(folder.clone()), + pinned: true, + ..draft(&space, "filed") + }); + shelf.written(draft(&space, "loose")); + let index = shelf.full_index(); + let pinned = NotesQuery { + filter: NoteFilter::Pinned, + ..query(None) + }; + + assert_eq!( + selected(&index, &query(None), Some(&[folder].into())), + ["filed"] + ); + assert_eq!(selected(&index, &pinned, None), ["filed"]); + } + + #[test] + fn facets_count_the_space_s_notes_by_folded_tag_alike_but_for_case_as_one() { + let mut shelf = shelf(); + let space = shelf.space.clone(); + shelf.written(NoteDraft { + tags: vec!["ops".into()], + ..draft(&space, "a") + }); + shelf.written(NoteDraft { + tags: vec!["OPS".into(), "ci".into()], + kind: NoteKind::Note, + ..draft(&space, "b") + }); + let elsewhere = crate::spaces::store::create(&mut shelf.library, "Home") + .unwrap() + .id; + shelf.written(NoteDraft { + tags: vec!["home".into()], + ..draft(&elsewhere, "c") + }); + let index = shelf.full_index(); + + let facets = index.facets(Some(&space)); + + let tags: Vec<_> = facets + .tags + .iter() + .map(|tag| (tag.value.as_str(), tag.count)) + .collect(); + assert_eq!(tags, [("ci", 1), ("OPS", 2)]); + assert_eq!( + facets.languages, + view::count_languages(&[("sh".to_string(), 1)]) + ); + assert_eq!( + facets.kinds[1], + view::FacetCount { + value: NoteKind::Note, + count: 1 + } + ); + assert_eq!(index.facets(None).tags.len(), 3); + } + + #[test] + fn facets_follow_a_note_read_again() { + let mut shelf = shelf(); + let id = shelf.note("a", 0); + let mut index = shelf.full_index(); + assert!(index.facets(None).tags.is_empty()); + let tag = NotePatch { + tags: Some(vec!["ops".into()]), + ..NotePatch::default() + }; + store::update(&mut shelf.library, &id, &tag, minutes(1)).unwrap(); + + index + .refresh(&mut shelf.library, &Changed::notes([id])) + .unwrap(); + + assert_eq!(index.facets(None).tags[0].value, "ops"); + } + + #[test] + fn a_search_keeps_the_notes_that_answer_in_their_order_with_their_quote() { + let mut shelf = shelf(); + shelf.note("psql", 2); + shelf.note("redis", 1); + let quoted = shelf.note("deploy", 0); + let space = shelf.space.clone(); + store::update( + &mut shelf.library, + "ed, + &NotePatch { + content: Some("psql -h db".into()), + ..NotePatch::default() + }, + minutes(0), + ) + .unwrap(); + let index = shelf.full_index(); + let (entries, _) = index.select(&query(Some(&space)), None); + + let found = search(&entries, "psql"); + let everything = search(&entries, ""); + + let titles: Vec<_> = found.iter().map(|card| card.title.clone()).collect(); + assert_eq!(titles, ["psql", "deploy"]); + assert!(found[0].hit.is_none()); + assert_eq!(found[1].hit.as_ref().unwrap().excerpt, "psql -h db"); + assert_eq!(everything.len(), 3); + assert!(everything.iter().all(|card| card.hit.is_none())); + } + + #[test] + fn a_note_is_found_by_its_id() { + let mut shelf = shelf(); + let id = shelf.note("a", 0); + let index = shelf.full_index(); + + assert_eq!( + index.get(&id).map(|entry| entry.note.title.as_str()), + Some("a") + ); + assert!(index.get("missing").is_none()); + } + + // --- Kept from the tests before. + + #[test] + fn an_entry_holds_the_note_as_the_store_reads_it_and_its_folded_text() { + let mut shelf = shelf(); + let id = shelf.note("Écrite", 0); + let index = shelf.full_index(); + + let entry = index.get(&id).unwrap(); + + assert_eq!(entry.note, store::get(&mut shelf.library, &id).unwrap()); + assert_eq!(entry.folded.title, "ecrite"); + } + + /// Sorting itself, SQLite read every sealed body before the first row (1.76 s). #[test] fn a_slice_is_read_in_the_order_of_the_updated_at_index() { use diesel::prelude::*; @@ -650,11 +1075,13 @@ mod tests { detail: String, } - let mut library = library(1); + let mut shelf = shelf(); let plan: Vec = diesel::sql_query( - "EXPLAIN QUERY PLAN SELECT * FROM notes WHERE deleted_at IS NULL AND (updated_at < '9' OR (updated_at = '9' AND id > 'a')) ORDER BY updated_at DESC, id ASC LIMIT 2000", + "EXPLAIN QUERY PLAN SELECT * FROM notes WHERE deleted_at IS NULL \ + AND (updated_at < '9' OR (updated_at = '9' AND id > 'a')) \ + ORDER BY updated_at DESC, id ASC LIMIT 2000", ) - .load::(library.db()) + .load::(shelf.library.db()) .unwrap() .into_iter() .map(|step| step.detail) @@ -672,13 +1099,13 @@ mod tests { ); } + /// Nothing of the index reaches the disk, and what it held is wiped when it goes. #[test] - fn a_dropped_value_map_is_left_empty() { + fn a_value_map_let_go_is_left_empty() { let mut values = BTreeMap::from([("host".to_string(), "prod.example".to_string())]); + wipe_values(&mut values); + assert!(values.is_empty()); } } - -#[cfg(test)] -mod oracle; From e5b14aa008409fccc95eb40076c9b95dfa4fb680 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:24:19 +0100 Subject: [PATCH 12/95] Note store: unit tests rewritten for writing, sealing and fields (#1735) * Rewrite the tests of writing a note through the store Creating, editing, what is sealed and what degrades, a todo list's items and a snippet's field values. * Rewrite the side tables' tests and keep the file-level sealing check --- crates/engine/src/notes/store/related.rs | 175 +++++---- crates/engine/tests/notes/checklists.rs | 164 ++++----- crates/engine/tests/notes/fields.rs | 228 +++++++----- crates/engine/tests/notes/main.rs | 3 +- crates/engine/tests/notes/storage.rs | 179 +++++++--- crates/engine/tests/notes/writes.rs | 432 +++++++---------------- 6 files changed, 582 insertions(+), 599 deletions(-) diff --git a/crates/engine/src/notes/store/related.rs b/crates/engine/src/notes/store/related.rs index 933a2b2f4..12d8e42e7 100644 --- a/crates/engine/src/notes/store/related.rs +++ b/crates/engine/src/notes/store/related.rs @@ -294,90 +294,123 @@ pub fn replace_placeholder_values( #[cfg(test)] mod tests { use super::*; + use crate::db::{Library, open_in_memory}; + use crate::notes::fixtures::{NOW, at}; + use crate::notes::kind::NoteKind; + use crate::notes::language::Language; + use crate::notes::model::{NoteDraft, NoteLifecycle}; + use crate::notes::priority::Priority; + use crate::notes::store; + + fn draft(space: &str, tag: &str) -> NoteDraft { + NoteDraft { + space_id: space.into(), + folder_id: None, + title: tag.into(), + language: Language::Txt, + content: String::new(), + source: String::new(), + tags: vec![tag.into()], + pinned: false, + lifecycle: NoteLifecycle::Permanent, + kind: NoteKind::Checklist, + priority: Priority::None, + items: vec![ChecklistItem { + text: format!("do {tag}"), + done: false, + }], + } + } + + fn written(library: &mut Library, space: &str, count: usize) -> Vec { + (0..count) + .map(|n| store::create(library, draft(space, &format!("t{n}")), at(NOW)).unwrap()) + .collect() + } + + fn emptied(notes: &[Note]) -> Vec { + notes + .iter() + .map(|note| Note { + tags: Vec::new(), + items: Vec::new(), + ..note.clone() + }) + .collect() + } + + #[test] + fn a_few_notes_get_their_own_side_tables_back() { + let mut library = open_in_memory().unwrap(); + let space = crate::spaces::store::create(&mut library, "Work") + .unwrap() + .id; + let notes = written(&mut library, &space, 3); + let mut read = emptied(¬es); + + let (db, vault) = library.split(); + attach_related(db, vault, &mut read, Some(&space)).unwrap(); + + assert_eq!(read, notes); + } - fn ids(count: usize) -> Vec { - (0..count).map(|n| format!("n-{n}")).collect() + /// Past the bind limit the side tables are read by space, a superset the notes pick from. + #[test] + fn more_notes_than_can_be_bound_get_theirs_back_too() { + let mut library = open_in_memory().unwrap(); + let space = crate::spaces::store::create(&mut library, "Work") + .unwrap() + .id; + let other = crate::spaces::store::create(&mut library, "Home") + .unwrap() + .id; + let notes = written(&mut library, &space, BIND_AT_MOST + 1); + written(&mut library, &other, 2); + + for scope in [Some(space.as_str()), None] { + let mut read = emptied(¬es); + let (db, vault) = library.split(); + attach_related(db, vault, &mut read, scope).unwrap(); + + assert_eq!(read, notes, "{scope:?}"); + } } #[test] - fn a_few_notes_are_read_by_their_ids() { - let few = ids(BIND_AT_MOST); + fn no_note_reads_nothing() { + let mut library = open_in_memory().unwrap(); + let (db, vault) = library.split(); - assert!( - matches!(Scope::of(&few, Some("s-1")), Scope::Notes(bound) if bound.len() == BIND_AT_MOST) - ); + attach_related(db, vault, &mut [], None).unwrap(); } #[test] - fn many_notes_are_read_by_their_space() { - let many = ids(BIND_AT_MOST + 1); - - assert!(matches!( - Scope::of(&many, Some("s-1")), - Scope::Space(Some("s-1")) - )); - assert!(matches!(Scope::of(&many, None), Scope::Space(None))); + fn tags_written_again_read_back_in_the_column_s_collation_once_each() { + let mut library = open_in_memory().unwrap(); + let space = crate::spaces::store::create(&mut library, "Work") + .unwrap() + .id; + let id = written(&mut library, &space, 1)[0].id.clone(); + let tags: Vec = ["b", "A", "c", "a"].map(String::from).to_vec(); + + let read = replace_tags(library.db(), &id, &tags).unwrap(); + + assert_eq!(read, ["A", "b", "c"]); + assert!(replace_tags(library.db(), &id, &[]).unwrap().is_empty()); } - /// Past the bound the space's subquery reads them, with a space and without one. #[test] - fn past_the_bound_every_note_still_carries_its_tags_and_items() { - use crate::notes::kind::NoteKind; - use crate::notes::language::Language; - use crate::notes::model::{NoteDraft, NoteLifecycle}; - use crate::notes::priority::Priority; - use crate::notes::view::{Grouping, NoteFilter, NoteOrder, NotesQuery}; - - let mut library = crate::db::open_in_memory().unwrap(); - let space = crate::spaces::store::create(&mut library, "Ops") + fn the_trash_s_tags_are_its_notes_alone() { + let mut library = open_in_memory().unwrap(); + let space = crate::spaces::store::create(&mut library, "Work") .unwrap() .id; - for n in 0..=BIND_AT_MOST { - let draft = NoteDraft { - space_id: space.clone(), - folder_id: None, - title: format!("List {n}"), - language: Language::Txt, - content: String::new(), - source: String::new(), - tags: vec!["ops".to_string()], - pinned: false, - lifecycle: NoteLifecycle::Permanent, - kind: NoteKind::Checklist, - priority: Priority::None, - items: vec![ChecklistItem { - text: "Restart".to_string(), - done: false, - }], - }; - crate::notes::store::create(&mut library, draft, chrono::Utc::now()).unwrap(); - } + let notes = written(&mut library, &space, 2); + store::trash::trash(&mut library, ¬es[0].id, at(NOW)).unwrap(); - for space_id in [Some(space.clone()), None] { - let query = NotesQuery { - space_id, - folder_id: None, - search: String::new(), - filter: NoteFilter::All, - tags: Vec::new(), - languages: Vec::new(), - kinds: Vec::new(), - priorities: Vec::new(), - order: NoteOrder::default(), - grouping: Grouping::default(), - ranked: false, - now: chrono::Utc::now(), - tz_offset_minutes: 0, - pinned_first: true, - }; - let (notes, _) = crate::notes::store::fetch(&mut library, &query).unwrap(); - - assert_eq!(notes.len(), BIND_AT_MOST + 1); - assert!( - notes - .iter() - .all(|note| note.tags == ["ops"] && note.items.len() == 1) - ); - } + let tags = trashed_tags(library.db()).unwrap(); + + assert_eq!(tags.len(), 1); + assert_eq!(tags[¬es[0].id], ["t0"]); } } diff --git a/crates/engine/tests/notes/checklists.rs b/crates/engine/tests/notes/checklists.rs index 383a35339..886864e5b 100644 --- a/crates/engine/tests/notes/checklists.rs +++ b/crates/engine/tests/notes/checklists.rs @@ -1,133 +1,111 @@ use super::*; +fn items(connection: &mut Library, id: &str, written: Vec) -> Vec { + let patch = NotePatch { + items: Some(written), + ..NotePatch::default() + }; + update(connection, id, &patch, t1()).unwrap(); + get(connection, id).unwrap().items +} + +fn todo_list(connection: &mut Library, written: Vec) -> String { + let space_id = space(connection, "Work"); + create(connection, checklist(&space_id, written), t0()) + .unwrap() + .id +} + #[test] -fn a_checklist_is_read_back_in_the_order_it_was_written() { +fn a_todo_list_reads_back_its_items_in_order_with_their_state() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); + let written = vec![item("b", true), item("a", false), item("b", true)]; - let created = create( - &mut connection, - checklist( - &space_id, - vec![item("Relire", true), item("Déployer", false)], - ), - t0(), - ) - .unwrap(); + let id = todo_list(&mut connection, written.clone()); - assert_eq!(created.kind, NoteKind::Checklist); - assert_eq!( - created.items, - [item("Relire", true), item("Déployer", false)] - ); - assert_eq!(list(&mut connection).unwrap()[0].items, created.items); + assert_eq!(get(&mut connection, &id).unwrap().items, written); } #[test] -fn patching_the_items_replaces_the_whole_list() { +fn a_list_written_again_replaces_the_one_before_whole() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let created = create( + let id = todo_list( &mut connection, - checklist( - &space_id, - vec![item("a", false), item("b", false), item("c", false)], - ), - t0(), - ) - .unwrap(); + vec![item("a", false), item("b", false), item("c", false)], + ); - let updated = update( + let shorter = items( &mut connection, - &created.id, - &NotePatch { - items: Some(vec![item("c", true), item("a", false)]), - ..NotePatch::default() - }, - t1(), - ) - .unwrap(); + &id, + vec![item("c", true), item("a", false)], + ); - assert_eq!(updated.items, [item("c", true), item("a", false)]); - assert_eq!(list(&mut connection).unwrap()[0].items, updated.items); + assert_eq!(shorter, [item("c", true), item("a", false)]); + let rows: i64 = note_items::table + .count() + .get_result(connection.db()) + .unwrap(); + assert_eq!(rows, 2); } #[test] -fn emptying_the_list_leaves_no_row_behind() { +fn a_list_emptied_holds_nothing() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let created = create( - &mut connection, - checklist(&space_id, vec![item("a", false)]), - t0(), - ) - .unwrap(); + let id = todo_list(&mut connection, vec![item("a", false)]); - update( - &mut connection, - &created.id, - &NotePatch { - items: Some(Vec::new()), - ..NotePatch::default() - }, - t1(), - ) - .unwrap(); + assert!(items(&mut connection, &id, Vec::new()).is_empty()); +} - assert!(list(&mut connection).unwrap()[0].items.is_empty()); - assert_eq!( - note_items::table - .count() - .get_result::(connection.db()) - .unwrap(), - 0 +#[test] +fn blank_items_are_left_out_and_the_others_trimmed() { + let mut connection = open_in_memory().unwrap(); + let id = todo_list( + &mut connection, + vec![item(" a ", false), item(" ", true)], ); + + assert_eq!(get(&mut connection, &id).unwrap().items, [item("a", false)]); } #[test] -fn a_patch_that_says_nothing_about_the_items_leaves_them_stored() { +fn an_item_s_text_is_sealed_in_its_column() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let created = create( - &mut connection, - checklist(&space_id, vec![item("a", true)]), - t0(), - ) - .unwrap(); + todo_list(&mut connection, vec![item("secret task", false)]); - let updated = update( - &mut connection, - &created.id, - &NotePatch { - title: Some("Sprint".to_string()), - ..NotePatch::default() - }, - t1(), - ) - .unwrap(); + let texts: Vec = note_items::table + .select(note_items::text) + .load(connection.db()) + .unwrap(); - assert_eq!(updated.items, [item("a", true)]); + assert_eq!(texts.len(), 1); + assert!(!texts[0].contains("secret")); } #[test] -fn purging_removes_the_note_and_its_items_for_good() { +fn a_list_of_notes_carries_each_note_s_own_items() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let created = create( + let space_id = space(&mut connection, "Work"); + create( &mut connection, - checklist(&space_id, vec![item("a", false)]), + checklist(&space_id, vec![item("first", false)]), t0(), ) .unwrap(); - trash(&mut connection, &created.id, t1()).unwrap(); + create( + &mut connection, + checklist(&space_id, vec![item("second", true)]), + t1(), + ) + .unwrap(); - purge(&mut connection, std::slice::from_ref(&created.id)).unwrap(); + let read: Vec> = list(&mut connection) + .unwrap() + .into_iter() + .map(|note| note.items) + .collect(); assert_eq!( - note_items::table - .count() - .get_result::(connection.db()) - .unwrap(), - 0 + read, + [vec![item("second", true)], vec![item("first", false)]] ); } diff --git a/crates/engine/tests/notes/fields.rs b/crates/engine/tests/notes/fields.rs index af940c1da..8355f3bee 100644 --- a/crates/engine/tests/notes/fields.rs +++ b/crates/engine/tests/notes/fields.rs @@ -1,172 +1,216 @@ use super::*; -#[test] -fn a_filled_field_is_read_back_on_the_next_opening() { - let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let created = create(&mut connection, templated(&space_id), t0()).unwrap(); - - set_placeholder_values(&mut connection, &created.id, &values(&[("host", "db")])).unwrap(); - - let listed = list(&mut connection).unwrap(); - assert_eq!(listed[0].placeholder_values, values(&[("host", "db")])); +fn snippet_with_fields(connection: &mut Library) -> String { + let space_id = space(connection, "Work"); + create(connection, templated(&space_id), t0()).unwrap().id } #[test] -fn filling_a_field_does_not_touch_updated_at() { +fn a_note_s_values_read_back_by_name_as_typed() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let created = create(&mut connection, templated(&space_id), t0()).unwrap(); + let id = snippet_with_fields(&mut connection); + let typed = values(&[("host", "db.internal"), ("Host", "other")]); - let saved = - set_placeholder_values(&mut connection, &created.id, &values(&[("host", "db")])).unwrap(); + let written = set_placeholder_values(&mut connection, &id, &typed).unwrap(); - assert_eq!(saved.updated_at, t0()); - assert_eq!(list(&mut connection).unwrap()[0].updated_at, t0()); + assert_eq!(written.placeholder_values, typed); + assert_eq!(get(&mut connection, &id).unwrap().placeholder_values, typed); } #[test] -fn writing_the_values_replaces_the_whole_set() { +fn values_written_again_replace_the_ones_before_whole() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let created = create(&mut connection, templated(&space_id), t0()).unwrap(); + let id = snippet_with_fields(&mut connection); set_placeholder_values( &mut connection, - &created.id, - &values(&[("host", "db"), ("port", "6543")]), + &id, + &values(&[("host", "a"), ("port", "1")]), ) .unwrap(); - set_placeholder_values(&mut connection, &created.id, &values(&[("host", "db")])).unwrap(); + set_placeholder_values(&mut connection, &id, &values(&[("port", "2")])).unwrap(); assert_eq!( - list(&mut connection).unwrap()[0].placeholder_values, - values(&[("host", "db")]) + get(&mut connection, &id).unwrap().placeholder_values, + values(&[("port", "2")]) ); } +/// Filling a field is not editing the note, and the canvas sorts on that column. #[test] -fn a_value_whose_token_left_the_content_stays_stored_but_out_of_the_fields() { +fn writing_values_leaves_the_date_of_the_last_edit() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let created = create(&mut connection, templated(&space_id), t0()).unwrap(); - set_placeholder_values(&mut connection, &created.id, &values(&[("host", "db")])).unwrap(); + let id = snippet_with_fields(&mut connection); - let renamed = update( - &mut connection, - &created.id, - &NotePatch { - content: Some("psql -h {{hostname}}".to_string()), - ..NotePatch::default() - }, - t1(), - ) - .unwrap(); + set_placeholder_values(&mut connection, &id, &values(&[("host", "db")])).unwrap(); - assert_eq!(renamed.placeholder_values, values(&[("host", "db")])); - let fields = decorate(renamed, t1()).placeholders; - assert_eq!(fields.len(), 1); - assert_eq!(fields[0].name, "hostname"); - assert!(fields[0].value.is_empty()); + assert_eq!(get(&mut connection, &id).unwrap().updated_at, t0()); } #[test] -fn filling_a_trashed_note_is_refused() { +fn values_for_a_note_that_is_not_there_fail_by_name() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let created = create(&mut connection, templated(&space_id), t0()).unwrap(); - trash(&mut connection, &created.id, t1()).unwrap(); - let error = set_placeholder_values(&mut connection, &created.id, &values(&[("host", "db")])) - .unwrap_err(); + assert!(matches!( + set_placeholder_values(&mut connection, "missing", &values(&[("host", "db")])), + Err(StorageError::NoteNotFound(id)) if id == "missing" + )); +} - assert!(matches!(error, StorageError::NoteNotFound(_))); +#[test] +fn a_value_is_sealed_and_its_name_is_not() { + let mut connection = open_in_memory().unwrap(); + let id = snippet_with_fields(&mut connection); + set_placeholder_values( + &mut connection, + &id, + &values(&[("host", "secret.internal")]), + ) + .unwrap(); + + let rows: Vec<(String, String)> = note_placeholders::table + .select((note_placeholders::name, note_placeholders::value)) + .load(connection.db()) + .unwrap(); + + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].0, "host"); + assert!(!rows[0].1.contains("secret")); } #[test] -fn purging_removes_the_note_and_its_values_for_good() { +fn a_list_of_notes_carries_each_note_s_own_values() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let created = create(&mut connection, templated(&space_id), t0()).unwrap(); - set_placeholder_values(&mut connection, &created.id, &values(&[("host", "db")])).unwrap(); - trash(&mut connection, &created.id, t1()).unwrap(); + let space_id = space(&mut connection, "Work"); + let first = create(&mut connection, templated(&space_id), t0()) + .unwrap() + .id; + let second = create(&mut connection, templated(&space_id), t1()) + .unwrap() + .id; + set_placeholder_values(&mut connection, &first, &values(&[("host", "one")])).unwrap(); + set_placeholder_values(&mut connection, &second, &values(&[("host", "two")])).unwrap(); - purge(&mut connection, std::slice::from_ref(&created.id)).unwrap(); + let read: Vec<_> = list(&mut connection) + .unwrap() + .into_iter() + .map(|note| note.placeholder_values) + .collect(); assert_eq!( - note_placeholders::table - .count() - .get_result::(connection.db()) - .unwrap(), - 0 + read, + [values(&[("host", "two")]), values(&[("host", "one")])] ); } #[test] -fn global_variables_read_back_what_was_written() { +fn global_values_are_replaced_whole_and_read_by_name() { let mut connection = open_in_memory().unwrap(); - replace_global_placeholder_values(&mut connection, &values(&[("host", "db.internal")])) + replace_global_placeholder_values(&mut connection, &values(&[("port", "1"), ("host", "a")])) + .unwrap(); + replace_global_placeholder_values(&mut connection, &values(&[("user", "ada"), ("host", "b")])) .unwrap(); assert_eq!( global_placeholder_values(&mut connection).unwrap(), - values(&[("host", "db.internal")]) + values(&[("host", "b"), ("user", "ada")]) ); } #[test] -fn writing_the_set_again_drops_what_is_no_longer_sent() { +fn global_values_emptied_hold_nothing_and_are_sealed_while_held() { let mut connection = open_in_memory().unwrap(); - replace_global_placeholder_values( - &mut connection, - &values(&[("host", "db.internal"), ("port", "5432")]), - ) - .unwrap(); + replace_global_placeholder_values(&mut connection, &values(&[("host", "secret")])).unwrap(); + let sealed: Vec = engine::db::schema::global_placeholders::table + .select(engine::db::schema::global_placeholders::value) + .load(connection.db()) + .unwrap(); - replace_global_placeholder_values(&mut connection, &values(&[("port", "6543")])).unwrap(); + replace_global_placeholder_values(&mut connection, &BTreeMap::new()).unwrap(); + assert!(!sealed[0].contains("secret")); + assert!( + global_placeholder_values(&mut connection) + .unwrap() + .is_empty() + ); +} + +#[test] +fn a_trashed_note_s_values_cannot_be_written() { + let mut connection = open_in_memory().unwrap(); + let id = snippet_with_fields(&mut connection); + trash(&mut connection, &id, t1()).unwrap(); + + assert!(matches!( + set_placeholder_values(&mut connection, &id, &values(&[("host", "db")])), + Err(StorageError::NoteNotFound(_)) + )); +} + +/// The text says which fields exist: a value whose token was renamed waits for it to return. +#[test] +fn a_value_whose_token_left_the_text_stays_stored_but_out_of_the_fields() { + let mut connection = open_in_memory().unwrap(); + let id = snippet_with_fields(&mut connection); + set_placeholder_values(&mut connection, &id, &values(&[("host", "db")])).unwrap(); + let renamed = NotePatch { + content: Some("psql -h {{hostname}}".to_string()), + ..NotePatch::default() + }; + + let edited = update(&mut connection, &id, &renamed, t1()).unwrap(); + + assert_eq!(edited.placeholder_values, values(&[("host", "db")])); + let fields = engine::notes::model::decorate(edited, t1()).placeholders; + assert_eq!(fields.len(), 1); assert_eq!( - global_placeholder_values(&mut connection).unwrap(), - values(&[("port", "6543")]) + (fields[0].name.as_str(), fields[0].value.as_str()), + ("hostname", "") ); } #[test] -fn a_global_variable_belongs_to_no_note_and_survives_a_purge() { +fn a_global_value_belongs_to_no_note_and_outlives_a_purge() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let created = create(&mut connection, templated(&space_id), t0()).unwrap(); - replace_global_placeholder_values(&mut connection, &values(&[("host", "db.internal")])) - .unwrap(); - trash(&mut connection, &created.id, t1()).unwrap(); + let id = snippet_with_fields(&mut connection); + set_placeholder_values(&mut connection, &id, &values(&[("port", "1")])).unwrap(); + replace_global_placeholder_values(&mut connection, &values(&[("host", "db")])).unwrap(); + trash(&mut connection, &id, t1()).unwrap(); - purge(&mut connection, std::slice::from_ref(&created.id)).unwrap(); + purge(&mut connection, std::slice::from_ref(&id)).unwrap(); assert_eq!( global_placeholder_values(&mut connection).unwrap(), - values(&[("host", "db.internal")]) + values(&[("host", "db")]) ); + let left: i64 = note_placeholders::table + .count() + .get_result(connection.db()) + .unwrap(); + assert_eq!(left, 0); } #[test] -fn a_global_variable_shows_up_as_the_suggested_value_of_a_field() { +fn a_global_value_reaches_a_card_as_its_field_s_suggestion() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let created = create(&mut connection, templated(&space_id), t0()).unwrap(); - + let id = snippet_with_fields(&mut connection); replace_global_placeholder_values(&mut connection, &values(&[("host", "db.internal")])) .unwrap(); - let mut display = decorate(created, t1()); + let mut shown = engine::notes::model::decorate(get(&mut connection, &id).unwrap(), t1()); + engine::notes::store::decorations(&mut connection) .unwrap() - .apply([&mut display]); + .apply([&mut shown]); - let field = display + let host = shown .placeholders .iter() - .find(|placeholder| placeholder.name == "host") + .find(|field| field.name == "host") .unwrap(); - assert_eq!(field.default_value, "db.internal"); - assert!(field.value.is_empty()); + assert_eq!( + (host.default_value.as_str(), host.value.as_str()), + ("db.internal", "") + ); } diff --git a/crates/engine/tests/notes/main.rs b/crates/engine/tests/notes/main.rs index d4b78e736..2e9506a81 100644 --- a/crates/engine/tests/notes/main.rs +++ b/crates/engine/tests/notes/main.rs @@ -6,14 +6,13 @@ use engine::db::Library; use engine::db::open_in_memory; use engine::db::schema::{ note_items, note_placeholders, note_revisions, note_tags, notes as notes_table, - spaces as spaces_table, }; use engine::error::StorageError; use engine::notes::checklist::ChecklistItem; use engine::notes::kind::NoteKind; use engine::notes::language::Language; use engine::notes::model::{ - DisplayNote, Note, NoteDraft, NoteLifecycle, NotePatch, NotePriority, PREVIEW_LINES, decorate, + DisplayNote, Note, NoteDraft, NoteLifecycle, NotePatch, NotePriority, PREVIEW_LINES, }; use engine::notes::priority::Priority; use engine::notes::store::trash::{expired_ids, list_trashed, purge, restore_many, trash}; diff --git a/crates/engine/tests/notes/storage.rs b/crates/engine/tests/notes/storage.rs index 177483872..2aa34e165 100644 --- a/crates/engine/tests/notes/storage.rs +++ b/crates/engine/tests/notes/storage.rs @@ -1,81 +1,174 @@ use super::*; +use diesel::sql_query; + +fn note(connection: &mut Library) -> String { + let space_id = space(connection, "Work"); + let secret = NoteDraft { + title: "secret title".to_string(), + content: "secret body".to_string(), + source: "secret source".to_string(), + ..tagged(&space_id, &["visible"]) + }; + create(connection, secret, t0()).unwrap().id +} + +fn set_column(connection: &mut Library, column: &str, value: &str) { + sql_query(format!("UPDATE notes SET {column} = '{value}'")) + .execute(connection.db()) + .unwrap(); +} + +fn column(connection: &mut Library, column: &str) -> String { + #[derive(QueryableByName)] + struct Value { + #[diesel(sql_type = diesel::sql_types::Text)] + value: String, + } + + sql_query(format!("SELECT {column} AS value FROM notes")) + .get_result::(connection.db()) + .unwrap() + .value +} #[test] -fn tags_are_normalized_on_write() { +fn what_a_reader_would_want_is_sealed_and_what_sql_sorts_on_is_not() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - - let created = create( - &mut connection, - tagged(&space_id, &[" #urgent ", "URGENT", "", " # ", "later"]), - t0(), - ) - .unwrap(); + note(&mut connection); - assert_eq!(created.tags, ["later", "urgent"]); - assert_eq!(list(&mut connection).unwrap()[0].tags, ["later", "urgent"]); + for sealed in ["title", "content", "source"] { + assert!( + !column(&mut connection, sealed).contains("secret"), + "{sealed}" + ); + } + assert_eq!(column(&mut connection, "language"), "txt"); + assert_eq!(column(&mut connection, "kind"), "snippet"); + assert_eq!(column(&mut connection, "priority"), "none"); + let pinned: bool = notes_table::table + .select(notes_table::pinned) + .first(connection.db()) + .unwrap(); + assert!(!pinned); + let tags: Vec = note_tags::table + .select(note_tags::tag) + .load(connection.db()) + .unwrap(); + assert_eq!(tags, ["visible"]); } #[test] -fn a_normalized_write_returns_what_a_read_would_return() { +fn a_value_a_newer_version_wrote_reads_as_the_default() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); + let id = note(&mut connection); + set_column(&mut connection, "language", "brainfuck"); + set_column(&mut connection, "kind", "kanban"); + set_column(&mut connection, "priority", "critical"); - let created = create(&mut connection, tagged(&space_id, &["zeta", "alpha"]), t0()).unwrap(); + let read = get(&mut connection, &id).unwrap(); - assert_eq!(created.tags, list(&mut connection).unwrap()[0].tags); + assert_eq!( + (read.language, read.kind, read.priority), + (Language::Txt, NoteKind::Snippet, Priority::None) + ); } +/// An edit writing every column back would make the fallback permanent. #[test] -fn deleting_a_space_takes_its_notes_with_it() { +fn an_edit_leaves_an_unknown_value_it_did_not_touch_as_it_was() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - create(&mut connection, draft(&space_id), t0()).unwrap(); + let id = note(&mut connection); + set_column(&mut connection, "language", "brainfuck"); + let retitle = NotePatch { + title: Some("Renamed".to_string()), + ..NotePatch::default() + }; - diesel::delete(spaces_table::table.find(&space_id)) - .execute(connection.db()) - .unwrap(); + update(&mut connection, &id, &retitle, t1()).unwrap(); - assert!(list(&mut connection).unwrap().is_empty()); + assert_eq!(column(&mut connection, "language"), "brainfuck"); +} + +#[test] +fn an_unreadable_date_fails_the_read_by_its_field() { + for (column, field) in [("created_at", "createdAt"), ("updated_at", "updatedAt")] { + let mut connection = open_in_memory().unwrap(); + let id = note(&mut connection); + set_column(&mut connection, column, "yesterday"); + + assert!( + matches!( + get(&mut connection, &id), + Err(StorageError::CorruptRow { field: found, .. }) if found == field + ), + "{column}" + ); + } } #[test] -fn a_stored_date_that_is_out_of_format_is_reported_rather_than_guessed() { +fn an_unreadable_deadline_fails_the_read_by_its_field() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let created = create(&mut connection, draft(&space_id), t0()).unwrap(); + let space_id = space(&mut connection, "Work"); + let expiring = NoteDraft { + lifecycle: NoteLifecycle::Expires { at: t1() }, + ..draft(&space_id) + }; + let id = create(&mut connection, expiring, t0()).unwrap().id; + set_column(&mut connection, "lifecycle_expires_at", "soon"); - diesel::update(engine::db::schema::notes::table.find(&created.id)) - .set(engine::db::schema::notes::created_at.eq("pas une date")) - .execute(connection.db()) - .unwrap(); + assert!(matches!( + get(&mut connection, &id), + Err(StorageError::CorruptRow { + field: "lifecycleExpiresAt", + .. + }) + )); +} - let error = list(&mut connection).unwrap_err(); +/// A wrong key must stop the read, never hand back plausible emptiness. +#[test] +fn a_value_that_will_not_open_stops_the_read() { + let mut connection = open_in_memory().unwrap(); + let id = note(&mut connection); + set_column(&mut connection, "title", "bm90IHNlYWxlZA=="); assert!(matches!( - error, - StorageError::CorruptRow { - field: "createdAt", - .. - } + get(&mut connection, &id), + Err(StorageError::Vault(_)) )); + assert!(matches!(list(&mut connection), Err(StorageError::Vault(_)))); } #[test] fn a_stored_date_always_carries_its_milliseconds() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let round_second = at("2026-07-25T09:00:00Z"); + let space_id = space(&mut connection, "Work"); - let created = create(&mut connection, draft(&space_id), round_second).unwrap(); + create( + &mut connection, + draft(&space_id), + at("2026-07-25T09:00:00Z"), + ) + .unwrap(); - let stored: String = engine::db::schema::notes::table - .find(&created.id) - .select(engine::db::schema::notes::updated_at) - .first(connection.db()) + assert_eq!( + column(&mut connection, "updated_at"), + "2026-07-25T09:00:00.000Z" + ); +} + +#[test] +fn deleting_a_space_takes_its_notes_with_it() { + let mut connection = open_in_memory().unwrap(); + let space_id = space(&mut connection, "Work"); + create(&mut connection, draft(&space_id), t0()).unwrap(); + + diesel::delete(engine::db::schema::spaces::table.find(&space_id)) + .execute(connection.db()) .unwrap(); - assert_eq!(stored, "2026-07-25T09:00:00.000Z"); + assert!(list(&mut connection).unwrap().is_empty()); } /// The point of the whole thing, and the only test that reads the file rather than the diff --git a/crates/engine/tests/notes/writes.rs b/crates/engine/tests/notes/writes.rs index 71eaa1781..8774047de 100644 --- a/crates/engine/tests/notes/writes.rs +++ b/crates/engine/tests/notes/writes.rs @@ -1,402 +1,238 @@ use super::*; -#[test] -fn a_created_note_is_read_back_whole() { - let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - - let created = create(&mut connection, draft(&space_id), t0()).unwrap(); - let listed = list(&mut connection).unwrap(); - - assert_eq!(listed.len(), 1); - let note = &listed[0]; - assert_eq!(note.id, created.id); - assert_eq!(note.space_id, space_id); - assert_eq!(note.title, "Titre"); - assert_eq!(note.content, "Contenu"); - assert_eq!(note.source, "API Gateway / Auth"); - assert!(!note.pinned); - assert_eq!(note.tags, ["api", "auth"]); +fn retitled(title: &str) -> NotePatch { + NotePatch { + title: Some(title.to_string()), + ..NotePatch::default() + } } #[test] -fn creation_stamps_both_dates_identically() { +fn a_created_note_reads_back_as_it_was_written() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); + let space_id = space(&mut connection, "Work"); let created = create(&mut connection, draft(&space_id), t0()).unwrap(); - assert_eq!(created.created_at, t0()); - assert_eq!(created.updated_at, t0()); + assert_eq!(get(&mut connection, &created.id).unwrap(), created); + assert_eq!((created.created_at, created.updated_at), (t0(), t0())); + assert_eq!(created.source, "API Gateway / Auth"); } #[test] -fn an_expiring_lifecycle_survives_a_round_trip() { +fn each_note_is_given_an_id_of_its_own() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let expiring = NoteDraft { - lifecycle: NoteLifecycle::Expires { - at: at("2026-08-01T00:00:00.000Z"), - }, - ..draft(&space_id) - }; + let space_id = space(&mut connection, "Work"); - create(&mut connection, expiring, t0()).unwrap(); + let first = create(&mut connection, draft(&space_id), t0()).unwrap(); + let second = create(&mut connection, draft(&space_id), t0()).unwrap(); - let deadline = at("2026-08-01T00:00:00.000Z"); - let listed = list(&mut connection).unwrap(); - assert!(matches!( - &listed[0].lifecycle, - NoteLifecycle::Expires { at } if *at == deadline - )); + assert_ne!(first.id, second.id); } #[test] -fn dropping_an_expiry_clears_the_stored_date() { +fn a_note_is_created_only_in_a_space_that_exists() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let expiring = NoteDraft { - lifecycle: NoteLifecycle::Expires { - at: at("2026-08-01T00:00:00.000Z"), - }, - ..draft(&space_id) - }; - let created = create(&mut connection, expiring, t0()).unwrap(); - - let patch = NotePatch { - lifecycle: Some(NoteLifecycle::Permanent), - ..NotePatch::default() - }; - update(&mut connection, &created.id, &patch, t1()).unwrap(); assert!(matches!( - list(&mut connection).unwrap()[0].lifecycle, - NoteLifecycle::Permanent + create(&mut connection, draft("nowhere"), t0()), + Err(StorageError::SpaceNotFound(space)) if space == "nowhere" )); + assert!(list(&mut connection).unwrap().is_empty()); } -/// A newer build writes a language this one cannot name, and this one reads it as the -/// fallback: an edit must not write that fallback back. #[test] -fn an_edit_keeps_a_language_this_build_cannot_read() { +fn a_note_s_tags_read_back_in_the_column_s_order_folding_ascii_case() { let mut connection = open_in_memory().unwrap(); - let space = spaces::create(&mut connection, "Perso").unwrap().id; - let created = create(&mut connection, draft(&space), t0()).unwrap(); - - // Written the way a newer build would have written it. - diesel::update(notes_table::table.find(&created.id)) - .set(notes_table::language.eq("rust")) - .execute(connection.db()) - .unwrap(); + let space_id = space(&mut connection, "Work"); - // The read degrades, which is deliberate and unchanged. - assert_eq!(list(&mut connection).unwrap()[0].language, Language::Txt); + let created = create(&mut connection, tagged(&space_id, &["b", "A", "c"]), t0()).unwrap(); - let patch = NotePatch { - title: Some("Nouveau titre".to_string()), - ..NotePatch::default() - }; - update(&mut connection, &created.id, &patch, t1()).unwrap(); - - let stored: String = notes_table::table - .find(&created.id) - .select(notes_table::language) - .first(connection.db()) - .unwrap(); + assert_eq!(created.tags, ["A", "b", "c"]); assert_eq!( - stored, "rust", - "the edit overwrote a language it could not read" + get(&mut connection, &created.id).unwrap().tags, + ["A", "b", "c"] ); } -/// A column the patch never named is left alone, which is what the guarantee above -/// rests on — and it costs nine columns less per title change. #[test] -fn an_edit_writes_only_what_it_moved() { +fn an_edit_writes_what_it_carries_and_dates_the_note() { let mut connection = open_in_memory().unwrap(); - let space = spaces::create(&mut connection, "Perso").unwrap().id; - let created = create(&mut connection, draft(&space), t0()).unwrap(); - - // A value no patch will touch, and that this build would happily rewrite. - diesel::update(notes_table::table.find(&created.id)) - .set(notes_table::kind.eq("runbook")) - .execute(connection.db()) - .unwrap(); - + let space_id = space(&mut connection, "Work"); + let id = create(&mut connection, draft(&space_id), t0()).unwrap().id; let patch = NotePatch { + title: Some("Renamed".to_string()), + content: Some("Body".to_string()), + source: Some("Elsewhere".to_string()), pinned: Some(true), + tags: Some(vec!["ops".to_string()]), + lifecycle: Some(NoteLifecycle::Expires { at: t1() }), ..NotePatch::default() }; - update(&mut connection, &created.id, &patch, t1()).unwrap(); - - let (kind, pinned): (String, bool) = notes_table::table - .find(&created.id) - .select((notes_table::kind, notes_table::pinned)) - .first(connection.db()) - .unwrap(); - assert_eq!(kind, "runbook"); - assert!(pinned); -} - -#[test] -fn creating_in_an_unknown_space_is_refused() { - let mut connection = open_in_memory().unwrap(); - - let error = create(&mut connection, draft("unknown"), t0()).unwrap_err(); - assert!(matches!(error, StorageError::SpaceNotFound(_))); - assert!(list(&mut connection).unwrap().is_empty()); -} + let edited = update(&mut connection, &id, &patch, t1()).unwrap(); -#[test] -fn notes_are_listed_most_recently_updated_first() { - let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - - let older = create(&mut connection, draft(&space_id), t0()).unwrap(); - let newer = create(&mut connection, draft(&space_id), t1()).unwrap(); - - let ids: Vec = list(&mut connection) - .unwrap() - .into_iter() - .map(|n| n.id) - .collect(); - - assert_eq!(ids, [newer.id, older.id]); + let read = get(&mut connection, &id).unwrap(); + assert_eq!(read, edited); + assert_eq!( + ( + read.title.as_str(), + read.content.as_str(), + read.source.as_str() + ), + ("Renamed", "Body", "Elsewhere") + ); + assert!(read.pinned); + assert_eq!(read.tags, ["ops"]); + assert_eq!(read.lifecycle, NoteLifecycle::Expires { at: t1() }); + assert_eq!((read.created_at, read.updated_at), (t0(), t1())); } #[test] -fn an_absent_patch_field_leaves_the_stored_value_untouched() { +fn an_edit_that_changes_nothing_leaves_the_date() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); + let space_id = space(&mut connection, "Work"); let created = create(&mut connection, draft(&space_id), t0()).unwrap(); - let patch = NotePatch { - title: Some("Nouveau titre".to_string()), - ..NotePatch::default() - }; - let updated = update(&mut connection, &created.id, &patch, t1()).unwrap(); + update( + &mut connection, + &created.id, + &retitled(&created.title), + t1(), + ) + .unwrap(); - assert_eq!(updated.title, "Nouveau titre"); - assert_eq!(updated.content, "Contenu"); - assert_eq!(updated.source, "API Gateway / Auth"); - assert_eq!(updated.tags, ["api", "auth"]); - assert!(matches!(updated.lifecycle, NoteLifecycle::Permanent)); + assert_eq!(get(&mut connection, &created.id).unwrap().updated_at, t0()); } #[test] -fn updating_refreshes_updated_at_but_not_created_at() { +fn a_deadline_taken_away_makes_the_note_permanent_again() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let created = create(&mut connection, draft(&space_id), t0()).unwrap(); - - let patch = NotePatch { - title: Some("Renamed".to_string()), - ..NotePatch::default() + let space_id = space(&mut connection, "Work"); + let expiring = NoteDraft { + lifecycle: NoteLifecycle::Expires { at: t1() }, + ..draft(&space_id) }; - let updated = update(&mut connection, &created.id, &patch, t1()).unwrap(); - - assert_eq!(updated.created_at, t0()); - assert_eq!(updated.updated_at, t1()); -} - -#[test] -fn updating_with_what_the_note_already_holds_leaves_updated_at_alone() { - let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let created = create(&mut connection, draft(&space_id), t0()).unwrap(); - let patch = NotePatch { - title: Some(created.title.clone()), - content: Some(created.content.clone()), + let id = create(&mut connection, expiring, t0()).unwrap().id; + let permanent = NotePatch { + lifecycle: Some(NoteLifecycle::Permanent), ..NotePatch::default() }; - let updated = update(&mut connection, &created.id, &patch, t1()).unwrap(); + update(&mut connection, &id, &permanent, t1()).unwrap(); - assert_eq!(updated.updated_at, t0()); - assert_eq!(get(&mut connection, &created.id).unwrap().updated_at, t0()); + assert_eq!( + get(&mut connection, &id).unwrap().lifecycle, + NoteLifecycle::Permanent + ); } #[test] -fn typing_into_a_freshly_created_note_keeps_it_prose() { +fn editing_a_note_that_is_not_there_fails_by_name() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let empty = NoteDraft { - kind: NoteKind::Note, - language: Language::Txt, - content: String::new(), - ..draft(&space_id) - }; - let created = create(&mut connection, empty, t0()).unwrap(); - - let patch = NotePatch { - content: Some("## Standup\n\ninterface Note { id: string } is the model".to_string()), - ..NotePatch::default() - }; - let updated = update(&mut connection, &created.id, &patch, t1()).unwrap(); - assert_eq!(updated.kind, NoteKind::Note); - assert_eq!(updated.language, Language::Txt); + assert!(matches!( + update(&mut connection, "missing", &retitled("x"), t1()), + Err(StorageError::NoteNotFound(id)) if id == "missing" + )); } -/// The title was typed first, so creation saw no body: the first one is read when it comes. #[test] -fn a_freshly_created_snippet_takes_the_language_of_its_first_content() { +fn a_move_to_a_space_that_does_not_exist_fails_and_changes_nothing() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let empty = NoteDraft { - language: Language::Txt, - content: String::new(), - ..draft(&space_id) - }; - let created = create(&mut connection, empty, t0()).unwrap(); - + let space_id = space(&mut connection, "Work"); + let id = create(&mut connection, draft(&space_id), t0()).unwrap().id; let patch = NotePatch { - content: Some("SELECT id FROM notes WHERE pinned = 1;".to_string()), + space_id: Some("nowhere".to_string()), + title: Some("Renamed".to_string()), ..NotePatch::default() }; - let updated = update(&mut connection, &created.id, &patch, t1()).unwrap(); - assert_eq!(updated.language, Language::Sql); + assert!(matches!( + update(&mut connection, &id, &patch, t1()), + Err(StorageError::SpaceNotFound(space)) if space == "nowhere" + )); + let read = get(&mut connection, &id).unwrap(); + assert_eq!( + (read.space_id.as_str(), read.title.as_str()), + (space_id.as_str(), "Titre") + ); } -/// A paste of code is detected by the front end, through `detect_language`, before it writes. #[test] -fn a_detected_paste_lands_with_its_language() { +fn a_move_to_another_space_leaves_its_folder_behind() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let empty = NoteDraft { - language: Language::Txt, - content: String::new(), + let space_id = space(&mut connection, "Work"); + let other = space(&mut connection, "Home"); + let folder = engine::folders::store::create(&mut connection, &space_id, None, "Infra", t0()) + .unwrap() + .id; + let filed = NoteDraft { + folder_id: Some(folder), ..draft(&space_id) }; - let created = create(&mut connection, empty, t0()).unwrap(); - - let patch = NotePatch { - content: Some("interface Note { id: string }".to_string()), - language: Some(Language::Ts), + let id = create(&mut connection, filed, t0()).unwrap().id; + let moving = NotePatch { + space_id: Some(other.clone()), ..NotePatch::default() }; - let updated = update(&mut connection, &created.id, &patch, t1()).unwrap(); - assert_eq!(updated.language, Language::Ts); - assert_eq!(list(&mut connection).unwrap()[0].language, Language::Ts); + update(&mut connection, &id, &moving, t1()).unwrap(); + + let read = get(&mut connection, &id).unwrap(); + assert_eq!(read.space_id, other); + assert_eq!(read.folder_id, None); } #[test] -fn a_later_edit_does_not_move_the_language_again() { +fn the_first_body_of_an_empty_plain_snippet_is_read_for_its_language() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); + let space_id = space(&mut connection, "Work"); let empty = NoteDraft { - language: Language::Txt, content: String::new(), ..draft(&space_id) }; - let created = create(&mut connection, empty, t0()).unwrap(); - - let first = NotePatch { - content: Some("SELECT 1".to_string()), - language: Some(Language::Sql), + let id = create(&mut connection, empty, t0()).unwrap().id; + let body = NotePatch { + content: Some("#!/usr/bin/env python\nprint(1)".to_string()), ..NotePatch::default() }; - update(&mut connection, &created.id, &first, t1()).unwrap(); - let second = NotePatch { - content: Some("interface Note { id: string }".to_string()), - ..NotePatch::default() - }; - let updated = update(&mut connection, &created.id, &second, t1()).unwrap(); + update(&mut connection, &id, &body, t1()).unwrap(); - assert_eq!(updated.language, Language::Sql); + assert_eq!(get(&mut connection, &id).unwrap().language, Language::Py); } #[test] -fn patching_tags_replaces_the_whole_set() { +fn a_trashed_or_missing_note_cannot_be_read() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let created = create(&mut connection, draft(&space_id), t0()).unwrap(); + let space_id = space(&mut connection, "Work"); + let id = create(&mut connection, draft(&space_id), t0()).unwrap().id; + trash(&mut connection, &id, t1()).unwrap(); - let patch = NotePatch { - tags: Some(vec!["sql".to_string()]), - ..NotePatch::default() - }; - update(&mut connection, &created.id, &patch, t1()).unwrap(); - - assert_eq!(list(&mut connection).unwrap()[0].tags, ["sql"]); + for wanted in [id.as_str(), "missing"] { + assert!(matches!( + get(&mut connection, wanted), + Err(StorageError::NoteNotFound(found)) if found == wanted + )); + } } #[test] -fn mixed_case_tags_come_back_in_the_same_order_a_reload_gives() { +fn a_kind_written_by_an_edit_reads_back() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let created = create(&mut connection, draft(&space_id), t0()).unwrap(); - - let patch = NotePatch { - tags: Some(vec!["Urgent".to_string(), "auth".to_string()]), - ..NotePatch::default() - }; - let updated = update(&mut connection, &created.id, &patch, t1()).unwrap(); - - assert_eq!(updated.tags, ["auth", "Urgent"]); - assert_eq!(list(&mut connection).unwrap()[0].tags, updated.tags); -} - -#[test] -fn patching_tags_to_an_empty_list_clears_them() { - let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let created = create(&mut connection, draft(&space_id), t0()).unwrap(); - - let patch = NotePatch { - tags: Some(Vec::new()), - ..NotePatch::default() - }; - let updated = update(&mut connection, &created.id, &patch, t1()).unwrap(); - - assert!(updated.tags.is_empty()); - assert!(list(&mut connection).unwrap()[0].tags.is_empty()); -} - -#[test] -fn a_note_can_be_moved_to_another_space() { - let mut connection = open_in_memory().unwrap(); - let origin = space(&mut connection, "Personal"); - let destination = space(&mut connection, "Boulot"); - let created = create(&mut connection, draft(&origin), t0()).unwrap(); - - let patch = NotePatch { - space_id: Some(destination.clone()), - ..NotePatch::default() - }; - let updated = update(&mut connection, &created.id, &patch, t1()).unwrap(); - - assert_eq!(updated.space_id, destination); -} - -#[test] -fn moving_a_note_to_an_unknown_space_is_refused_and_changes_nothing() { - let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let created = create(&mut connection, draft(&space_id), t0()).unwrap(); - - let patch = NotePatch { - space_id: Some("unknown".to_string()), - title: Some("Ne doit pas passer".to_string()), + let space_id = space(&mut connection, "Work"); + let id = create(&mut connection, written_in(&space_id, Language::Sh), t0()) + .unwrap() + .id; + let calc = NotePatch { + kind: Some(NoteKind::Calc), + content: Some("2 + 2".to_string()), ..NotePatch::default() }; - let error = update(&mut connection, &created.id, &patch, t1()).unwrap_err(); - - assert!(matches!(error, StorageError::SpaceNotFound(_))); - let note = &list(&mut connection).unwrap()[0]; - assert_eq!(note.space_id, space_id); - assert_eq!(note.title, "Titre"); -} - -#[test] -fn updating_an_unknown_note_reports_an_error() { - let mut connection = open_in_memory().unwrap(); - let error = update(&mut connection, "unknown", &NotePatch::default(), t1()).unwrap_err(); + update(&mut connection, &id, &calc, t1()).unwrap(); - assert!(matches!(error, StorageError::NoteNotFound(_))); + let read = get(&mut connection, &id).unwrap(); + assert_eq!((read.kind, read.language), (NoteKind::Calc, Language::Txt)); } From ee785ebf6cd00484237d6b5b29386612ff95ef3c Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:24:26 +0100 Subject: [PATCH 13/95] Note copies: unit tests rewritten for duplicates, pictures and imports (#1736) Duplicating with attachments and pictures, a drawing's pictures, the first launch's samples, an export and an import. --- crates/engine/src/notes/duplicate.rs | 237 +++++++++--------- crates/engine/src/notes/store/pictures.rs | 284 ++++++++++++---------- crates/engine/tests/notes/exchange.rs | 132 ++++++---- crates/engine/tests/notes/seeding.rs | 238 ++++++------------ 4 files changed, 439 insertions(+), 452 deletions(-) diff --git a/crates/engine/src/notes/duplicate.rs b/crates/engine/src/notes/duplicate.rs index 501ae1de0..f0ec6463c 100644 --- a/crates/engine/src/notes/duplicate.rs +++ b/crates/engine/src/notes/duplicate.rs @@ -54,166 +54,177 @@ pub(crate) fn duplicate( #[cfg(test)] mod tests { - use std::collections::BTreeMap; - use super::*; - use crate::notes::checklist::ChecklistItem; + use crate::db::open_in_memory; + use crate::notes::drawing::Pictures; use crate::notes::fixtures::{NOW, at, note}; use crate::notes::kind::NoteKind; - use crate::notes::priority::Priority; + use crate::notes::store::pictures::{self, Which}; + + struct Shelf { + _scratch: tempfile::TempDir, + library: Library, + original: Note, + } - fn library_with(original: impl FnOnce(String) -> Note) -> (tempfile::TempDir, Library, Note) { + /// A pinned note filed with a field value, and a library that writes its files to disk. + fn shelf(kind: NoteKind) -> Shelf { let scratch = tempfile::tempdir().unwrap(); - let mut library = crate::db::open_in_memory() + let mut library = open_in_memory() .unwrap() .with_directory(scratch.path().to_path_buf()); - let space_id = crate::spaces::store::create(&mut library, "Perso") + let space_id = crate::spaces::store::create(&mut library, "Work") .unwrap() .id; - let original = original(space_id); + let original = Note { + space_id, + kind, + pinned: true, + content: "psql -h {{host}}".into(), + placeholder_values: [("host".to_string(), "db".to_string())].into(), + ..note() + }; store::insert_imported(&mut library, &original).unwrap(); - - (scratch, library, original) + Shelf { + _scratch: scratch, + library, + original, + } } - fn attach(library: &mut Library, note_id: &str, id: &str) -> Attachment { + fn attach(shelf: &mut Shelf, id: &str, with_file: bool) -> Attachment { let attachment = Attachment { - id: id.to_string(), - note_id: note_id.to_string(), - file_name: "capture.png".to_string(), - mime_type: "image/png".to_string(), - byte_size: 4, + id: id.into(), + note_id: shelf.original.id.clone(), + file_name: format!("{id}.txt"), + mime_type: "text/plain".into(), + byte_size: 5, created_at: at(NOW), }; - let directory = attachments::files::directory(library); + let directory = attachments::files::directory(&shelf.library); std::fs::create_dir_all(&directory).unwrap(); - attachments::sealed::write_sealed( - library.vault(), - &directory.join(attachment.stored_name()), - b"\x89PNG", - ) - .unwrap(); - let (db, vault) = library.split(); + if with_file { + std::fs::write(directory.join(attachment.stored_name()), id.as_bytes()).unwrap(); + } + let (db, vault) = shelf.library.split(); attachments::store::create(db, vault, &attachment).unwrap(); - attachment } - #[test] - fn the_copy_says_what_the_note_says_under_its_own_id_and_title() { - let (_scratch, mut library, original) = library_with(|space_id| Note { - space_id, - pinned: true, - content: "ssh {{user}}@{{host}}".to_string(), - source: "OpenSSH".to_string(), - placeholder_values: BTreeMap::from([("user".to_string(), "deploy".to_string())]), - priority: Priority::High, - ..note() - }); - let later = at("2026-07-26T09:00:00.000Z"); - - let copy = duplicate( - &mut library, - &original.id, - "Title (copy)".to_string(), - later, - ) - .unwrap(); - - let read = store::get(&mut library, ©.id).unwrap(); - assert_ne!(read.id, original.id); - assert_eq!(read.title, "Title (copy)"); - assert_eq!(read.content, original.content); - assert_eq!(read.source, original.source); - assert_eq!(read.tags, original.tags); - assert_eq!(read.placeholder_values, original.placeholder_values); - assert_eq!(read.priority, Priority::High); - assert_eq!(read.space_id, original.space_id); - assert!(!read.pinned, "a copy is not pinned"); - assert_eq!((read.created_at, read.updated_at), (later, later)); - assert_eq!( - store::get(&mut library, &original.id).unwrap().title, - original.title - ); + fn later() -> DateTime { + at("2026-07-26T10:00:00.000Z") } #[test] - fn a_todo_list_keeps_its_items() { - let (_scratch, mut library, original) = library_with(|space_id| Note { - space_id, - kind: NoteKind::Checklist, - content: String::new(), - items: vec![ - ChecklistItem { - text: "Tag".to_string(), - done: true, - }, - ChecklistItem { - text: "Publish".to_string(), - done: false, - }, - ], - ..note() - }); + fn a_copy_says_what_the_note_says_under_a_new_id_and_title_unpinned_and_dated_now() { + let mut shelf = shelf(NoteKind::Snippet); - let copy = duplicate(&mut library, &original.id, "Copy".to_string(), at(NOW)).unwrap(); + let copy = duplicate(&mut shelf.library, "n-1", "Copy".into(), later()).unwrap(); + assert_ne!(copy.id, shelf.original.id); + assert_eq!(store::get(&mut shelf.library, ©.id).unwrap(), copy); + assert_eq!( + copy, + Note { + id: copy.id.clone(), + title: "Copy".into(), + pinned: false, + created_at: later(), + updated_at: later(), + ..shelf.original.clone() + } + ); assert_eq!( - store::get(&mut library, ©.id).unwrap().items, - original.items + store::get(&mut shelf.library, "n-1").unwrap(), + shelf.original ); } #[test] - fn the_attachments_are_copied_under_new_ids_and_still_open() { - let (_scratch, mut library, original) = - library_with(|space_id| Note { space_id, ..note() }); - let attachment = attach(&mut library, &original.id, "a-1"); + fn a_copy_carries_each_attachment_with_its_own_file() { + let mut shelf = shelf(NoteKind::Snippet); + attach(&mut shelf, "a-1", true); - let copy = duplicate(&mut library, &original.id, "Copy".to_string(), at(NOW)).unwrap(); + let copy = duplicate(&mut shelf.library, "n-1", "Copy".into(), later()).unwrap(); - let carried = attachments::store::list(&mut library, ©.id).unwrap(); + let carried = attachments::store::list(&mut shelf.library, ©.id).unwrap(); assert_eq!(carried.len(), 1); - assert_ne!(carried[0].id, attachment.id); - assert_eq!(carried[0].file_name, attachment.file_name); - let sealed = - std::fs::read(attachments::files::directory(&library).join(carried[0].stored_name())) - .unwrap(); - assert_eq!(library.vault().open_bytes(&sealed).unwrap(), b"\x89PNG"); + assert_ne!(carried[0].id, "a-1"); + assert_eq!(carried[0].file_name, "a-1.txt"); + let directory = attachments::files::directory(&shelf.library); assert_eq!( - attachments::store::list(&mut library, &original.id) + std::fs::read(directory.join(carried[0].stored_name())).unwrap(), + b"a-1" + ); + assert_eq!( + attachments::store::list(&mut shelf.library, "n-1") .unwrap() .len(), 1 ); } + /// As an export leaves it: the original has no bytes to give either. #[test] - fn an_attachment_whose_file_went_missing_stays_behind() { - let (_scratch, mut library, original) = - library_with(|space_id| Note { space_id, ..note() }); - let attachment = attach(&mut library, &original.id, "a-1"); - std::fs::remove_file( - attachments::files::directory(&library).join(attachment.stored_name()), - ) - .unwrap(); - - let copy = duplicate(&mut library, &original.id, "Copy".to_string(), at(NOW)).unwrap(); - - assert!( - attachments::store::list(&mut library, ©.id) - .unwrap() - .is_empty() + fn an_attachment_whose_file_is_gone_is_left_behind() { + let mut shelf = shelf(NoteKind::Snippet); + attach(&mut shelf, "a-1", false); + attach(&mut shelf, "a-2", true); + + let copy = duplicate(&mut shelf.library, "n-1", "Copy".into(), later()).unwrap(); + + let carried = attachments::store::list(&mut shelf.library, ©.id).unwrap(); + let names: Vec<_> = carried.iter().map(|each| each.file_name.as_str()).collect(); + assert_eq!(names, ["a-2.txt"]); + } + + #[test] + fn a_copy_of_a_drawing_carries_its_pictures() { + let mut shelf = shelf(NoteKind::Drawing); + let taken = Pictures { + thumbnail: b"small".to_vec(), + picture: b"large".to_vec(), + }; + let (db, vault) = shelf.library.split(); + pictures::save(db, vault, "n-1", &taken).unwrap(); + + let copy = duplicate(&mut shelf.library, "n-1", "Copy".into(), later()).unwrap(); + + let (db, vault) = shelf.library.split(); + assert_eq!( + pictures::read(db, vault, ©.id, Which::Picture).unwrap(), + pictures::read(db, vault, "n-1", Which::Picture).unwrap() ); } #[test] - fn an_unknown_note_is_refused() { - let (_scratch, mut library, _) = library_with(|space_id| Note { space_id, ..note() }); + fn copying_a_note_that_is_not_there_fails_by_name() { + let mut shelf = shelf(NoteKind::Snippet); assert!(matches!( - duplicate(&mut library, "missing", "Copy".to_string(), at(NOW)), - Err(StorageError::NoteNotFound(_)) + duplicate(&mut shelf.library, "missing", "Copy".into(), later()), + Err(StorageError::NoteNotFound(id)) if id == "missing" )); } + + #[test] + fn a_copy_of_a_todo_list_keeps_its_items() { + let mut shelf = shelf(NoteKind::Checklist); + let items = vec![crate::notes::checklist::ChecklistItem { + text: "Publish".into(), + done: true, + }]; + let patch = crate::notes::model::NotePatch { + items: Some(items.clone()), + ..crate::notes::model::NotePatch::default() + }; + store::update(&mut shelf.library, "n-1", &patch, later()).unwrap(); + + let copy = duplicate(&mut shelf.library, "n-1", "Copy".into(), later()).unwrap(); + + assert_eq!( + store::get(&mut shelf.library, ©.id).unwrap().items, + items + ); + } } diff --git a/crates/engine/src/notes/store/pictures.rs b/crates/engine/src/notes/store/pictures.rs index 9bfefda2c..5470f0bfc 100644 --- a/crates/engine/src/notes/store/pictures.rs +++ b/crates/engine/src/notes/store/pictures.rs @@ -116,196 +116,214 @@ pub fn copy(connection: &mut SqliteConnection, from: &str, to: &str) -> Result<( #[cfg(test)] mod tests { use super::*; - use crate::db::Library; - use crate::notes::drawing::DrawingPictures; + use crate::db::{Library, open_in_memory}; use crate::notes::fixtures::{NOW, at, note}; - use crate::notes::kind::NoteKind; - use crate::notes::model::{Note, NotePatch}; + use crate::notes::model::Note; use crate::notes::store; - const SCENE: &str = r#"{"version":1,"scene":{"objects":[]}}"#; - - fn png(tag: u8) -> String { - uri_of(&[0x89, b'P', b'N', b'G', b'\r', b'\n', 0x1a, b'\n', tag]) - } - - fn library_with(kind: NoteKind) -> (Library, Note) { - let mut library = crate::db::open_in_memory().unwrap(); - let space_id = crate::spaces::store::create(&mut library, "Perso") + fn shelf() -> (Library, String) { + let mut library = open_in_memory().unwrap(); + let space = crate::spaces::store::create(&mut library, "Work") .unwrap() .id; - let drawing = Note { - space_id, - kind, - content: SCENE.to_string(), + (library, space) + } + + fn drawing(library: &mut Library, space: &str, id: &str, title: &str) { + let drawn = Note { + id: id.into(), + space_id: space.into(), + title: title.into(), + kind: NoteKind::Drawing, ..note() }; - store::insert_imported(&mut library, &drawing).unwrap(); - (library, drawing) + store::insert_imported(library, &drawn).unwrap(); } - fn save(library: &mut Library, id: &str, thumbnail: u8, picture: u8) { - let sent = DrawingPictures { - thumbnail: png(thumbnail), - picture: png(picture), - }; - let patch = NotePatch { - content: Some(SCENE.to_string()), - pictures: Some(sent.clone()), - ..NotePatch::default() - }; - store::update_drawn( - library, - id, - &patch, - Some(sent.decoded().unwrap().as_ref()), - at(NOW), - ) - .unwrap(); + fn taken(thumbnail: &[u8], picture: &[u8]) -> Pictures { + Pictures { + thumbnail: thumbnail.to_vec(), + picture: picture.to_vec(), + } } - fn shown(library: &mut Library, id: &str, which: Which) -> Option { - let (connection, vault) = library.split(); - read(connection, vault, id, which).unwrap() + fn shown(library: &mut Library, id: &str) -> (Option, Option) { + let (db, vault) = library.split(); + ( + read(db, vault, id, Which::Thumbnail).unwrap(), + read(db, vault, id, Which::Picture).unwrap(), + ) } #[test] - fn a_drawing_saved_gives_each_picture_alone_and_the_last_taken() { - let (mut library, drawing) = library_with(NoteKind::Drawing); - assert_eq!(shown(&mut library, &drawing.id, Which::Thumbnail), None); + fn a_drawing_s_pictures_read_back_each_as_a_data_uri() { + let (mut library, space) = shelf(); + drawing(&mut library, &space, "d-1", "Plan"); + let (db, vault) = library.split(); - save(&mut library, &drawing.id, 1, 2); - save(&mut library, &drawing.id, 3, 4); + save(db, vault, "d-1", &taken(b"small", b"large")).unwrap(); assert_eq!( - shown(&mut library, &drawing.id, Which::Thumbnail), - Some(png(3)) - ); - assert_eq!( - shown(&mut library, &drawing.id, Which::Picture), - Some(png(4)) + shown(&mut library, "d-1"), + (Some(uri_of(b"small")), Some(uri_of(b"large"))) ); } - /// Sealed like a body: what the file holds is no PNG. #[test] - fn the_pictures_are_sealed_in_the_file() { - let (mut library, drawing) = library_with(NoteKind::Drawing); - save(&mut library, &drawing.id, 1, 2); + fn pictures_saved_again_replace_the_ones_before() { + let (mut library, space) = shelf(); + drawing(&mut library, &space, "d-1", "Plan"); + let (db, vault) = library.split(); + save(db, vault, "d-1", &taken(b"old", b"old")).unwrap(); + + save(db, vault, "d-1", &taken(b"new", b"newer")).unwrap(); + + assert_eq!(shown(&mut library, "d-1").1, Some(uri_of(b"newer"))); + } + + #[test] + fn a_drawing_without_pictures_a_trashed_one_or_none_at_all_shows_nothing() { + let (mut library, space) = shelf(); + drawing(&mut library, &space, "bare", "Bare"); + drawing(&mut library, &space, "trashed", "Trashed"); + let (db, vault) = library.split(); + save(db, vault, "trashed", &taken(b"a", b"b")).unwrap(); + store::trash::trash(&mut library, "trashed", at(NOW)).unwrap(); + drawing(&mut library, &space, "removed", "Removed"); + let (db, vault) = library.split(); + save(db, vault, "removed", &taken(b"a", b"b")).unwrap(); + remove(db, "removed").unwrap(); + + for id in ["bare", "trashed", "removed", "missing"] { + assert_eq!(shown(&mut library, id), (None, None), "{id}"); + } + } + + #[test] + fn a_picture_is_sealed_in_its_column() { + let (mut library, space) = shelf(); + drawing(&mut library, &space, "d-1", "Plan"); + let (db, vault) = library.split(); + save(db, vault, "d-1", &taken(b"secret-small", b"secret-large")).unwrap(); - let (connection, _) = library.split(); let stored: Vec = drawing_pictures::table - .select(drawing_pictures::thumbnail) - .first(connection) + .select(drawing_pictures::picture) + .first(library.db()) .unwrap(); - assert!(!stored.windows(4).any(|bytes| bytes == b"PNG\r")); + + assert!(!stored.windows(6).any(|window| window == b"secret")); } - /// DES-15: an imported drawing is pictured at its first opening, and that is no edit. #[test] - fn the_pictures_of_a_drawing_left_as_it_was_leave_its_date_alone() { - let (mut library, drawing) = library_with(NoteKind::Drawing); - let sent = DrawingPictures { - thumbnail: png(1), - picture: png(2), - }; - let patch = NotePatch { - content: Some(SCENE.to_string()), - pictures: Some(sent.clone()), - ..NotePatch::default() + fn the_drawings_are_those_out_of_the_trash_by_their_title() { + let (mut library, space) = shelf(); + drawing(&mut library, &space, "d-1", "zèbre"); + drawing(&mut library, &space, "d-2", "Écran"); + drawing(&mut library, &space, "d-3", "gone"); + store::trash::trash(&mut library, "d-3", at(NOW)).unwrap(); + let snippet = Note { + id: "s-1".into(), + space_id: space.clone(), + title: "a snippet".into(), + ..note() }; + store::insert_imported(&mut library, &snippet).unwrap(); - let saved = store::update_drawn( - &mut library, - &drawing.id, - &patch, - Some(sent.decoded().unwrap().as_ref()), - at("2026-07-26T09:00:00.000Z"), - ) - .unwrap(); + let (db, vault) = library.split(); + let titles: Vec = drawings(db, vault) + .unwrap() + .into_iter() + .map(|drawing| drawing.title) + .collect(); - assert_eq!(saved.updated_at, drawing.updated_at); - assert_eq!( - shown(&mut library, &drawing.id, Which::Thumbnail), - Some(png(1)) - ); + assert_eq!(titles, ["Écran", "zèbre"]); } #[test] - fn a_drawing_emptied_has_no_picture_any_more() { - let (mut library, drawing) = library_with(NoteKind::Drawing); - save(&mut library, &drawing.id, 1, 2); - - let patch = NotePatch::default(); - store::update_drawn(&mut library, &drawing.id, &patch, Some(None), at(NOW)).unwrap(); + fn a_copy_takes_the_pictures_and_a_drawing_without_any_gives_none() { + let (mut library, space) = shelf(); + drawing(&mut library, &space, "d-1", "Plan"); + drawing(&mut library, &space, "d-2", "Copy"); + drawing(&mut library, &space, "d-3", "Bare"); + drawing(&mut library, &space, "d-4", "Copy of bare"); + let (db, vault) = library.split(); + save(db, vault, "d-1", &taken(b"small", b"large")).unwrap(); + + copy(db, "d-1", "d-2").unwrap(); + copy(db, "d-3", "d-4").unwrap(); + + assert_eq!(shown(&mut library, "d-2"), shown(&mut library, "d-1")); + assert_eq!(shown(&mut library, "d-4"), (None, None)); + } - assert_eq!(shown(&mut library, &drawing.id, Which::Thumbnail), None); + /// The drawing patched with `pictures` taken, or with none: emptied. + fn patched(library: &mut Library, id: &str, pictures: Option<&Pictures>) -> Note { + let patch = crate::notes::model::NotePatch::default(); + store::update_drawn( + library, + id, + &patch, + Some(pictures), + at("2026-07-26T09:00:00.000Z"), + ) + .unwrap() } + /// An imported drawing is pictured at its first opening, and that is no edit (DES-15). #[test] - fn the_drawings_a_note_can_embed_are_named_and_the_trashed_left_out() { - let (mut library, drawing) = library_with(NoteKind::Drawing); - let trashed = Note { - id: "trashed".to_string(), - space_id: drawing.space_id.clone(), - kind: NoteKind::Drawing, - ..note() - }; - store::insert_imported(&mut library, &trashed).unwrap(); - store::trash::trash(&mut library, "trashed", at(NOW)).unwrap(); + fn a_drawing_s_patch_writes_its_pictures_without_dating_it() { + let (mut library, space) = shelf(); + drawing(&mut library, &space, "d-1", "Plan"); - let (connection, vault) = library.split(); - let listed = drawings(connection, vault).unwrap(); + let saved = patched(&mut library, "d-1", Some(&taken(b"small", b"large"))); - assert_eq!( - listed, - [DrawingRef { - id: drawing.id.clone(), - title: drawing.title.clone() - }] - ); + assert_eq!(saved.updated_at, at(NOW)); + assert_eq!(shown(&mut library, "d-1").0, Some(uri_of(b"small"))); } #[test] - fn what_is_no_drawing_keeps_no_picture() { - let (mut library, snippet) = library_with(NoteKind::Snippet); + fn a_drawing_emptied_by_its_patch_has_no_picture_any_more() { + let (mut library, space) = shelf(); + drawing(&mut library, &space, "d-1", "Plan"); + patched(&mut library, "d-1", Some(&taken(b"small", b"large"))); - save(&mut library, &snippet.id, 1, 2); + patched(&mut library, "d-1", None); - assert_eq!(shown(&mut library, &snippet.id, Which::Picture), None); + assert_eq!(shown(&mut library, "d-1"), (None, None)); } #[test] - fn a_drawing_in_the_trash_shows_nothing_and_a_purge_takes_its_pictures() { - let (mut library, drawing) = library_with(NoteKind::Drawing); - save(&mut library, &drawing.id, 1, 2); + fn a_note_that_is_no_drawing_keeps_no_picture() { + let (mut library, space) = shelf(); + let snippet = Note { + id: "s-1".into(), + space_id: space, + ..note() + }; + store::insert_imported(&mut library, &snippet).unwrap(); - store::trash::trash(&mut library, &drawing.id, at(NOW)).unwrap(); - assert_eq!(shown(&mut library, &drawing.id, Which::Picture), None); + patched(&mut library, "s-1", Some(&taken(b"small", b"large"))); - store::trash::purge(&mut library, std::slice::from_ref(&drawing.id)).unwrap(); - let (connection, _) = library.split(); let left: i64 = drawing_pictures::table .count() - .get_result(connection) + .get_result(library.db()) .unwrap(); assert_eq!(left, 0); } #[test] - fn a_copy_takes_the_pictures_under_its_own_id() { - let (mut library, drawing) = library_with(NoteKind::Drawing); - save(&mut library, &drawing.id, 1, 2); + fn a_purge_takes_a_drawing_s_pictures_with_it() { + let (mut library, space) = shelf(); + drawing(&mut library, &space, "d-1", "Plan"); + patched(&mut library, "d-1", Some(&taken(b"small", b"large"))); + store::trash::trash(&mut library, "d-1", at(NOW)).unwrap(); - let twin = - crate::notes::duplicate::duplicate(&mut library, &drawing.id, "Copie".into(), at(NOW)) - .unwrap(); + store::trash::purge(&mut library, &["d-1".to_string()]).unwrap(); - assert_eq!( - shown(&mut library, &twin.id, Which::Thumbnail), - Some(png(1)) - ); - let (connection, _) = library.split(); - assert!(copy(connection, "nothing", "else").is_ok()); + let left: i64 = drawing_pictures::table + .count() + .get_result(library.db()) + .unwrap(); + assert_eq!(left, 0); } } diff --git a/crates/engine/tests/notes/exchange.rs b/crates/engine/tests/notes/exchange.rs index 45f91e2ef..65619ec3b 100644 --- a/crates/engine/tests/notes/exchange.rs +++ b/crates/engine/tests/notes/exchange.rs @@ -1,67 +1,115 @@ use super::*; +/// A note as an export file carries it: its own id and dates, its side tables. +fn exported(space_id: &str, id: &str, created: &str) -> Note { + Note { + id: id.to_string(), + space_id: space_id.to_string(), + folder_id: None, + title: id.to_string(), + language: Language::Sql, + content: "select {{n}}".to_string(), + source: "from a file".to_string(), + tags: vec!["imported".to_string()], + pinned: true, + created_at: at(created), + updated_at: at(created), + lifecycle: NoteLifecycle::Expires { at: t1() }, + kind: NoteKind::Snippet, + priority: Priority::High, + items: Vec::new(), + placeholder_values: values(&[("n", "1")]), + } +} + #[test] -fn an_export_reads_every_live_note_of_a_space() { +fn an_imported_note_is_written_as_it_came() { let mut connection = open_in_memory().unwrap(); - let personal = space(&mut connection, "Personal"); - let boulot = space(&mut connection, "Boulot"); - create(&mut connection, draft(&personal), t0()).unwrap(); - let elsewhere = create(&mut connection, draft(&boulot), t0()).unwrap(); - let thrown = create(&mut connection, draft(&personal), t0()).unwrap(); - trash(&mut connection, &thrown.id, t1()).unwrap(); + let space_id = space(&mut connection, "Work"); + let note = exported(&space_id, "n-1", "2020-01-01T00:00:00.000Z"); - let exported = all(&mut connection, Some(&personal)).unwrap(); + assert!(insert_imported(&mut connection, ¬e).unwrap()); - assert_eq!(exported.len(), 1); - assert_eq!(exported[0].tags, ["api", "auth"]); - assert_eq!(all(&mut connection, None).unwrap().len(), 2); - assert!( - all(&mut connection, None) - .unwrap() - .iter() - .any(|note| note.id == elsewhere.id) - ); + assert_eq!(get(&mut connection, "n-1").unwrap(), note); } #[test] -fn an_imported_note_keeps_its_identifier_and_its_dates() { +fn an_import_whose_id_is_taken_writes_nothing() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let mut note = create(&mut connection, draft(&space_id), t0()).unwrap(); - note.id = "imported".to_string(); + let space_id = space(&mut connection, "Work"); + let first = exported(&space_id, "n-1", "2020-01-01T00:00:00.000Z"); + insert_imported(&mut connection, &first).unwrap(); + let again = Note { + title: "other".to_string(), + ..first.clone() + }; - assert!(insert_imported(&mut connection, ¬e).unwrap()); + assert!(!insert_imported(&mut connection, &again).unwrap()); + assert_eq!(get(&mut connection, "n-1").unwrap(), first); +} - let found = all(&mut connection, None) - .unwrap() - .into_iter() - .find(|candidate| candidate.id == "imported") - .unwrap(); - assert_eq!(found.created_at, t0()); - assert_eq!(found.tags, ["api", "auth"]); +/// An id in the trash is taken too: the note there can still come back. +#[test] +fn an_import_whose_id_waits_in_the_trash_writes_nothing() { + let mut connection = open_in_memory().unwrap(); + let space_id = space(&mut connection, "Work"); + let first = exported(&space_id, "n-1", "2020-01-01T00:00:00.000Z"); + insert_imported(&mut connection, &first).unwrap(); + trash(&mut connection, "n-1", t1()).unwrap(); + + assert!(!insert_imported(&mut connection, &first).unwrap()); } #[test] -fn importing_the_same_note_twice_leaves_the_first_one_alone() { +fn an_export_takes_the_live_notes_oldest_first_of_a_space_or_all() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let mut note = create(&mut connection, draft(&space_id), t0()).unwrap(); - note.title = "Écrasé ?".to_string(); + let work = space(&mut connection, "Work"); + let home = space(&mut connection, "Home"); + for (space_id, id, created) in [ + (&work, "w-new", "2021-01-01T00:00:00.000Z"), + (&work, "w-old", "2020-01-01T00:00:00.000Z"), + (&home, "h", "2020-06-01T00:00:00.000Z"), + (&work, "w-gone", "2019-01-01T00:00:00.000Z"), + ] { + insert_imported(&mut connection, &exported(space_id, id, created)).unwrap(); + } + trash(&mut connection, "w-gone", t1()).unwrap(); + let ids = |notes: Vec| notes.into_iter().map(|note| note.id).collect::>(); - assert!(!insert_imported(&mut connection, ¬e).unwrap()); - assert_eq!(list(&mut connection).unwrap()[0].title, "Titre"); + assert_eq!( + ids(all(&mut connection, Some(&work)).unwrap()), + ["w-old", "w-new"] + ); + assert_eq!( + ids(all(&mut connection, None).unwrap()), + ["w-old", "h", "w-new"] + ); + assert_eq!( + all(&mut connection, Some(&work)).unwrap()[0].tags, + ["imported"] + ); } #[test] -fn sharing_a_selection_reads_the_notes_it_names() { +fn notes_chosen_by_id_come_oldest_first_and_only_out_of_the_trash() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let first = create(&mut connection, draft(&space_id), t0()).unwrap(); - create(&mut connection, draft(&space_id), t0()).unwrap(); + let work = space(&mut connection, "Work"); + for (id, created) in [ + ("b", "2021-01-01T00:00:00.000Z"), + ("a", "2020-01-01T00:00:00.000Z"), + ("gone", "2019-01-01T00:00:00.000Z"), + ] { + insert_imported(&mut connection, &exported(&work, id, created)).unwrap(); + } + trash(&mut connection, "gone", t1()).unwrap(); + let asked = ["b", "gone", "a", "missing"].map(String::from); - let selected = by_ids(&mut connection, std::slice::from_ref(&first.id)).unwrap(); + let chosen: Vec = by_ids(&mut connection, &asked) + .unwrap() + .into_iter() + .map(|note| note.id) + .collect(); - assert_eq!(selected.len(), 1); - assert_eq!(selected[0].id, first.id); + assert_eq!(chosen, ["a", "b"]); assert!(by_ids(&mut connection, &[]).unwrap().is_empty()); } diff --git a/crates/engine/tests/notes/seeding.rs b/crates/engine/tests/notes/seeding.rs index 75b112ef1..8e8838440 100644 --- a/crates/engine/tests/notes/seeding.rs +++ b/crates/engine/tests/notes/seeding.rs @@ -1,201 +1,111 @@ use super::*; -/// A process killed halfway must not leave a space with nothing in it, which both of the -/// front end's guards would read as "already seeded". -#[test] -fn the_first_launch_writes_the_space_and_its_notes_as_one() { - let mut library = open_in_memory().unwrap(); - - let space = seed( - &mut library, - "Personnel", - &[], - vec![ - sample( - None, - NoteDraft { - title: "Bienvenue".to_string(), - ..draft("ignored") - }, - ), - sample( - None, - NoteDraft { - title: "Un snippet".to_string(), - ..draft("ignored") - }, - ), - ], - t0(), - ) - .unwrap(); - - assert_eq!(space.name, "Personnel"); - let written = list(&mut library).unwrap(); - assert_eq!(written.len(), 2); - // The drafts carry a space that does not exist when the front end composes them. - assert!(written.iter().all(|note| note.space_id == space.id)); +fn titled(title: &str) -> NoteDraft { + NoteDraft { + title: title.to_string(), + ..snippet("ignored") + } } -/// The folders belong to the same transaction. A seeding that wrote the space and the -/// notes but not the folders would be permanent: a space exists, so both of the front -/// end's guards read "already seeded" and it never runs again. -#[test] -fn the_first_launch_writes_its_folders_with_everything_else() { - let mut library = open_in_memory().unwrap(); - - let space = seed( - &mut library, - "Découverte", - &["Snippets".to_string(), "Prise en main".to_string()], - vec![ - sample( - Some(0), - NoteDraft { - title: "Connexion psql".to_string(), - ..draft("ignored") - }, - ), - sample( - Some(1), - NoteDraft { - title: "Bienvenue".to_string(), - ..draft("ignored") - }, - ), - sample( - None, - NoteDraft { - title: "À essayer".to_string(), - ..draft("ignored") - }, - ), - ], - t0(), - ) - .unwrap(); - - let folders = engine::folders::store::list(&mut library, Some(&space.id)).unwrap(); - assert_eq!( - folders.iter().map(|f| f.name.as_str()).collect::>(), - ["Snippets", "Prise en main"] - ); - // Assigned by rotation, so the two zones are told apart on the board at a glance. - assert_ne!(folders[0].colour, folders[1].colour); - - let written = list(&mut library).unwrap(); - let filed = |title: &str| { - written - .iter() - .find(|note| note.title == title) - .and_then(|note| note.folder_id.clone()) - }; - assert_eq!(filed("Connexion psql"), Some(folders[0].id.clone())); - assert_eq!(filed("Bienvenue"), Some(folders[1].id.clone())); - // One left loose on purpose: "no folder" is a legitimate state, and the first - // launch shows it rather than describing it. - assert_eq!(filed("À essayer"), None); +fn folders(names: &[&str]) -> Vec { + names.iter().map(|name| (*name).to_string()).collect() } -/// Rows sharing one instant would fall back to a random UUID in both orders, and each install -/// would be arranged differently. #[test] -fn the_samples_are_read_back_in_the_order_they_were_declared() { - let mut library = open_in_memory().unwrap(); +fn the_first_launch_writes_its_space_its_folders_and_its_notes() { + let mut connection = open_in_memory().unwrap(); + let samples = vec![ + sample(Some(1), titled("first")), + sample(None, titled("loose")), + ]; let space = seed( - &mut library, - "Découverte", - &["Un".to_string(), "Deux".to_string(), "Trois".to_string()], - vec![ - sample( - None, - NoteDraft { - title: "Premier".to_string(), - ..draft("ignored") - }, - ), - sample( - None, - NoteDraft { - title: "Deuxième".to_string(), - ..draft("ignored") - }, - ), - sample( - None, - NoteDraft { - title: "Troisième".to_string(), - ..draft("ignored") - }, - ), - ], + &mut connection, + "Welcome", + &folders(&["Start", "Go further"]), + samples, t0(), ) .unwrap(); - let folders = engine::folders::store::list(&mut library, Some(&space.id)).unwrap(); - assert_eq!( - folders.iter().map(|f| f.name.as_str()).collect::>(), - ["Un", "Deux", "Trois"] - ); - - // `fetch` is what the canvas asks, ordered as the canvas orders it. + let notes = all(&mut connection, Some(&space.id)).unwrap(); + assert_eq!(notes.len(), 2); + assert!(notes.iter().all(|note| note.space_id == space.id)); + let filed: Vec<_> = engine::folders::store::list(&mut connection, Some(&space.id)) + .unwrap() + .into_iter() + .map(|folder| (folder.id, folder.name)) + .collect(); assert_eq!( - list(&mut library) - .unwrap() + filed .iter() - .map(|note| note.title.as_str()) + .map(|(_, name)| name.as_str()) .collect::>(), - ["Premier", "Deuxième", "Troisième"] + ["Start", "Go further"] ); + let first = notes.iter().find(|note| note.title == "first").unwrap(); + assert_eq!(first.folder_id.as_ref(), Some(&filed[1].0)); + let loose = notes.iter().find(|note| note.title == "loose").unwrap(); + assert_eq!(loose.folder_id, None); +} + +/// The canvas orders the last edit first: the first sample is the newest. +#[test] +fn the_samples_list_in_the_order_they_were_given() { + let mut connection = open_in_memory().unwrap(); + let samples = ["one", "two", "three"] + .map(|title| sample(None, titled(title))) + .to_vec(); + + seed(&mut connection, "Welcome", &[], samples, t0()).unwrap(); + + let titles: Vec = list(&mut connection) + .unwrap() + .into_iter() + .map(|note| note.title) + .collect(); + assert_eq!(titles, ["one", "two", "three"]); } -/// A folder index nothing answers leaves the note loose rather than failing the launch. #[test] -fn a_sample_naming_a_folder_that_is_not_there_is_simply_left_loose() { - let mut library = open_in_memory().unwrap(); +fn a_sample_naming_a_folder_that_is_not_there_is_left_loose() { + let mut connection = open_in_memory().unwrap(); seed( - &mut library, - "Découverte", - &["Snippets".to_string()], - vec![sample( - Some(7), - NoteDraft { - title: "Égarée".to_string(), - ..draft("ignored") - }, - )], + &mut connection, + "Welcome", + &folders(&["Only"]), + vec![sample(Some(7), titled("lost"))], t0(), ) .unwrap(); - assert_eq!(list(&mut library).unwrap()[0].folder_id, None); + assert_eq!(list(&mut connection).unwrap()[0].folder_id, None); } -/// A refused seeding leaves nothing behind — not even the space it had started with. +/// A space standing without its notes reads as « already seeded » for ever. #[test] -fn a_seeding_that_fails_leaves_no_half_library() { - let mut library = open_in_memory().unwrap(); - spaces::create(&mut library, "Personnel").unwrap(); - let before = spaces::list(&mut library).unwrap().len(); - - // The name is taken, so the space this seeding opens with is refused. - let refused = seed( - &mut library, - "personnel", - &["Snippets".to_string()], - vec![sample(None, draft("ignored"))], +fn the_first_launch_is_one_write_that_leaves_nothing_when_it_fails() { + let mut connection = open_in_memory().unwrap(); + space(&mut connection, "Welcome"); + + let failed = seed( + &mut connection, + "Welcome", + &folders(&["Start"]), + vec![sample(None, titled("x"))], t0(), ); - assert!(matches!(refused, Err(StorageError::DuplicateSpaceName(_)))); - assert_eq!(spaces::list(&mut library).unwrap().len(), before); - assert!(list(&mut library).unwrap().is_empty()); + assert!(matches!(failed, Err(StorageError::DuplicateSpaceName(_)))); + assert!(list(&mut connection).unwrap().is_empty()); assert!( - engine::folders::store::list(&mut library, None) + engine::folders::store::list(&mut connection, None) .unwrap() .is_empty() ); + assert_eq!( + engine::spaces::store::list(&mut connection).unwrap().len(), + 1 + ); } From 25c68f215e74bafc948d62027b7517ab183db20a Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:24:34 +0100 Subject: [PATCH 14/95] Tags and bulk actions: unit tests rewritten (#1738) Corpus-wide renames, merges and drops with the count they announce; moves, tags, pins and priorities answering what they changed, undone exactly, dating nothing. The doc and the comment that still said tagging dates a note follow #1534. --- crates/engine/src/notes/store.rs | 4 +- crates/engine/tests/notes/batches.rs | 628 ++++++++++++++++----------- crates/engine/tests/notes/main.rs | 3 - crates/engine/tests/notes/tags.rs | 216 ++++----- docs/architecture.md | 6 +- 5 files changed, 487 insertions(+), 370 deletions(-) diff --git a/crates/engine/src/notes/store.rs b/crates/engine/src/notes/store.rs index 71d5d6757..4f1239071 100644 --- a/crates/engine/src/notes/store.rs +++ b/crates/engine/src/notes/store.rs @@ -887,8 +887,8 @@ pub fn untag_many(connection: &mut Library, pairs: &[NoteTag]) -> Result Desk { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let note = create(&mut connection, draft(&space_id), t0()).unwrap(); + let work = space(&mut connection, "Work"); + let home = space(&mut connection, "Home"); + Desk { + connection, + work, + home, + } +} + +impl Desk { + fn note(&mut self, draft: NoteDraft) -> String { + create(&mut self.connection, draft, t0()).unwrap().id + } - let error = move_many(&mut connection, std::slice::from_ref(¬e.id), "ghost").unwrap_err(); + fn folder(&mut self, space_id: &str, name: &str) -> String { + engine::folders::store::create(&mut self.connection, space_id, None, name, t0()) + .unwrap() + .id + } - assert!(matches!(error, StorageError::SpaceNotFound(_))); - assert_eq!(list(&mut connection).unwrap()[0].space_id, space_id); + fn read(&mut self, id: &str) -> Note { + get(&mut self.connection, id).unwrap() + } } -fn prioritised(space_id: &str, priority: Priority) -> NoteDraft { - NoteDraft { - priority, - ..draft(space_id) +fn pair(note_id: &str, tag: &str) -> NoteTag { + NoteTag { + note_id: note_id.to_string(), + tag: tag.to_string(), } } -/// Triaging is not editing: a list sorted by modification must not reshuffle under it. +fn pairs(found: &[NoteTag]) -> Vec<(String, String)> { + let mut found: Vec<_> = found + .iter() + .map(|each| (each.note_id.clone(), each.tag.clone())) + .collect(); + found.sort(); + found +} + +// --- Moving. + #[test] -fn a_priority_moves_only_the_notes_that_differ_and_leaves_updated_at_alone() { - let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let plain = create(&mut connection, draft(&space_id), t0()).unwrap(); - let urgent = create( - &mut connection, - prioritised(&space_id, Priority::Urgent), - t0(), +fn a_move_answers_where_each_note_it_moved_came_from() { + let mut desk = desk(); + let work = desk.work.clone(); + let folder = desk.folder(&work, "Infra"); + let filed = desk.note(NoteDraft { + folder_id: Some(folder.clone()), + ..draft(&work) + }); + let loose = desk.note(draft(&work)); + let home = desk.home.clone(); + let already_there = desk.note(draft(&home)); + + let moved = move_many( + &mut desk.connection, + &[ + filed.clone(), + loose.clone(), + already_there.clone(), + "missing".to_string(), + ], + &home, ) .unwrap(); - let previous = set_priority_many( - &mut connection, - &[plain.id.clone(), urgent.id.clone()], - Priority::Urgent, - ) - .unwrap(); + let mut from: Vec<_> = moved + .iter() + .map(|placement| (placement.note_id.clone(), placement.folder_id.clone())) + .collect(); + from.sort(); + let mut expected = vec![(filed.clone(), Some(folder)), (loose.clone(), None)]; + expected.sort(); + assert_eq!(from, expected); + assert!(moved.iter().all(|placement| placement.space_id == work)); + for id in [&filed, &loose] { + let read = desk.read(id); + assert_eq!( + (read.space_id.as_str(), read.folder_id.as_deref()), + (home.as_str(), None) + ); + assert_eq!(read.updated_at, t0()); + } +} - assert_eq!( - previous, - [NotePriority { - note_id: plain.id, - priority: Priority::None - }] +/// Out of its folder, in its own space too. +#[test] +fn a_move_into_a_note_s_own_space_takes_it_out_of_its_folder() { + let mut desk = desk(); + let work = desk.work.clone(); + let folder = desk.folder(&work, "Infra"); + let filed = desk.note(NoteDraft { + folder_id: Some(folder), + ..draft(&work) + }); + + let moved = move_many(&mut desk.connection, std::slice::from_ref(&filed), &work).unwrap(); + + assert_eq!(moved.len(), 1); + assert_eq!(desk.read(&filed).folder_id, None); +} + +#[test] +fn a_move_to_a_space_that_does_not_exist_moves_nothing() { + let mut desk = desk(); + let work = desk.work.clone(); + let id = desk.note(draft(&work)); + + assert!(matches!( + move_many(&mut desk.connection, std::slice::from_ref(&id), "nowhere"), + Err(StorageError::SpaceNotFound(_)) + )); + assert_eq!(desk.read(&id).space_id, work); + assert!( + move_many(&mut desk.connection, &[], "nowhere") + .unwrap() + .is_empty() ); - let listed = list(&mut connection).unwrap(); - assert!(listed.iter().all(|note| note.priority == Priority::Urgent)); - assert!(listed.iter().all(|note| note.updated_at == t0())); } -/// Each note gets its own back, not one priority for the whole batch. #[test] -fn undoing_a_priority_gives_each_note_back_its_own() { - let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let low = create(&mut connection, prioritised(&space_id, Priority::Low), t0()).unwrap(); - let high = create( - &mut connection, - prioritised(&space_id, Priority::High), - t0(), - ) - .unwrap(); +fn a_trashed_note_is_not_moved() { + let mut desk = desk(); + let work = desk.work.clone(); + let home = desk.home.clone(); + let id = desk.note(draft(&work)); + trash(&mut desk.connection, &id, t1()).unwrap(); + + assert!( + move_many(&mut desk.connection, &[id], &home) + .unwrap() + .is_empty() + ); +} - let previous = set_priority_many( - &mut connection, - &[low.id.clone(), high.id.clone()], - Priority::Urgent, - ) - .unwrap(); - let restored = restore_priorities(&mut connection, &previous).unwrap(); +#[test] +fn a_move_undone_puts_each_note_back_in_its_space_and_folder() { + let mut desk = desk(); + let work = desk.work.clone(); + let home = desk.home.clone(); + let folder = desk.folder(&work, "Infra"); + let filed = desk.note(NoteDraft { + folder_id: Some(folder.clone()), + ..draft(&work) + }); + let loose = desk.note(draft(&work)); + let moved = move_many(&mut desk.connection, &[filed.clone(), loose.clone()], &home).unwrap(); + + let restored = restore_placements(&mut desk.connection, &moved).unwrap(); assert_eq!(restored, 2); - let listed = list(&mut connection).unwrap(); - let priority_of = |id: &str| listed.iter().find(|note| note.id == id).unwrap().priority; - assert_eq!(priority_of(&low.id), Priority::Low); - assert_eq!(priority_of(&high.id), Priority::High); - assert!(listed.iter().all(|note| note.updated_at == t0())); + let back = desk.read(&filed); + assert_eq!( + (back.space_id.as_str(), back.folder_id.as_deref()), + (work.as_str(), Some(folder.as_str())) + ); + assert_eq!(desk.read(&loose).space_id, work); + assert_eq!(restore_placements(&mut desk.connection, &[]).unwrap(), 0); } +/// A folder deleted since leaves the note loose, as deleting the folder would have. #[test] -fn tagging_a_selection_adds_without_replacing() { - let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let note = create(&mut connection, draft(&space_id), t0()).unwrap(); +fn a_move_undone_into_a_folder_gone_since_leaves_the_note_loose() { + let mut desk = desk(); + let work = desk.work.clone(); + let home = desk.home.clone(); + let placement = |note_id: &str, folder: &str| NotePlacement { + note_id: note_id.to_string(), + space_id: work.clone(), + folder_id: Some(folder.to_string()), + }; + let id = desk.note(draft(&home)); - let added = tag_many( - &mut connection, - std::slice::from_ref(¬e.id), - &["urgent".to_string()], - ) - .unwrap(); + restore_placements(&mut desk.connection, &[placement(&id, "gone")]).unwrap(); - assert_eq!(added.len(), 1); - assert_eq!(added[0].note_id, note.id); - assert_eq!(added[0].tag, "urgent"); + let back = desk.read(&id); assert_eq!( - list(&mut connection).unwrap()[0].tags, - ["api", "auth", "urgent"] + (back.space_id.as_str(), back.folder_id), + (work.as_str(), None) ); } -/// The pair list is what the undo strips again, so a tag the note already carried -/// must not appear in it — and nothing changed, so `updated_at` stays put. +/// A space dropped since is no error: the rest still goes back. #[test] -fn tagging_twice_does_not_duplicate_the_tag_nor_claim_to_have_added_it() { - let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let note = create(&mut connection, draft(&space_id), t0()).unwrap(); - - let added = tag_many( - &mut connection, - std::slice::from_ref(¬e.id), - &["Auth".to_string()], - ) - .unwrap(); +fn a_move_undone_skips_a_space_gone_since_and_a_trashed_note() { + let mut desk = desk(); + let home = desk.home.clone(); + let work = desk.work.clone(); + let kept = desk.note(draft(&home)); + let trashed = desk.note(draft(&home)); + trash(&mut desk.connection, &trashed, t1()).unwrap(); + let placements = [ + NotePlacement { + note_id: kept.clone(), + space_id: "gone".to_string(), + folder_id: None, + }, + NotePlacement { + note_id: trashed.clone(), + space_id: work.clone(), + folder_id: None, + }, + ]; - assert!(added.is_empty(), "{added:?}"); - let listed = list(&mut connection).unwrap(); - assert_eq!(listed[0].tags, ["api", "auth"]); - assert_eq!(listed[0].updated_at, t0()); + assert_eq!( + restore_placements(&mut desk.connection, &placements).unwrap(), + 0 + ); + assert_eq!(desk.read(&kept).space_id, home); } -/// The whole point of answering pairs: undoing a batch that skipped a note must not take -/// the tag off that note. +// --- Tagging. + #[test] -fn undoing_a_tagging_leaves_the_tag_on_the_note_that_already_carried_it() { - let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let carried = create(&mut connection, draft(&space_id), t0()).unwrap(); - let plain = create( - &mut connection, - NoteDraft { - tags: Vec::new(), - ..draft(&space_id) - }, - t0(), - ) - .unwrap(); +fn tagging_adds_to_what_each_note_carries_and_answers_only_the_pairs_it_added() { + let mut desk = desk(); + let work = desk.work.clone(); + let carrying = desk.note(tagged(&work, &["OPS"])); + let bare = desk.note(tagged(&work, &[])); + let trashed = desk.note(tagged(&work, &[])); + trash(&mut desk.connection, &trashed, t1()).unwrap(); + let ids = [ + carrying.clone(), + bare.clone(), + trashed, + "missing".to_string(), + ]; let added = tag_many( - &mut connection, - &[carried.id.clone(), plain.id.clone()], - &["auth".to_string()], + &mut desk.connection, + &ids, + &["ops".to_string(), "ci".to_string()], ) .unwrap(); - untag_many(&mut connection, &added).unwrap(); - - let listed = list(&mut connection).unwrap(); - let kept = listed.iter().find(|note| note.id == carried.id).unwrap(); - let stripped = listed.iter().find(|note| note.id == plain.id).unwrap(); - assert_eq!(kept.tags, ["api", "auth"]); - assert!(stripped.tags.is_empty(), "{:?}", stripped.tags); + let mut expected = vec![ + (carrying.clone(), "ci".to_string()), + (bare.clone(), "ci".to_string()), + (bare.clone(), "ops".to_string()), + ]; + expected.sort(); + assert_eq!(pairs(&added), expected); + assert_eq!(desk.read(&carrying).tags, ["ci", "OPS"]); + assert_eq!(desk.read(&bare).updated_at, t0()); } #[test] -fn a_move_goes_back_to_the_space_each_note_left() { - let mut connection = open_in_memory().unwrap(); - let personal = space(&mut connection, "Personal"); - let work = space(&mut connection, "Boulot"); - let target = space(&mut connection, "Archive"); - let from_personal = create(&mut connection, draft(&personal), t0()).unwrap(); - let from_work = create(&mut connection, draft(&work), t0()).unwrap(); - - let previous = move_many( - &mut connection, - &[from_personal.id.clone(), from_work.id.clone()], - &target, - ) - .unwrap(); - let restored = restore_placements(&mut connection, &previous).unwrap(); +fn tagging_nothing_or_with_nothing_adds_nothing() { + let mut desk = desk(); + let work = desk.work.clone(); + let id = desk.note(draft(&work)); - assert_eq!(restored, 2); - let listed = list(&mut connection).unwrap(); - let one = listed - .iter() - .find(|note| note.id == from_personal.id) - .unwrap(); - let other = listed.iter().find(|note| note.id == from_work.id).unwrap(); - - assert_eq!(one.space_id, personal); - assert_eq!(other.space_id, work); + assert!( + tag_many(&mut desk.connection, &[], &["x".to_string()]) + .unwrap() + .is_empty() + ); + assert!( + tag_many(&mut desk.connection, &[id], &[]) + .unwrap() + .is_empty() + ); } -/// A space dropped between the move and the undo takes its notes with it; the rest of -/// the batch still goes home. +/// The undo strips exactly what was added, never a tag the note already carried. #[test] -fn a_space_gone_since_the_move_does_not_take_the_rest_of_the_undo_with_it() { - let mut connection = open_in_memory().unwrap(); - let doomed = space(&mut connection, "Personal"); - let kept = space(&mut connection, "Boulot"); - let target = space(&mut connection, "Archive"); - let orphan = create(&mut connection, draft(&doomed), t0()).unwrap(); - let survivor = create(&mut connection, draft(&kept), t0()).unwrap(); - - let previous = move_many( - &mut connection, - &[orphan.id.clone(), survivor.id.clone()], - &target, +fn tagging_undone_takes_off_exactly_the_pairs_it_added() { + let mut desk = desk(); + let work = desk.work.clone(); + let carrying = desk.note(tagged(&work, &["ops"])); + let bare = desk.note(tagged(&work, &[])); + let added = tag_many( + &mut desk.connection, + &[carrying.clone(), bare.clone()], + &["ops".to_string()], ) .unwrap(); - spaces::delete(&mut connection, &doomed, &target, None).unwrap(); - let restored = restore_placements(&mut connection, &previous).unwrap(); + let removed = untag_many(&mut desk.connection, &added).unwrap(); - assert_eq!(restored, 1); - let listed = list(&mut connection).unwrap(); - assert_eq!( - listed - .iter() - .find(|note| note.id == survivor.id) + assert_eq!(removed, 1); + assert_eq!(desk.read(&carrying).tags, ["ops"]); + assert!(desk.read(&bare).tags.is_empty()); + assert_eq!(untag_many(&mut desk.connection, &[]).unwrap(), 0); +} + +#[test] +fn a_tag_taken_off_answers_the_pairs_as_each_note_spelled_them() { + let mut desk = desk(); + let work = desk.work.clone(); + let upper = desk.note(tagged(&work, &["OPS", "keep"])); + let lower = desk.note(tagged(&work, &["ops"])); + let bare = desk.note(tagged(&work, &[])); + let trashed = desk.note(tagged(&work, &["ops"])); + trash(&mut desk.connection, &trashed, t1()).unwrap(); + let ids = [upper.clone(), lower.clone(), bare, trashed.clone()]; + + let removed = remove_tag(&mut desk.connection, &ids, "ops").unwrap(); + + let mut expected = vec![ + (upper.clone(), "OPS".to_string()), + (lower.clone(), "ops".to_string()), + ]; + expected.sort(); + assert_eq!(pairs(&removed), expected); + assert_eq!(desk.read(&upper).tags, ["keep"]); + assert_eq!(desk.read(&upper).updated_at, t0()); + assert!( + remove_tag(&mut desk.connection, &[], "ops") .unwrap() - .space_id, - kept + .is_empty() ); } -/// A note taken out of its folder by a move goes back into it with the undo. #[test] -fn putting_a_move_back_files_the_note_into_its_folder_again() { - use engine::folders::store as folders; - - let mut connection = open_in_memory().unwrap(); - let source = space(&mut connection, "Personal"); - let target = space(&mut connection, "Boulot"); - let folder = folders::create(&mut connection, &source, None, "Perf", t0()).unwrap(); - let note = create(&mut connection, draft(&source), t0()).unwrap(); - folders::file_many( - &mut connection, - std::slice::from_ref(¬e.id), - Some(&folder.id), - crate::CARD, +fn a_tag_taken_off_and_undone_comes_back_on_the_live_notes_alone() { + let mut desk = desk(); + let work = desk.work.clone(); + let live = desk.note(tagged(&work, &["ops"])); + let trashed = desk.note(tagged(&work, &[])); + trash(&mut desk.connection, &trashed, t1()).unwrap(); + let removed = remove_tag(&mut desk.connection, std::slice::from_ref(&live), "ops").unwrap(); + + let back = restore_tags( + &mut desk.connection, + &[removed[0].clone(), pair(&trashed, "ops")], ) .unwrap(); - let previous = move_many(&mut connection, std::slice::from_ref(¬e.id), &target).unwrap(); - assert_eq!(previous[0].folder_id.as_deref(), Some(folder.id.as_str())); - assert_eq!(list(&mut connection).unwrap()[0].folder_id, None); + assert_eq!(back, 1); + assert_eq!(desk.read(&live).tags, ["ops"]); + assert_eq!(restore_tags(&mut desk.connection, &[]).unwrap(), 0); + assert_eq!( + restore_tags(&mut desk.connection, &[pair(&trashed, "x")]).unwrap(), + 0 + ); +} - restore_placements(&mut connection, &previous).unwrap(); +// --- Pins and priorities: triage, never an edit. - let back = &list(&mut connection).unwrap()[0]; - assert_eq!(back.space_id, source); - assert_eq!(back.folder_id.as_deref(), Some(folder.id.as_str())); +#[test] +fn a_pin_answers_the_notes_whose_pin_changed_and_dates_none() { + let mut desk = desk(); + let work = desk.work.clone(); + let pinned = desk.note(NoteDraft { + pinned: true, + ..draft(&work) + }); + let loose = desk.note(draft(&work)); + + let changed = + set_pinned_many(&mut desk.connection, &[pinned.clone(), loose.clone()], true).unwrap(); + + assert_eq!(changed, std::slice::from_ref(&loose)); + assert!(desk.read(&loose).pinned); + assert_eq!(desk.read(&loose).updated_at, t0()); + assert!( + set_pinned_many(&mut desk.connection, &[], true) + .unwrap() + .is_empty() + ); } -/// A folder deleted between the move and the undo leaves the note loose in its space. #[test] -fn a_folder_gone_since_the_move_leaves_the_note_loose() { - use engine::folders::store as folders; +fn a_priority_answers_what_each_note_had_and_its_undo_gives_each_its_own_back() { + let mut desk = desk(); + let work = desk.work.clone(); + let low = desk.note(NoteDraft { + priority: Priority::Low, + ..draft(&work) + }); + let high = desk.note(NoteDraft { + priority: Priority::High, + ..draft(&work) + }); + let urgent = desk.note(NoteDraft { + priority: Priority::Urgent, + ..draft(&work) + }); - let mut connection = open_in_memory().unwrap(); - let source = space(&mut connection, "Personal"); - let target = space(&mut connection, "Boulot"); - let folder = folders::create(&mut connection, &source, None, "Perf", t0()).unwrap(); - let note = create(&mut connection, draft(&source), t0()).unwrap(); - folders::file_many( - &mut connection, - std::slice::from_ref(¬e.id), - Some(&folder.id), - crate::CARD, + let previous = set_priority_many( + &mut desk.connection, + &[low.clone(), high.clone(), urgent.clone()], + Priority::Urgent, ) .unwrap(); - let previous = move_many(&mut connection, std::slice::from_ref(¬e.id), &target).unwrap(); - folders::delete(&mut connection, &folder.id, crate::CARD, None).unwrap(); - assert_eq!(restore_placements(&mut connection, &previous).unwrap(), 1); + let mut had: Vec<_> = previous + .iter() + .map(|change| (change.note_id.clone(), change.priority)) + .collect(); + had.sort(); + let mut expected = vec![(low.clone(), Priority::Low), (high.clone(), Priority::High)]; + expected.sort(); + assert_eq!(had, expected); + assert_eq!(desk.read(&low).priority, Priority::Urgent); + assert_eq!(desk.read(&low).updated_at, t0()); - let back = &list(&mut connection).unwrap()[0]; - assert_eq!(back.space_id, source); - assert_eq!(back.folder_id, None); + assert_eq!( + restore_priorities(&mut desk.connection, &previous).unwrap(), + 2 + ); + assert_eq!(desk.read(&low).priority, Priority::Low); + assert_eq!(desk.read(&high).priority, Priority::High); } -/// Moving, tagging and untagging a selection is not editing it, and « Undo » after any of them -/// leaves the list as it was: the date that orders it never moved (#1478, N17). #[test] -fn moves_and_tags_in_a_batch_leave_updated_at_alone_through_their_undo() { - let mut connection = open_in_memory().unwrap(); - let source = space(&mut connection, "Personal"); - let target = space(&mut connection, "Boulot"); - let note = create(&mut connection, draft(&source), t0()).unwrap(); - let ids = std::slice::from_ref(¬e.id); - let dated = |connection: &mut Library| { - list(connection) - .unwrap() - .into_iter() - .find(|listed| listed.id == note.id) +fn a_priority_skips_the_trash_and_nothing_given_does_nothing() { + let mut desk = desk(); + let work = desk.work.clone(); + let trashed = desk.note(draft(&work)); + trash(&mut desk.connection, &trashed, t1()).unwrap(); + let previous = [NotePriority { + note_id: trashed.clone(), + priority: Priority::High, + }]; + + assert!( + set_priority_many( + &mut desk.connection, + std::slice::from_ref(&trashed), + Priority::High + ) + .unwrap() + .is_empty() + ); + assert_eq!( + restore_priorities(&mut desk.connection, &previous).unwrap(), + 0 + ); + assert!( + set_priority_many(&mut desk.connection, &[], Priority::High) .unwrap() - .updated_at - }; - - let moved = move_many(&mut connection, ids, &target).unwrap(); - assert_eq!(dated(&mut connection), t0(), "moved"); - restore_placements(&mut connection, &moved).unwrap(); - let tagged = tag_many(&mut connection, ids, &["ops".to_owned()]).unwrap(); - assert_eq!(dated(&mut connection), t0(), "tagged"); - untag_many(&mut connection, &tagged).unwrap(); - tag_many(&mut connection, ids, &["ops".to_owned()]).unwrap(); - let removed = engine::notes::store::remove_tag(&mut connection, ids, "ops").unwrap(); - assert_eq!(dated(&mut connection), t0(), "untagged"); - engine::notes::store::restore_tags(&mut connection, &removed).unwrap(); - - assert_eq!(dated(&mut connection), t0()); + .is_empty() + ); + assert_eq!(restore_priorities(&mut desk.connection, &[]).unwrap(), 0); } diff --git a/crates/engine/tests/notes/main.rs b/crates/engine/tests/notes/main.rs index 2e9506a81..c72988403 100644 --- a/crates/engine/tests/notes/main.rs +++ b/crates/engine/tests/notes/main.rs @@ -26,9 +26,6 @@ use engine::notes::view::{self, Grouping, NoteFilter, NoteOrder, NotesQuery, Not use engine::spaces::store as spaces; use std::collections::BTreeMap; -/// A four-line card, the default `PreviewLines`: what the board's geometry is sized from. -const CARD: i32 = 140; - #[path = "../common/mod.rs"] mod common; use common::{at, snippet, space, t0, t1}; diff --git a/crates/engine/tests/notes/tags.rs b/crates/engine/tests/notes/tags.rs index 2d37b0fcd..71655b942 100644 --- a/crates/engine/tests/notes/tags.rs +++ b/crates/engine/tests/notes/tags.rs @@ -1,165 +1,165 @@ use super::*; -/// Distinct, not summed: a note carrying two of the tags is one note, and a -/// confirmation that overstates its blast radius teaches people to dismiss it. -#[test] -fn the_blast_radius_counts_a_note_carrying_two_of_the_tags_once() { - let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - create(&mut connection, draft(&space_id), t0()).unwrap(); +fn strings(values: &[&str]) -> Vec { + values.iter().map(|value| (*value).to_string()).collect() +} - let counted = - count_notes_tagged(&mut connection, &["api".to_string(), "auth".to_string()]).unwrap(); +/// Notes tagged as given, in one space; the last one trashed when `trash_last`. +fn corpus(connection: &mut Library, tags: &[&[&str]], trash_last: bool) -> Vec { + let space_id = space(connection, "Work"); + let ids: Vec = tags + .iter() + .map(|carried| { + create(connection, tagged(&space_id, carried), t0()) + .unwrap() + .id + }) + .collect(); + if trash_last { + trash(connection, ids.last().unwrap(), t1()).unwrap(); + } + ids +} - assert_eq!(counted, 1); +fn tags_of(connection: &mut Library, id: &str) -> Vec { + note_tags::table + .filter(note_tags::note_id.eq(id)) + .select(note_tags::tag) + .order(note_tags::tag.asc()) + .load(connection.db()) + .unwrap() } -/// A rename reaches the trash too, so the count that announces it has to. #[test] -fn the_blast_radius_counts_what_is_in_the_trash() { +fn the_tags_in_use_are_counted_over_the_live_notes_in_the_column_s_order() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let note = create(&mut connection, draft(&space_id), t0()).unwrap(); - create(&mut connection, draft(&space_id), t0()).unwrap(); - trash(&mut connection, ¬e.id, t1()).unwrap(); + corpus( + &mut connection, + &[&["ops", "Ci"], &["ops"], &["ops", "gone"]], + true, + ); assert_eq!( - count_notes_tagged(&mut connection, &["auth".to_string()]).unwrap(), - 2 + tag_usage(&mut connection).unwrap(), + [("Ci".to_string(), 1), ("ops".to_string(), 2)] ); } +/// A note carrying two of the tags is one note; the trash counts, as the rename touches it. #[test] -fn the_count_confirmed_is_the_count_renamed() { +fn the_notes_tagged_are_counted_once_each_the_trash_included() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let thrown = create(&mut connection, draft(&space_id), t0()).unwrap(); - create(&mut connection, draft(&space_id), t0()).unwrap(); - trash(&mut connection, &thrown.id, t1()).unwrap(); - let tags = ["api".to_string(), "auth".to_string()]; - - let confirmed = count_notes_tagged(&mut connection, &tags).unwrap(); + corpus( + &mut connection, + &[&["a", "b"], &["b"], &["c"], &["a"]], + true, + ); - assert_eq!(retag(&mut connection, &tags, "backend").unwrap(), confirmed); + assert_eq!( + count_notes_tagged(&mut connection, &strings(&["a", "b"])).unwrap(), + 3 + ); + assert_eq!( + count_notes_tagged(&mut connection, &strings(&["none"])).unwrap(), + 0 + ); + assert_eq!(count_notes_tagged(&mut connection, &[]).unwrap(), 0); } #[test] -fn the_count_confirmed_is_the_count_deleted() { +fn a_rename_moves_every_note_onto_the_new_tag_and_answers_how_many_it_touched() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let thrown = create(&mut connection, draft(&space_id), t0()).unwrap(); - create(&mut connection, draft(&space_id), t0()).unwrap(); - trash(&mut connection, &thrown.id, t1()).unwrap(); - let tags = ["api".to_string(), "auth".to_string()]; + let ids = corpus( + &mut connection, + &[&["auth"], &["authentication", "auth"], &["ops"]], + false, + ); - let confirmed = count_notes_tagged(&mut connection, &tags).unwrap(); + let renamed = retag( + &mut connection, + &strings(&["auth", "authentication"]), + "security", + ) + .unwrap(); - assert_eq!(drop_tags(&mut connection, &tags).unwrap(), confirmed); + assert_eq!(renamed, 2); + assert_eq!(tags_of(&mut connection, &ids[0]), ["security"]); + assert_eq!(tags_of(&mut connection, &ids[1]), ["security"]); + assert_eq!(tags_of(&mut connection, &ids[2]), ["ops"]); } +/// The database cannot carry one tag twice on a note: renaming onto one in use merges. #[test] -fn a_note_restored_after_a_rename_comes_back_under_the_new_name() { +fn a_rename_onto_a_tag_in_use_merges_the_two() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let thrown = create(&mut connection, draft(&space_id), t0()).unwrap(); - trash(&mut connection, &thrown.id, t1()).unwrap(); - - retag(&mut connection, &["auth".to_string()], "identity").unwrap(); - restore_many(&mut connection, std::slice::from_ref(&thrown.id)).unwrap(); - - assert_eq!(list(&mut connection).unwrap()[0].tags, ["api", "identity"]); -} + let ids = corpus( + &mut connection, + &[&["auth", "security"], &["security"]], + false, + ); -#[test] -fn every_tag_is_listed_with_the_number_of_notes_carrying_it() { - let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - create(&mut connection, draft(&space_id), t0()).unwrap(); - create(&mut connection, draft(&space_id), t0()).unwrap(); + retag(&mut connection, &strings(&["auth"]), "security").unwrap(); + assert_eq!(tags_of(&mut connection, &ids[0]), ["security"]); assert_eq!( tag_usage(&mut connection).unwrap(), - [("api".to_string(), 2), ("auth".to_string(), 2)] + [("security".to_string(), 2)] ); } +/// The key folds ASCII case: without sweeping the target along, `auth` → `Auth` would change +/// nothing. #[test] -fn a_trashed_note_no_longer_counts_towards_its_tags() { +fn a_rename_that_corrects_the_case_alone_takes_effect() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let kept = create(&mut connection, draft(&space_id), t0()).unwrap(); - let thrown = create(&mut connection, draft(&space_id), t0()).unwrap(); - trash(&mut connection, &thrown.id, t1()).unwrap(); + let ids = corpus(&mut connection, &[&["auth"]], false); - let usage = tag_usage(&mut connection).unwrap(); + retag(&mut connection, &strings(&["auth"]), "Auth").unwrap(); - assert_eq!(usage[0], ("api".to_string(), 1)); - assert_eq!(list(&mut connection).unwrap()[0].id, kept.id); + assert_eq!(tags_of(&mut connection, &ids[0]), ["Auth"]); } #[test] -fn renaming_a_tag_onto_an_existing_one_merges_them() { +fn a_rename_reaches_the_trash_and_leaves_every_date() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let note = create(&mut connection, draft(&space_id), t0()).unwrap(); + let ids = corpus(&mut connection, &[&["auth"], &["auth"]], true); - let touched = retag(&mut connection, &["api".to_string()], "auth").unwrap(); + let renamed = retag(&mut connection, &strings(&["auth"]), "security").unwrap(); - assert_eq!(touched, 1); - assert_eq!(list(&mut connection).unwrap()[0].tags, ["auth"]); - assert_eq!(note.tags.len(), 2); + assert_eq!(renamed, 2); + assert_eq!(tags_of(&mut connection, &ids[1]), ["security"]); + assert_eq!(get(&mut connection, &ids[0]).unwrap().updated_at, t0()); + assert_eq!(retag(&mut connection, &[], "x").unwrap(), 0); } +/// The rename answers the count its confirmation announced. #[test] -fn merging_several_tags_keeps_one_note_entry_each() { +fn a_rename_and_its_confirmation_count_the_same_notes() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - create(&mut connection, draft(&space_id), t0()).unwrap(); + corpus(&mut connection, &[&["a", "b"], &["b"], &["a"]], true); + let sources = strings(&["a", "b"]); - retag( - &mut connection, - &["api".to_string(), "auth".to_string()], - "backend", - ) - .unwrap(); + let announced = count_notes_tagged(&mut connection, &sources).unwrap(); - assert_eq!(list(&mut connection).unwrap()[0].tags, ["backend"]); + assert_eq!(retag(&mut connection, &sources, "c").unwrap(), announced); } #[test] -fn correcting_the_case_of_a_tag_does_not_erase_it() { +fn dropping_tags_takes_them_off_every_note_and_answers_how_many_carried_them() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - create(&mut connection, draft(&space_id), t0()).unwrap(); - - retag(&mut connection, &["auth".to_string()], "Auth").unwrap(); - - assert_eq!(list(&mut connection).unwrap()[0].tags, ["api", "Auth"]); -} - -#[test] -fn dropping_a_tag_leaves_the_notes_in_place() { - let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - create(&mut connection, draft(&space_id), t0()).unwrap(); - - assert_eq!( - drop_tags(&mut connection, &["auth".to_string()]).unwrap(), - 1 + let ids = corpus( + &mut connection, + &[&["a", "b", "keep"], &["b"], &["a"]], + true, ); + let dropped = strings(&["a", "b"]); + let announced = count_notes_tagged(&mut connection, &dropped).unwrap(); - let listed = list(&mut connection).unwrap(); - assert_eq!(listed.len(), 1); - assert_eq!(listed[0].tags, ["api"]); -} - -#[test] -fn a_global_retag_does_not_float_the_corpus_to_the_top_of_the_canvas() { - let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - create(&mut connection, draft(&space_id), t0()).unwrap(); - - retag(&mut connection, &["auth".to_string()], "identity").unwrap(); + let answered = drop_tags(&mut connection, &dropped).unwrap(); - assert_eq!(list(&mut connection).unwrap()[0].updated_at, t0()); + assert_eq!((answered, announced), (3, 3)); + assert_eq!(tags_of(&mut connection, &ids[0]), ["keep"]); + assert!(tags_of(&mut connection, &ids[2]).is_empty()); + assert_eq!(get(&mut connection, &ids[0]).unwrap().updated_at, t0()); + assert_eq!(drop_tags(&mut connection, &[]).unwrap(), 0); } diff --git a/docs/architecture.md b/docs/architecture.md index 470edaa93..7fbdc9ffc 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -3431,8 +3431,8 @@ at — the placements the notes left, the `(note, tag)` pairs actually inserted. `move_notes_back` and `untag_notes` undo, exactly and nothing wider. It also fixed a count that had always overstated itself: `tag_many` used to report every live note in the selection, including the ones already carrying the tag, which `INSERT OR IGNORE` had quietly skipped. -Those notes no longer have `updated_at` refreshed either, for the same reason — nothing about -them changed. +None of them has `updated_at` refreshed: moving, filing and tagging a selection is not editing +it, and « Undo » after any of them leaves a list sorted by modification as it was. ⚠️ Which notes "already carry the tag" is decided in SQL, before the insert, by the same comparison the insert will make: `note_tags.tag` is `COLLATE NOCASE`, and SQLite's `NOCASE` @@ -3452,7 +3452,7 @@ no date; its undo is the same call the other way over those. The selection bar, the `P` key and the editor all go through it (`NotesStore.setPinned`, a batch of one with its undo); only a draft takes its pin as a field. The bar's one button pins what is ticked, or unpins it once all of it is pinned. **A tag is taken off** by `remove_tag(ids, tag)`, which answers the -pairs as stored and moves `updated_at` like tagging; `restore_tags` puts back exactly those. +pairs as stored and leaves `updated_at` like tagging; `restore_tags` puts back exactly those. The bar offers the tags the ticked notes carry (`NoteSelectionStore.checkedTags`). **On screen, a priority is said three ways**: a pill on the card (`PriorityPillComponent`, in From 55c7b409ba1a2c81f1c307f7f27d646fa0c6e1fa Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:30:27 +0100 Subject: [PATCH 15/95] Note history and trash: unit tests rewritten (#1732) * Rewrite the tests of a note's history and of the trash What an edit keeps and when, the cap, the preview's diff, going back; what the trash hides, gives back, lets expire and erases. * Hold the startup sweep as never fatal --- crates/engine/src/notes/revision.rs | 154 ++++----- crates/engine/src/notes/trash.rs | 88 ++++-- crates/engine/tests/notes/revisions.rs | 416 +++++++++++++------------ crates/engine/tests/notes/trash.rs | 219 ++++++++----- docs/architecture.md | 2 +- 5 files changed, 491 insertions(+), 388 deletions(-) diff --git a/crates/engine/src/notes/revision.rs b/crates/engine/src/notes/revision.rs index 59a6c70fe..bade108da 100644 --- a/crates/engine/src/notes/revision.rs +++ b/crates/engine/src/notes/revision.rs @@ -116,134 +116,98 @@ fn skip(lines: &mut Vec, count: usize) { #[cfg(test)] mod tests { use super::*; - use crate::notes::fixtures::note; - fn snippet(content: &str) -> Note { - Note { - content: content.to_string(), - ..note() - } + fn kept(text: &str) -> DiffLine { + DiffLine::Kept { text: text.into() } } - #[test] - fn a_changed_body_is_worth_keeping() { - assert!(worth_keeping(&snippet("select 1"), &snippet("select 2"))); + fn numbered(lines: std::ops::RangeInclusive) -> String { + lines.map(|n| n.to_string()).collect::>().join("\n") } #[test] - fn an_unchanged_or_empty_body_is_not() { - assert!(!worth_keeping(&snippet("select 1"), &snippet("select 1"))); - assert!(!worth_keeping(&snippet(""), &snippet("select 1"))); + fn the_same_text_has_nothing_to_show() { + assert!(diff("a\nb", "a\nb").is_empty()); + assert!(diff("", "").is_empty()); } #[test] - fn a_checklist_keeps_nothing() { - let before = Note { - kind: NoteKind::Checklist, - ..snippet("select 1") - }; + fn a_changed_line_is_dropped_then_restored_between_three_lines_of_context() { + let current = numbered(1..=10); + let version = current.replace('5', "five"); - assert!(!worth_keeping(&before, &snippet("select 2"))); + assert_eq!( + diff(¤t, &version), + [ + DiffLine::Skipped { count: 1 }, + kept("2"), + kept("3"), + kept("4"), + DiffLine::Dropped { text: "5".into() }, + DiffLine::Restored { + text: "five".into() + }, + kept("6"), + kept("7"), + kept("8"), + DiffLine::Skipped { count: 2 }, + ] + ); } #[test] - fn a_drawing_keeps_nothing() { - let drawing = |content| Note { - kind: NoteKind::Drawing, - ..snippet(content) - }; - - assert!(!worth_keeping( - &drawing(r#"{"scene":{}}"#), - &drawing(r#"{"scene":{"objects":[]}}"#) - )); + fn a_line_only_the_kept_body_has_is_restored_and_one_only_the_current_has_dropped() { + assert_eq!( + diff("a\n", "a\nb\n"), + [kept("a"), DiffLine::Restored { text: "b".into() }] + ); + assert_eq!( + diff("a\nb\n", "a\n"), + [kept("a"), DiffLine::Dropped { text: "b".into() }] + ); } #[test] - fn a_note_keeps_its_prose() { - let note = |content| Note { - kind: NoteKind::Note, - ..snippet(content) - }; - - assert!(worth_keeping( - ¬e("## Standup"), - ¬e("## Standup, done") - )); - } + fn two_changes_far_apart_are_two_groups_with_the_run_between_folded() { + let current = numbered(1..=20); + let version = current + .replace("\n2\n", "\ntwo\n") + .replace("19", "nineteen"); - fn numbered(count: usize) -> Vec { - (1..=count).map(|n| format!("ligne {n}")).collect() - } - - fn text_of(line: &DiffLine) -> Option<&str> { - match line { - DiffLine::Kept { text } | DiffLine::Restored { text } | DiffLine::Dropped { text } => { - Some(text) - } - DiffLine::Skipped { .. } => None, - } - } - - #[test] - fn the_same_text_has_nothing_to_show() { - assert!(diff("a\nb\n", "a\nb\n").is_empty()); - } + let lines = diff(¤t, &version); - /// The typo in the middle of two hundred lines: the change and its context, the rest folded. - #[test] - fn a_change_is_shown_with_its_context_and_the_rest_is_folded() { - let current = numbered(20); - let mut version = current.clone(); - version[9] = "ligne dix".to_string(); - - let lines = diff(¤t.join("\n"), &version.join("\n")); - - assert_eq!(lines.first(), Some(&DiffLine::Skipped { count: 6 })); - assert!(lines.contains(&DiffLine::Dropped { - text: "ligne 10".to_string() - })); - assert!(lines.contains(&DiffLine::Restored { - text: "ligne dix".to_string() - })); - assert_eq!(lines.last(), Some(&DiffLine::Skipped { count: 7 })); + assert!(lines.contains(&DiffLine::Skipped { count: 10 })); assert_eq!( lines .iter() - .filter(|line| matches!(line, DiffLine::Kept { .. })) + .filter(|line| matches!(line, DiffLine::Restored { .. })) .count(), - 6 + 2 ); } - /// Restoring is what is being previewed: a line only the kept body has comes **back**. #[test] - fn a_line_only_the_version_holds_is_one_restoring_brings_back() { - let lines = diff("select 1\n", "select 1\nwhere id = 2\n"); - + fn a_line_s_ending_is_not_part_of_its_text() { assert_eq!( - lines, - vec![ - DiffLine::Kept { - text: "select 1".to_string() - }, - DiffLine::Restored { - text: "where id = 2".to_string() - }, + diff("a\r\n", "b\r\n"), + [ + DiffLine::Dropped { text: "a".into() }, + DiffLine::Restored { text: "b".into() } ] ); } #[test] - fn a_line_carries_no_line_ending() { - let lines = diff("a\r\nb\r\n", "a\r\nc\r\n"); + fn a_kept_body_is_described_by_its_size_in_characters() { + let taken_at = DateTime::::UNIX_EPOCH; - assert!(!lines.is_empty()); - assert!( - lines - .iter() - .filter_map(text_of) - .all(|text| !text.ends_with(['\n', '\r'])) + assert_eq!( + describe("r".into(), taken_at, "héllo"), + Revision { + id: "r".into(), + taken_at, + characters: 5 + } ); } } diff --git a/crates/engine/src/notes/trash.rs b/crates/engine/src/notes/trash.rs index 54b22263b..ebafc4b0d 100644 --- a/crates/engine/src/notes/trash.rs +++ b/crates/engine/src/notes/trash.rs @@ -92,7 +92,55 @@ pub fn sweep_at_startup(db: &Db) { mod tests { use super::*; use crate::attachments::model::Attachment; - use crate::notes::fixtures::{at, note}; + use crate::notes::fixtures::{NOW, at, note}; + use crate::notes::kind::NoteKind; + + #[test] + fn a_trashed_note_is_purged_thirty_days_after_it_was_trashed() { + assert_eq!(purge_at(at(NOW)), at("2026-08-24T09:00:00.000Z")); + } + + #[test] + fn a_note_expires_once_thirty_days_have_passed_to_the_millisecond() { + let now = at(NOW); + + for (deleted_at, expired) in [ + (at("2026-06-25T09:00:00.000Z"), true), + (at("2026-06-25T08:59:59.999Z"), true), + (at("2026-06-25T09:00:00.001Z"), false), + (now, false), + ] { + assert_eq!(is_expired(deleted_at, now), expired, "{deleted_at}"); + } + assert_eq!(expiry_cutoff(now), at("2026-06-25T09:00:00.000Z")); + } + + #[test] + fn a_trash_row_shows_the_first_two_lines_of_what_the_note_shows() { + let prose = Note { + kind: NoteKind::Note, + content: "# Plan\n\n- **ship**\n- tell".into(), + ..note() + }; + + let row = trashed(prose, at(NOW)); + + assert_eq!(row.preview, "Plan\n• ship"); + assert!(row.note.content.is_empty()); + assert_eq!(row.deleted_at, at(NOW)); + assert_eq!(row.purge_at, purge_at(at(NOW))); + } + + #[test] + fn a_drawing_s_trash_row_shows_its_words_not_its_scene() { + let drawing = Note { + kind: NoteKind::Drawing, + content: r#"{"scene":{"objects":[{"text":"Gateway"}]}}"#.into(), + ..note() + }; + + assert_eq!(trashed(drawing, at(NOW)).preview, "Gateway"); + } /// A note trashed long ago, with an attachment whose file sits in the library. fn a_trashed_note_with_a_file() -> (tempfile::TempDir, Db, String, std::path::PathBuf) { @@ -103,12 +151,11 @@ mod tests { let space_id = crate::spaces::store::create(&mut library, "Perso") .unwrap() .id; - let note = Note { space_id, ..note() }; - store::insert_imported(&mut library, ¬e).unwrap(); - + let trashed = Note { space_id, ..note() }; + store::insert_imported(&mut library, &trashed).unwrap(); let attachment = Attachment { id: "a-1".to_string(), - note_id: note.id.clone(), + note_id: trashed.id.clone(), file_name: "capture.png".to_string(), mime_type: "image/png".to_string(), byte_size: 3, @@ -120,9 +167,14 @@ mod tests { std::fs::write(&file, b"png").unwrap(); let (db, vault) = library.split(); attachments::store::create(db, vault, &attachment).unwrap(); - store::trash::trash(&mut library, ¬e.id, at("2020-01-01T00:00:00.000Z")).unwrap(); - - (scratch, std::sync::Mutex::new(Some(library)), note.id, file) + store::trash::trash(&mut library, &trashed.id, at("2020-01-01T00:00:00.000Z")).unwrap(); + + ( + scratch, + std::sync::Mutex::new(Some(library)), + trashed.id, + file, + ) } #[test] @@ -130,8 +182,8 @@ mod tests { let (_scratch, db, id, file) = a_trashed_note_with_a_file(); assert_eq!(purge(&db, &[id]).unwrap(), 1); - assert!(!file.exists()); + assert_eq!(purge(&db, &[]).unwrap(), 0); } #[test] @@ -141,26 +193,20 @@ mod tests { sweep_at_startup(&db); assert!(!file.exists()); + let mut connection = crate::db::lock(&db).unwrap(); assert!( - store::trash::list_trashed(&mut crate::db::lock(&db).unwrap()) + store::trash::list_trashed(&mut connection) .unwrap() .is_empty() ); } #[test] - fn a_note_deleted_today_expires_thirty_days_later() { - assert_eq!( - purge_at(at("2026-07-25T09:00:00.000Z")), - at("2026-08-24T09:00:00.000Z") - ); - } + fn the_startup_sweep_without_a_library_open_is_never_fatal() { + let locked: Db = std::sync::Mutex::new(None); - #[test] - fn the_last_day_still_belongs_to_the_user() { - let deleted = at("2026-07-25T09:00:00.000Z"); + sweep_at_startup(&locked); - assert!(!is_expired(deleted, at("2026-08-24T08:59:59.999Z"))); - assert!(is_expired(deleted, at("2026-08-24T09:00:00.000Z"))); + assert!(locked.lock().unwrap().is_none()); } } diff --git a/crates/engine/tests/notes/revisions.rs b/crates/engine/tests/notes/revisions.rs index 9bf633c8d..880e559b7 100644 --- a/crates/engine/tests/notes/revisions.rs +++ b/crates/engine/tests/notes/revisions.rs @@ -1,309 +1,296 @@ use super::*; use engine::notes::revision::{KEEP, Revision}; -use engine::notes::store::restore_revision; -use engine::notes::store::revisions::{compare, content_of, list}; +use engine::notes::store::revisions::{compare, content_of, discard_from, list}; +use engine::notes::store::{convert, restore_revision}; fn body(content: &str) -> NotePatch { NotePatch { content: Some(content.to_string()), - ..Default::default() + ..NotePatch::default() } } -fn snippet(connection: &mut Library) -> String { - let space_id = space(connection, "Personal"); - create(connection, draft(&space_id), t0()).unwrap().id +fn written(connection: &mut Library, content: &str) -> String { + let draft = NoteDraft { + content: content.to_string(), + ..snippet(&space(connection, &format!("Space of {content}"))) + }; + create(connection, draft, t0()).unwrap().id } fn kept(connection: &mut Library, id: &str) -> Vec { - let (db, vault) = connection.split(); - list(db, vault, id).unwrap() + let (connection, vault) = connection.split(); + list(connection, vault, id).unwrap() } -fn opened(connection: &mut Library, note_id: &str, revision_id: &str) -> String { - let (db, vault) = connection.split(); - content_of(db, vault, note_id, revision_id) - .unwrap() - .unwrap() +/// The kept bodies of `id`, newest first, opened. +fn bodies(connection: &mut Library, id: &str) -> Vec { + kept(connection, id) + .into_iter() + .map(|revision| { + let (connection, vault) = connection.split(); + content_of(connection, vault, id, &revision.id) + .unwrap() + .unwrap() + }) + .collect() +} + +fn edit(connection: &mut Library, id: &str, contents: &[&str]) { + for content in contents { + update(connection, id, &body(content), t1()).unwrap(); + } } -/// It is the body before the edit that is worth keeping: the version that worked. #[test] -fn an_edit_keeps_the_body_it_replaced() { +fn an_edit_of_the_body_keeps_the_body_it_replaced() { let mut connection = open_in_memory().unwrap(); - let id = snippet(&mut connection); + let id = written(&mut connection, "select 1"); - update(&mut connection, &id, &body("psql -h prod"), t1()).unwrap(); + update(&mut connection, &id, &body("select 2"), t1()).unwrap(); - let history = kept(&mut connection, &id); - assert_eq!(history.len(), 1); - assert_eq!(opened(&mut connection, &id, &history[0].id), "Contenu"); + let revisions = kept(&mut connection, &id); + assert_eq!(revisions.len(), 1); + assert_eq!(revisions[0].taken_at, t1()); + assert_eq!(revisions[0].characters, 8); + assert_eq!(bodies(&mut connection, &id), ["select 1"]); } -/// Creating a note writes nothing until the first change worth keeping, and that -/// write is the **title**: the body arrives as a second update, replacing the empty -/// string the row was born with. Without the guard, every note came out of its first -/// editing session already carrying a revision of nothing. #[test] -fn the_first_body_typed_replaces_nothing_worth_keeping() { +fn an_edit_that_leaves_the_body_as_it_was_keeps_nothing() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let id = create( - &mut connection, - NoteDraft { - content: String::new(), - ..draft(&space_id) - }, - t0(), - ) - .unwrap() - .id; + let id = written(&mut connection, "select 1"); + let title = NotePatch { + title: Some("Renamed".to_string()), + ..NotePatch::default() + }; + update(&mut connection, &id, &title, t1()).unwrap(); update(&mut connection, &id, &body("select 1"), t1()).unwrap(); assert!(kept(&mut connection, &id).is_empty()); - - // And the one after it is kept, which is the whole point. - update(&mut connection, &id, &body("select 2"), t1()).unwrap(); - assert_eq!(kept(&mut connection, &id).len(), 1); } -/// The front end already computes what moved, and the back end agrees: a -/// title-only edit stores no body. #[test] -fn a_title_only_edit_keeps_nothing() { +fn the_first_body_of_an_empty_note_keeps_nothing() { let mut connection = open_in_memory().unwrap(); - let id = snippet(&mut connection); + let id = written(&mut connection, ""); + + update(&mut connection, &id, &body("select 1"), t1()).unwrap(); + + assert!(kept(&mut connection, &id).is_empty()); +} - update( +/// A checklist's items and a drawing's scene are no body to compare: both kinds keep nothing. +#[test] +fn a_checklist_or_a_drawing_keeps_nothing() { + let mut connection = open_in_memory().unwrap(); + let space_id = space(&mut connection, "Work"); + let list_id = create( &mut connection, - &id, - &NotePatch { - title: Some("Un autre titre".to_string()), - ..Default::default() - }, - t1(), + checklist(&space_id, vec![item("a", false)]), + t0(), ) - .unwrap(); + .unwrap() + .id; + let drawing = NoteDraft { + kind: NoteKind::Drawing, + content: r#"{"scene":{"objects":[]}}"#.to_string(), + ..snippet(&space_id) + }; + let drawing_id = create(&mut connection, drawing, t0()).unwrap().id; + + let items = NotePatch { + items: Some(vec![item("b", true)]), + ..NotePatch::default() + }; + update(&mut connection, &list_id, &items, t1()).unwrap(); + edit( + &mut connection, + &drawing_id, + &[r#"{"scene":{"objects":[{}]}}"#], + ); - assert!(kept(&mut connection, &id).is_empty()); + assert!(kept(&mut connection, &list_id).is_empty()); + assert!(kept(&mut connection, &drawing_id).is_empty()); } -/// The editor commits on blur *and* on every closing path, so one session writes -/// the same body several times. Without the skip, each write would push a duplicate -/// and rotate a genuinely different version out of the cap. #[test] -fn writing_the_same_body_again_keeps_one_copy_of_it() { +fn a_change_of_kind_keeps_the_body_it_rewrites() { let mut connection = open_in_memory().unwrap(); - let id = snippet(&mut connection); + let id = written(&mut connection, "- a\n- b"); - update(&mut connection, &id, &body("une"), t1()).unwrap(); - update(&mut connection, &id, &body("deux"), t1()).unwrap(); - update(&mut connection, &id, &body("deux"), t1()).unwrap(); + convert(&mut connection, &id, NoteKind::Checklist, t1()).unwrap(); - // "Contenu" then "une": the third write moved nothing, and the second was - // already the newest kept body. - let history = kept(&mut connection, &id); - assert_eq!(history.len(), 2); + assert_eq!(bodies(&mut connection, &id), ["- a\n- b"]); } -/// A count and not a time window: a body runs to tens of kilobytes. +/// A conversion undone, then made again, would push the same body twice and rotate a +/// different version out of the cap. #[test] -fn only_the_last_few_are_kept() { +fn a_body_already_the_newest_kept_is_not_kept_twice() { let mut connection = open_in_memory().unwrap(); - let id = snippet(&mut connection); - - for step in 0..KEEP + 5 { - update( - &mut connection, - &id, - &body(&format!("version {step}")), - t1(), - ) - .unwrap(); - } - - assert_eq!(kept(&mut connection, &id).len(), KEEP); + let id = written(&mut connection, "- a\n- b"); + let undo = NotePatch { + kind: Some(NoteKind::Snippet), + content: Some("- a\n- b".to_string()), + items: Some(Vec::new()), + ..NotePatch::default() + }; + + convert(&mut connection, &id, NoteKind::Checklist, t1()).unwrap(); + update(&mut connection, &id, &undo, t1()).unwrap(); + convert(&mut connection, &id, NoteKind::Checklist, t1()).unwrap(); + + assert_eq!(bodies(&mut connection, &id), ["- a\n- b"]); } #[test] -fn a_kept_body_goes_back_onto_the_note() { +fn the_history_keeps_the_newest_bodies_up_to_its_cap() { let mut connection = open_in_memory().unwrap(); - let id = snippet(&mut connection); - update(&mut connection, &id, &body("casse"), t1()).unwrap(); - let history = kept(&mut connection, &id); + let id = written(&mut connection, "v0"); + let versions: Vec = (1..=KEEP + 5).map(|n| format!("v{n}")).collect(); + let typed: Vec<&str> = versions.iter().map(String::as_str).collect(); - let note = restore_revision(&mut connection, &id, &history[0].id).unwrap(); + edit(&mut connection, &id, &typed); - assert_eq!(note.content, "Contenu"); + let history = bodies(&mut connection, &id); + assert_eq!(history.len(), KEEP); assert_eq!( - by_ids(&mut connection, &[id]).unwrap()[0].content, - "Contenu" + history.first().map(String::as_str), + Some(format!("v{}", KEEP + 4).as_str()) ); + assert_eq!(history.last().map(String::as_str), Some("v5")); } -/// The canvas sorts on `updated_at`, and putting something back is not editing it -/// — the same line `restore_many`, `restore_placements` and `untag_many` hold. +/// The editor commits title, source and body back to back: two revisions can share a +/// millisecond, and the newest must still come first. #[test] -fn putting_a_body_back_does_not_float_the_note_to_the_top() { +fn bodies_kept_in_the_same_millisecond_list_newest_first() { let mut connection = open_in_memory().unwrap(); - let id = snippet(&mut connection); - update(&mut connection, &id, &body("casse"), t1()).unwrap(); - let before = by_ids(&mut connection, std::slice::from_ref(&id)).unwrap()[0].updated_at; - let history = kept(&mut connection, &id); + let id = written(&mut connection, "first"); - restore_revision(&mut connection, &id, &history[0].id).unwrap(); + edit(&mut connection, &id, &["second", "third", "fourth"]); - assert_eq!( - by_ids(&mut connection, &[id]).unwrap()[0].updated_at, - before - ); + assert_eq!(bodies(&mut connection, &id), ["third", "second", "first"]); } -/// Going back, not adding a row: nothing of the replaced body stays in the history. #[test] -fn a_restore_keeps_nothing_of_what_it_replaced() { +fn a_kept_body_is_not_readable_in_the_column_it_sits_in() { let mut connection = open_in_memory().unwrap(); - let id = snippet(&mut connection); - update(&mut connection, &id, &body("casse"), t1()).unwrap(); - let history = kept(&mut connection, &id); + let id = written(&mut connection, "secret token"); + edit(&mut connection, &id, &["rotated"]); - restore_revision(&mut connection, &id, &history[0].id).unwrap(); + let raw: Vec = note_revisions::table + .select(note_revisions::content) + .load(connection.db()) + .unwrap(); - assert!(kept(&mut connection, &id).is_empty()); + assert_eq!(raw.len(), 1); + assert!(!raw[0].contains("secret")); } -/// A → B → C, back to B: C is gone, and so is B from the list, since it is the text now. #[test] -fn going_back_drops_the_version_and_everything_newer() { +fn a_kept_body_is_reached_through_its_own_note_only() { let mut connection = open_in_memory().unwrap(); - let id = snippet(&mut connection); - update(&mut connection, &id, &body("B"), t1()).unwrap(); - update(&mut connection, &id, &body("C"), t1()).unwrap(); - let history = kept(&mut connection, &id); - assert_eq!(opened(&mut connection, &id, &history[0].id), "B"); - - let note = restore_revision(&mut connection, &id, &history[0].id).unwrap(); - - assert_eq!(note.content, "B"); - let after = kept(&mut connection, &id); - assert_eq!(after.len(), 1); - assert_eq!(opened(&mut connection, &id, &after[0].id), "Contenu"); + let id = written(&mut connection, "mine"); + let other = written(&mut connection, "theirs"); + edit(&mut connection, &id, &["mine, edited"]); + let revision = kept(&mut connection, &id)[0].id.clone(); + + let (db, vault) = connection.split(); + assert_eq!(content_of(db, vault, &other, &revision).unwrap(), None); + assert_eq!(compare(db, vault, &other, &revision).unwrap(), None); + assert_eq!(content_of(db, vault, &id, "missing").unwrap(), None); } -/// Going back further takes the newer ones with it, and leaves the older ones. #[test] -fn going_back_to_the_oldest_leaves_nothing_newer() { +fn a_kept_body_is_compared_with_the_current_one() { let mut connection = open_in_memory().unwrap(); - let id = snippet(&mut connection); - update(&mut connection, &id, &body("B"), t1()).unwrap(); - update(&mut connection, &id, &body("C"), t1()).unwrap(); - let history = kept(&mut connection, &id); + let id = written(&mut connection, "before"); + edit(&mut connection, &id, &["after"]); + let revision = kept(&mut connection, &id)[0].id.clone(); - restore_revision(&mut connection, &id, &history[1].id).unwrap(); + let (db, vault) = connection.split(); - assert!(kept(&mut connection, &id).is_empty()); assert_eq!( - by_ids(&mut connection, &[id]).unwrap()[0].content, - "Contenu" + compare(db, vault, &id, &revision).unwrap(), + Some(("after".to_string(), "before".to_string())) ); } -/// The preview compares the kept body with the text it would replace. #[test] -fn the_preview_compares_the_version_with_the_current_text() { +fn a_trashed_note_has_nothing_to_compare() { let mut connection = open_in_memory().unwrap(); - let id = snippet(&mut connection); - update(&mut connection, &id, &body("casse"), t1()).unwrap(); - let history = kept(&mut connection, &id); + let id = written(&mut connection, "before"); + edit(&mut connection, &id, &["after"]); + let revision = kept(&mut connection, &id)[0].id.clone(); + trash(&mut connection, &id, t1()).unwrap(); let (db, vault) = connection.split(); - let pair = compare(db, vault, &id, &history[0].id).unwrap(); - assert_eq!(pair, Some(("casse".to_string(), "Contenu".to_string()))); + assert_eq!(compare(db, vault, &id, &revision).unwrap(), None); } #[test] -fn a_revision_of_another_note_cannot_be_previewed() { +fn restoring_puts_a_body_back_and_forgets_it_and_every_newer_one() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let mine = create(&mut connection, draft(&space_id), t0()).unwrap().id; - let theirs = create(&mut connection, draft(&space_id), t0()).unwrap().id; - update(&mut connection, &theirs, &body("le leur"), t1()).unwrap(); - let history = kept(&mut connection, &theirs); + let id = written(&mut connection, "A"); + edit(&mut connection, &id, &["B", "C", "D"]); + let revisions = kept(&mut connection, &id); + let b = revisions[1].id.clone(); - let (db, vault) = connection.split(); - assert_eq!(compare(db, vault, &mine, &history[0].id).unwrap(), None); + let restored = restore_revision(&mut connection, &id, &b).unwrap(); + + assert_eq!(restored.content, "B"); + assert_eq!(get(&mut connection, &id).unwrap().content, "B"); + assert_eq!(bodies(&mut connection, &id), ["A"]); } -/// An id comes from the front end: one note's history must not be reachable -/// through another note. +/// Putting something back is not editing it, and the canvas sorts on that column. #[test] -fn a_revision_of_another_note_is_not_reachable() { +fn restoring_leaves_the_date_of_the_last_edit() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let mine = create(&mut connection, draft(&space_id), t0()).unwrap().id; - let theirs = create(&mut connection, draft(&space_id), t0()).unwrap().id; - update(&mut connection, &theirs, &body("le leur"), t1()).unwrap(); - let history = kept(&mut connection, &theirs); + let id = written(&mut connection, "A"); + edit(&mut connection, &id, &["B"]); + let revision = kept(&mut connection, &id)[0].id.clone(); - let refused = restore_revision(&mut connection, &mine, &history[0].id); + restore_revision(&mut connection, &id, &revision).unwrap(); - assert!(matches!(refused, Err(StorageError::RevisionNotFound(_)))); + assert_eq!(get(&mut connection, &id).unwrap().updated_at, t1()); } -/// Said out loud rather than shipped silently: a checklist's items live in -/// `note_items`, a second table to snapshot and a two-step restore. Half the note -/// kinds get nothing from this first version. #[test] -fn a_checklist_keeps_nothing_yet() { +fn restoring_what_is_not_kept_fails_by_name() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let id = create( - &mut connection, - NoteDraft { - kind: NoteKind::Checklist, - content: String::new(), - items: vec![ChecklistItem { - text: "un item".to_string(), - done: false, - }], - ..draft(&space_id) - }, - t0(), - ) - .unwrap() - .id; - - update(&mut connection, &id, &body("un corps"), t1()).unwrap(); - - assert!(kept(&mut connection, &id).is_empty()); + let id = written(&mut connection, "A"); + + assert!(matches!( + restore_revision(&mut connection, &id, "missing"), + Err(StorageError::RevisionNotFound(revision)) if revision == "missing" + )); + assert!(matches!( + restore_revision(&mut connection, "gone", "missing"), + Err(StorageError::NoteNotFound(note)) if note == "gone" + )); } -/// A history of every body in plaintext beside a sealed library would undo the -/// encryption entirely. #[test] -fn a_kept_body_is_not_readable_in_the_column_it_sits_in() { +fn forgetting_from_a_body_not_kept_forgets_nothing() { let mut connection = open_in_memory().unwrap(); - let id = snippet(&mut connection); - update(&mut connection, &id, &body("psql -h prod"), t1()).unwrap(); + let id = written(&mut connection, "A"); + edit(&mut connection, &id, &["B"]); - let stored: Vec = note_revisions::table - .select(note_revisions::content) - .load(connection.db()) - .unwrap(); + discard_from(connection.db(), &id, "missing").unwrap(); - assert_eq!(stored.len(), 1); - assert!(!stored[0].contains("Contenu")); + assert_eq!(bodies(&mut connection, &id), ["A"]); } -/// Deleting a note takes its history with it: `ON DELETE CASCADE`, which is inert -/// without `PRAGMA foreign_keys` — set per connection in `db::configure`. #[test] -fn purging_a_note_takes_its_history_with_it() { +fn a_purged_note_takes_its_history_with_it() { let mut connection = open_in_memory().unwrap(); - let id = snippet(&mut connection); - update(&mut connection, &id, &body("psql -h prod"), t1()).unwrap(); + let id = written(&mut connection, "A"); + edit(&mut connection, &id, &["B"]); trash(&mut connection, &id, t1()).unwrap(); purge(&mut connection, std::slice::from_ref(&id)).unwrap(); @@ -314,3 +301,40 @@ fn purging_a_note_takes_its_history_with_it() { .unwrap(); assert_eq!(left, 0); } + +#[test] +fn a_kept_body_with_an_unreadable_date_fails_the_listing_by_its_field() { + let mut connection = open_in_memory().unwrap(); + let id = written(&mut connection, "A"); + edit(&mut connection, &id, &["B"]); + diesel::update(note_revisions::table) + .set(note_revisions::taken_at.eq("not a date")) + .execute(connection.db()) + .unwrap(); + + let (db, vault) = connection.split(); + + assert!(matches!( + list(db, vault, &id), + Err(StorageError::CorruptRow { + field: "takenAt", + .. + }) + )); +} + +#[test] +fn a_note_s_prose_is_kept_as_a_snippet_s_body_is() { + let mut connection = open_in_memory().unwrap(); + let space_id = space(&mut connection, "Work"); + let prose = NoteDraft { + kind: NoteKind::Note, + content: "**First** draft".to_string(), + ..snippet(&space_id) + }; + let id = create(&mut connection, prose, t0()).unwrap().id; + + edit(&mut connection, &id, &["Second draft"]); + + assert_eq!(bodies(&mut connection, &id), ["**First** draft"]); +} diff --git a/crates/engine/tests/notes/trash.rs b/crates/engine/tests/notes/trash.rs index 1d3e5aec7..dcdd3b87e 100644 --- a/crates/engine/tests/notes/trash.rs +++ b/crates/engine/tests/notes/trash.rs @@ -1,120 +1,189 @@ use super::*; +use engine::notes::store::trash::{trash_many, trashed_ids}; +use engine::notes::trash::RETENTION; + +fn notes(connection: &mut Library, count: usize) -> Vec { + let space_id = space(connection, "Work"); + (0..count) + .map(|_| create(connection, draft(&space_id), t0()).unwrap().id) + .collect() +} + +fn ids_of(trashed: &[(Note, chrono::DateTime)]) -> Vec { + trashed.iter().map(|(note, _)| note.id.clone()).collect() +} #[test] -fn deleting_takes_the_note_off_the_canvas_without_destroying_it() { +fn a_trashed_note_leaves_every_read_and_waits_in_the_trash() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let created = create(&mut connection, draft(&space_id), t0()).unwrap(); + let ids = notes(&mut connection, 2); - trash(&mut connection, &created.id, t1()).unwrap(); - - assert!(list(&mut connection).unwrap().is_empty()); - let kept_tags = note_tags::table - .count() - .get_result::(connection.db()) - .unwrap(); - assert_eq!(kept_tags, 2); + trash(&mut connection, &ids[0], t1()).unwrap(); + assert!(matches!( + get(&mut connection, &ids[0]), + Err(StorageError::NoteNotFound(_)) + )); + assert_eq!( + list(&mut connection) + .unwrap() + .iter() + .map(|note| note.id.clone()) + .collect::>(), + [ids[1].clone()] + ); let trashed = list_trashed(&mut connection).unwrap(); - assert_eq!(trashed.len(), 1); - assert_eq!(trashed[0].0.id, created.id); + assert_eq!(ids_of(&trashed), [ids[0].clone()]); assert_eq!(trashed[0].1, t1()); + let mut tags = trashed[0].0.tags.clone(); + tags.sort(); + assert_eq!(tags, ["api", "auth"]); } #[test] -fn a_restored_note_comes_back_whole() { +fn trashing_what_is_gone_or_trashed_already_fails_by_name() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let created = create(&mut connection, draft(&space_id), t0()).unwrap(); - trash(&mut connection, &created.id, t1()).unwrap(); + let ids = notes(&mut connection, 1); + trash(&mut connection, &ids[0], t1()).unwrap(); + + for id in [ids[0].as_str(), "missing"] { + assert!(matches!( + trash(&mut connection, id, t1()), + Err(StorageError::NoteNotFound(found)) if found == id + )); + } +} +#[test] +fn trashing_many_answers_what_moved_and_skips_what_could_not() { + let mut connection = open_in_memory().unwrap(); + let ids = notes(&mut connection, 2); + trash(&mut connection, &ids[0], t0()).unwrap(); + let asked = vec![ids[0].clone(), ids[1].clone(), "missing".to_string()]; + + assert_eq!(trash_many(&mut connection, &asked, t1()).unwrap(), 1); + assert_eq!(trash_many(&mut connection, &[], t1()).unwrap(), 0); + let trashed = list_trashed(&mut connection).unwrap(); assert_eq!( - restore_many(&mut connection, std::slice::from_ref(&created.id)).unwrap(), - 1 + trashed.iter().map(|(_, at)| *at).collect::>(), + [t1(), t0()] ); - - let listed = list(&mut connection).unwrap(); - assert_eq!(listed.len(), 1); - assert_eq!(listed[0].tags, ["api", "auth"]); - assert_eq!(listed[0].updated_at, t0()); } #[test] -fn a_trashed_note_is_no_longer_editable() { +fn restoring_brings_a_note_back_as_it_was_and_counts_only_what_came_back() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let created = create(&mut connection, draft(&space_id), t0()).unwrap(); - trash(&mut connection, &created.id, t1()).unwrap(); - - let error = update(&mut connection, &created.id, &NotePatch::default(), t1()).unwrap_err(); - - assert!(matches!(error, StorageError::NoteNotFound(_))); + let ids = notes(&mut connection, 2); + trash(&mut connection, &ids[0], t1()).unwrap(); + let asked = vec![ids[0].clone(), ids[1].clone()]; + + assert_eq!(restore_many(&mut connection, &asked).unwrap(), 1); + assert_eq!(restore_many(&mut connection, &[]).unwrap(), 0); + let back = get(&mut connection, &ids[0]).unwrap(); + assert_eq!(back.updated_at, t0()); + assert!(list_trashed(&mut connection).unwrap().is_empty()); } #[test] -fn purging_removes_the_note_and_its_tags_for_good() { +fn the_trash_lists_the_latest_deletion_first_then_by_id() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let created = create(&mut connection, draft(&space_id), t0()).unwrap(); - trash(&mut connection, &created.id, t1()).unwrap(); - - assert_eq!( - purge(&mut connection, std::slice::from_ref(&created.id)).unwrap(), - 1 - ); - - assert!(list_trashed(&mut connection).unwrap().is_empty()); - let orphan_tags = note_tags::table - .count() - .get_result::(connection.db()) - .unwrap(); - assert_eq!(orphan_tags, 0); + let ids = notes(&mut connection, 3); + trash(&mut connection, &ids[0], t0()).unwrap(); + trash(&mut connection, &ids[1], t1()).unwrap(); + trash(&mut connection, &ids[2], t1()).unwrap(); + let mut latest = vec![ids[1].clone(), ids[2].clone()]; + latest.sort(); + latest.push(ids[0].clone()); + + assert_eq!(ids_of(&list_trashed(&mut connection).unwrap()), latest); + let mut every = trashed_ids(&mut connection).unwrap(); + every.sort(); + let mut expected = ids.clone(); + expected.sort(); + assert_eq!(every, expected); } #[test] -fn a_note_still_on_the_canvas_cannot_be_purged() { +fn a_note_expires_thirty_days_after_its_deletion_to_the_millisecond() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let created = create(&mut connection, draft(&space_id), t0()).unwrap(); + let ids = notes(&mut connection, 3); + let edge = t0() - RETENTION; + trash(&mut connection, &ids[0], edge).unwrap(); + trash( + &mut connection, + &ids[1], + edge + chrono::TimeDelta::milliseconds(1), + ) + .unwrap(); assert_eq!( - purge(&mut connection, std::slice::from_ref(&created.id)).unwrap(), - 0 + expired_ids(&mut connection, t0()).unwrap(), + [ids[0].clone()] ); - assert_eq!(list(&mut connection).unwrap().len(), 1); } #[test] -fn only_notes_past_the_retention_are_reported_as_expired() { +fn a_purge_erases_only_trashed_notes_with_their_tags_items_and_fields() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let old = create(&mut connection, draft(&space_id), t0()).unwrap(); - let recent = create(&mut connection, draft(&space_id), t0()).unwrap(); - trash(&mut connection, &old.id, t0()).unwrap(); - trash(&mut connection, &recent.id, at("2026-08-20T09:00:00.000Z")).unwrap(); - - let expired = expired_ids(&mut connection, at("2026-08-25T09:00:00.000Z")).unwrap(); - - assert_eq!(expired, [old.id]); + let space_id = space(&mut connection, "Work"); + let list_id = create( + &mut connection, + checklist(&space_id, vec![item("a", false)]), + t0(), + ) + .unwrap() + .id; + let live = create(&mut connection, templated(&space_id), t0()) + .unwrap() + .id; + set_placeholder_values(&mut connection, &live, &values(&[("host", "db")])).unwrap(); + trash(&mut connection, &list_id, t1()).unwrap(); + + let purged = purge(&mut connection, &[list_id.clone(), live.clone()]).unwrap(); + + assert_eq!(purged, 1); + assert_eq!(purge(&mut connection, &[]).unwrap(), 0); + assert!(list_trashed(&mut connection).unwrap().is_empty()); + let items: i64 = note_items::table + .count() + .get_result(connection.db()) + .unwrap(); + let tags: Vec = note_tags::table + .select(note_tags::note_id) + .load(connection.db()) + .unwrap(); + assert_eq!(items, 0); + assert!(tags.iter().all(|note_id| *note_id == live)); + assert_eq!(get(&mut connection, &live).unwrap().id, live); } #[test] -fn deleting_an_unknown_note_reports_an_error() { +fn a_trashed_note_with_an_unreadable_deletion_date_fails_the_trash_by_its_field() { let mut connection = open_in_memory().unwrap(); + let ids = notes(&mut connection, 1); + trash(&mut connection, &ids[0], t1()).unwrap(); + diesel::update(notes_table::table) + .set(notes_table::deleted_at.eq("not a date")) + .execute(connection.db()) + .unwrap(); - let error = trash(&mut connection, "unknown", t1()).unwrap_err(); - - assert!(matches!(error, StorageError::NoteNotFound(_))); + assert!(matches!( + list_trashed(&mut connection), + Err(StorageError::CorruptRow { + field: "deletedAt", + .. + }) + )); } #[test] -fn deleting_the_same_note_twice_reports_an_error_rather_than_a_silent_ok() { +fn a_trashed_note_can_no_longer_be_edited() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let created = create(&mut connection, draft(&space_id), t0()).unwrap(); - trash(&mut connection, &created.id, t1()).unwrap(); - - let error = trash(&mut connection, &created.id, t1()).unwrap_err(); + let ids = notes(&mut connection, 1); + trash(&mut connection, &ids[0], t1()).unwrap(); - assert!(matches!(error, StorageError::NoteNotFound(_))); + assert!(matches!( + update(&mut connection, &ids[0], &NotePatch::default(), t1()), + Err(StorageError::NoteNotFound(_)) + )); } diff --git a/docs/architecture.md b/docs/architecture.md index 7fbdc9ffc..d6e7996b8 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -5316,7 +5316,7 @@ note. | exports | **out** | revisions in the bundle would inflate it by a factor of the cap; a note restored elsewhere arriving without its history is the accepted cost | ⚠️ Both omissions are held by a test rather than left to be noticed — -`a_checklist_keeps_nothing_yet` and `a_bundle_carries_no_history_of_the_bodies_it_holds`. +`a_checklist_or_a_drawing_keeps_nothing` and `a_bundle_carries_no_history_of_the_bodies_it_holds`. Half the note kinds get nothing from this first version, and that is said out loud rather than shipped silently. From 11e6e49447813477b1a38426614dac2cb8d12219 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:44:36 +0100 Subject: [PATCH 16/95] Notes SQL read: unit tests rewritten for what each criterion keeps (#1737) What each criterion keeps, facets of the space, and the read path end to end. --- crates/engine/tests/notes/main.rs | 11 +- crates/engine/tests/notes/queries.rs | 1064 +++++++++----------------- 2 files changed, 381 insertions(+), 694 deletions(-) diff --git a/crates/engine/tests/notes/main.rs b/crates/engine/tests/notes/main.rs index c72988403..9c677c6e7 100644 --- a/crates/engine/tests/notes/main.rs +++ b/crates/engine/tests/notes/main.rs @@ -11,9 +11,7 @@ use engine::error::StorageError; use engine::notes::checklist::ChecklistItem; use engine::notes::kind::NoteKind; use engine::notes::language::Language; -use engine::notes::model::{ - DisplayNote, Note, NoteDraft, NoteLifecycle, NotePatch, NotePriority, PREVIEW_LINES, -}; +use engine::notes::model::{Note, NoteDraft, NoteLifecycle, NotePatch, NotePriority}; use engine::notes::priority::Priority; use engine::notes::store::trash::{expired_ids, list_trashed, purge, restore_many, trash}; use engine::notes::store::{ @@ -137,13 +135,6 @@ fn all_notes() -> NotesQuery { } } -fn matched_ids(view: &NotesView) -> Vec { - view.sections - .iter() - .flat_map(|section| section.cards.iter().map(|card| card.id.clone())) - .collect() -} - fn tagged(space_id: &str, tags: &[&str]) -> NoteDraft { NoteDraft { tags: tags.iter().copied().map(String::from).collect(), diff --git a/crates/engine/tests/notes/queries.rs b/crates/engine/tests/notes/queries.rs index 33cd5da55..215d40ac9 100644 --- a/crates/engine/tests/notes/queries.rs +++ b/crates/engine/tests/notes/queries.rs @@ -1,814 +1,510 @@ use super::*; +use engine::notes::model::PREVIEW_LINES; +use engine::notes::view::FacetCount; -#[test] -fn a_query_without_criteria_returns_every_note() { - let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - create(&mut connection, draft(&space_id), t0()).unwrap(); - - let view = query(&mut connection, &all_notes()).unwrap(); - - assert_eq!(view.matched, 1); - assert!(!view.is_filtering); +fn fetched(connection: &mut Library, request: &NotesQuery) -> Vec { + fetch(connection, request) + .unwrap() + .0 + .into_iter() + .map(|note| note.title) + .collect() } -#[test] -fn the_space_filter_excludes_the_other_spaces() { - let mut connection = open_in_memory().unwrap(); - let here = space(&mut connection, "Personal"); - let elsewhere = space(&mut connection, "Boulot"); - let kept = create(&mut connection, draft(&here), t0()).unwrap(); - create(&mut connection, draft(&elsewhere), t0()).unwrap(); - - let view = query( - &mut connection, - &NotesQuery { - space_id: Some(here), - ..all_notes() - }, - ) - .unwrap(); - - assert_eq!(matched_ids(&view), [kept.id]); +fn titled(space_id: &str, title: &str) -> NoteDraft { + NoteDraft { + title: title.to_string(), + ..draft(space_id) + } } -#[test] -fn no_space_means_every_space_rather_than_none() { - let mut connection = open_in_memory().unwrap(); - let here = space(&mut connection, "Personal"); - let elsewhere = space(&mut connection, "Boulot"); - create(&mut connection, draft(&here), t0()).unwrap(); - create(&mut connection, draft(&elsewhere), t0()).unwrap(); - - let view = query(&mut connection, &all_notes()).unwrap(); +fn written(connection: &mut Library, draft: NoteDraft, at_: &str) -> String { + create(connection, draft, at(at_)).unwrap().id +} - assert_eq!(view.matched, 2); +fn in_space(space_id: &str) -> NotesQuery { + NotesQuery { + space_id: Some(space_id.to_string()), + ..all_notes() + } } #[test] -fn the_pinned_filter_keeps_only_pinned_notes() { +fn a_query_reads_the_live_notes_edited_last_first() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let pinned = create( + let space_id = space(&mut connection, "Work"); + written( &mut connection, - NoteDraft { - pinned: true, - ..draft(&space_id) - }, - t0(), - ) - .unwrap(); - create(&mut connection, draft(&space_id), t0()).unwrap(); - - let view = query( + titled(&space_id, "old"), + "2026-07-01T00:00:00.000Z", + ); + written( &mut connection, - &NotesQuery { - filter: NoteFilter::Pinned, - ..all_notes() - }, - ) - .unwrap(); + titled(&space_id, "new"), + "2026-07-20T00:00:00.000Z", + ); + let gone = written( + &mut connection, + titled(&space_id, "gone"), + "2026-07-24T00:00:00.000Z", + ); + trash(&mut connection, &gone, t1()).unwrap(); - assert_eq!(matched_ids(&view), [pinned.id]); + assert_eq!(fetched(&mut connection, &all_notes()), ["new", "old"]); } #[test] -fn the_untriaged_filter_keeps_only_expiring_notes() { +fn notes_edited_in_the_same_instant_come_by_id() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let expiring = create( - &mut connection, - NoteDraft { - lifecycle: NoteLifecycle::Expires { - at: at("2026-08-01T00:00:00.000Z"), - }, - ..draft(&space_id) - }, - t0(), - ) - .unwrap(); - create(&mut connection, draft(&space_id), t0()).unwrap(); + let space_id = space(&mut connection, "Work"); + let mut ids: Vec = (0..4) + .map(|n| { + written( + &mut connection, + titled(&space_id, &n.to_string()), + "2026-07-20T00:00:00.000Z", + ) + }) + .collect(); + ids.sort(); - let view = query( - &mut connection, - &NotesQuery { - filter: NoteFilter::Untriaged, - ..all_notes() - }, - ) - .unwrap(); + let read: Vec = fetch(&mut connection, &all_notes()) + .unwrap() + .0 + .into_iter() + .map(|note| note.id) + .collect(); - assert_eq!(matched_ids(&view), [expiring.id]); + assert_eq!(read, ids); } #[test] -fn a_quick_filter_alone_does_not_switch_to_results_mode() { +fn a_space_keeps_its_own_notes_and_none_keeps_every_space_s() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - create(&mut connection, draft(&space_id), t0()).unwrap(); - - let view = query( + let work = space(&mut connection, "Work"); + let home = space(&mut connection, "Home"); + written( &mut connection, - &NotesQuery { - filter: NoteFilter::Pinned, - ..all_notes() - }, - ) - .unwrap(); + titled(&work, "work"), + "2026-07-01T00:00:00.000Z", + ); + written( + &mut connection, + titled(&home, "home"), + "2026-07-02T00:00:00.000Z", + ); - assert!(!view.is_filtering); + assert_eq!(fetched(&mut connection, &in_space(&work)), ["work"]); + assert_eq!(fetched(&mut connection, &all_notes()), ["home", "work"]); } #[test] -fn the_search_matches_the_title_the_content_and_the_tags() { +fn an_opened_folder_keeps_the_notes_filed_under_it_at_any_depth() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let by_title = create( - &mut connection, - NoteDraft { - title: "Script de deploiement".to_string(), - content: String::new(), - tags: Vec::new(), - ..draft(&space_id) - }, - t0(), - ) - .unwrap(); - let by_content = create( - &mut connection, - NoteDraft { - title: String::new(), - content: "kubectl rollout".to_string(), - tags: Vec::new(), - ..draft(&space_id) - }, - t0(), - ) - .unwrap(); - let by_tag = create(&mut connection, tagged(&space_id, &["urgent"]), t0()).unwrap(); - - for (needle, expected) in [ - ("deploiement", &by_title), - ("rollout", &by_content), - ("urgent", &by_tag), + let space_id = space(&mut connection, "Work"); + let top = engine::folders::store::create(&mut connection, &space_id, None, "Top", t0()) + .unwrap() + .id; + let below = + engine::folders::store::create(&mut connection, &space_id, Some(&top), "Below", t0()) + .unwrap() + .id; + let beside = engine::folders::store::create(&mut connection, &space_id, None, "Beside", t0()) + .unwrap() + .id; + for (folder, title, instant) in [ + (Some(&top), "top", "2026-07-03T00:00:00.000Z"), + (Some(&below), "below", "2026-07-02T00:00:00.000Z"), + (Some(&beside), "beside", "2026-07-01T00:00:00.000Z"), + (None, "loose", "2026-07-04T00:00:00.000Z"), ] { - let view = query( - &mut connection, - &NotesQuery { - search: needle.to_string(), - ..all_notes() - }, - ) - .unwrap(); - assert_eq!( - matched_ids(&view), - [expected.id.as_str()], - "needle: {needle}" - ); + let filed = NoteDraft { + folder_id: folder.cloned(), + ..titled(&space_id, title) + }; + written(&mut connection, filed, instant); } + let opened = NotesQuery { + folder_id: Some(top), + ..in_space(&space_id) + }; + + assert_eq!(fetched(&mut connection, &opened), ["top", "below"]); } +/// Past the bind limit the sub-tree is kept after the read rather than bound. #[test] -fn the_search_ignores_case_beyond_ascii() { +fn a_folder_with_more_sub_folders_than_can_be_bound_still_keeps_its_notes() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - create( - &mut connection, - NoteDraft { - title: "Étape de migration".to_string(), - ..draft(&space_id) - }, - t0(), - ) - .unwrap(); - - let view = query( - &mut connection, - &NotesQuery { - search: "étape".to_string(), - ..all_notes() - }, - ) - .unwrap(); + let space_id = space(&mut connection, "Work"); + let top = engine::folders::store::create(&mut connection, &space_id, None, "Top", t0()) + .unwrap() + .id; + let mut last = top.clone(); + for n in 0..500 { + last = engine::folders::store::create( + &mut connection, + &space_id, + Some(&top), + &format!("f{n}"), + t0(), + ) + .unwrap() + .id; + } + let deep = NoteDraft { + folder_id: Some(last), + ..titled(&space_id, "deep") + }; + written(&mut connection, deep, "2026-07-02T00:00:00.000Z"); + written( + &mut connection, + titled(&space_id, "loose"), + "2026-07-03T00:00:00.000Z", + ); + let opened = NotesQuery { + folder_id: Some(top), + ..in_space(&space_id) + }; - assert_eq!(view.matched, 1); + assert_eq!(fetched(&mut connection, &opened), ["deep"]); } #[test] -fn a_blank_search_is_not_a_search() { +fn the_quick_filter_keeps_the_pinned_or_the_notes_with_a_deadline() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - create(&mut connection, draft(&space_id), t0()).unwrap(); + let space_id = space(&mut connection, "Work"); + let pinned = NoteDraft { + pinned: true, + ..titled(&space_id, "pinned") + }; + let expiring = NoteDraft { + lifecycle: NoteLifecycle::Expires { at: t1() }, + ..titled(&space_id, "expiring") + }; + written(&mut connection, pinned, "2026-07-01T00:00:00.000Z"); + written(&mut connection, expiring, "2026-07-02T00:00:00.000Z"); + written( + &mut connection, + titled(&space_id, "plain"), + "2026-07-03T00:00:00.000Z", + ); - let view = query( - &mut connection, - &NotesQuery { - search: " ".to_string(), + for (filter, kept) in [ + (NoteFilter::Pinned, "pinned"), + (NoteFilter::Untriaged, "expiring"), + ] { + let request = NotesQuery { + filter, ..all_notes() - }, - ) - .unwrap(); - - assert!(!view.is_filtering); - assert_eq!(view.matched, 1); + }; + assert_eq!(fetched(&mut connection, &request), [kept], "{filter:?}"); + } } #[test] -fn a_note_matches_when_it_carries_at_least_one_selected_tag() { +fn the_rails_keep_the_snippets_of_a_language_and_the_notes_of_a_kind_or_priority() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let one = create(&mut connection, tagged(&space_id, &["urgent"]), t0()).unwrap(); - let two = create(&mut connection, tagged(&space_id, &["later"]), t0()).unwrap(); - create(&mut connection, tagged(&space_id, &["neither"]), t0()).unwrap(); - - let view = query( + let space_id = space(&mut connection, "Work"); + written( &mut connection, - &NotesQuery { - tags: vec!["urgent".to_string(), "later".to_string()], + NoteDraft { + title: "sql".into(), + ..written_in(&space_id, Language::Sql) + }, + "2026-07-01T00:00:00.000Z", + ); + let prose = NoteDraft { + kind: NoteKind::Note, + priority: Priority::High, + ..titled(&space_id, "prose") + }; + written(&mut connection, prose, "2026-07-02T00:00:00.000Z"); + let rails = [ + NotesQuery { + languages: vec![Language::Sql, Language::Txt], ..all_notes() }, - ) - .unwrap(); - - let ids = matched_ids(&view); - assert_eq!(ids.len(), 2); - assert!(ids.contains(&one.id) && ids.contains(&two.id)); - assert!(view.is_filtering); -} - -#[test] -fn a_selected_tag_is_normalized_like_a_stored_one() { - let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - create(&mut connection, tagged(&space_id, &["urgent"]), t0()).unwrap(); - - let view = query( - &mut connection, - &NotesQuery { - tags: vec![" #urgent ".to_string()], + NotesQuery { + kinds: vec![NoteKind::Note], ..all_notes() }, - ) - .unwrap(); - - assert_eq!(view.matched, 1); -} - -#[test] -fn a_selected_tag_matches_a_stored_one_of_a_different_case() { - let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - create(&mut connection, tagged(&space_id, &["Urgent"]), t0()).unwrap(); - - let view = query( - &mut connection, - &NotesQuery { - tags: vec!["urgent".to_string()], + NotesQuery { + priorities: vec![Priority::High, Priority::Urgent], ..all_notes() }, - ) - .unwrap(); + ]; - assert_eq!(view.matched, 1); -} - -#[test] -fn the_rail_offers_one_facet_for_tags_differing_only_in_case() { - let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - create(&mut connection, tagged(&space_id, &["Urgent"]), t0()).unwrap(); - create(&mut connection, tagged(&space_id, &["urgent"]), t1()).unwrap(); - - let view = query(&mut connection, &all_notes()).unwrap(); + let kept: Vec> = rails + .iter() + .map(|request| fetched(&mut connection, request)) + .collect(); - assert_eq!(view.available_tags.len(), 1); + assert_eq!(kept, [vec!["sql"], vec!["prose"], vec!["prose"]]); } #[test] -fn criteria_combine_rather_than_replace_each_other() { +fn a_tag_rail_keeps_a_note_carrying_any_of_its_tags_as_written_or_typed() { let mut connection = open_in_memory().unwrap(); - let here = space(&mut connection, "Personal"); - let elsewhere = space(&mut connection, "Boulot"); - - let target = create( + let space_id = space(&mut connection, "Work"); + written( &mut connection, NoteDraft { - title: "deploy".to_string(), - pinned: true, - tags: vec!["urgent".to_string()], - ..draft(&here) + title: "ops".into(), + ..tagged(&space_id, &["Ops"]) }, - t0(), - ) - .unwrap(); - create( - &mut connection, - NoteDraft { - title: "deploy".to_string(), - pinned: true, - tags: vec!["later".to_string()], - ..draft(&here) - }, - t0(), - ) - .unwrap(); - create( - &mut connection, - NoteDraft { - title: "deploy".to_string(), - pinned: false, - tags: vec!["urgent".to_string()], - ..draft(&here) - }, - t0(), - ) - .unwrap(); - create( + "2026-07-01T00:00:00.000Z", + ); + written( &mut connection, NoteDraft { - title: "autre".to_string(), - pinned: true, - tags: vec!["urgent".to_string()], - ..draft(&here) + title: "ci".into(), + ..tagged(&space_id, &["ci"]) }, - t0(), - ) - .unwrap(); - create( + "2026-07-02T00:00:00.000Z", + ); + written( &mut connection, NoteDraft { - title: "deploy".to_string(), - pinned: true, - tags: vec!["urgent".to_string()], - ..draft(&elsewhere) - }, - t0(), - ) - .unwrap(); - - let view = query( - &mut connection, - &NotesQuery { - space_id: Some(here), - search: "deploy".to_string(), - filter: NoteFilter::Pinned, - tags: vec!["urgent".to_string()], - ..all_notes() - }, - ) - .unwrap(); - - assert_eq!(matched_ids(&view), [target.id]); -} - -#[test] -fn a_note_matches_when_it_is_written_in_one_of_the_selected_languages() { - let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let json = create(&mut connection, written_in(&space_id, Language::Json), t0()).unwrap(); - let yml = create(&mut connection, written_in(&space_id, Language::Yml), t0()).unwrap(); - create(&mut connection, written_in(&space_id, Language::Py), t0()).unwrap(); - - let view = query( - &mut connection, - &NotesQuery { - languages: vec![Language::Json, Language::Yml], - ..all_notes() + title: "none".into(), + ..tagged(&space_id, &[]) }, - ) - .unwrap(); + "2026-07-03T00:00:00.000Z", + ); + let request = NotesQuery { + tags: vec!["#OPS".to_string(), "ci".to_string()], + ..all_notes() + }; - let ids = matched_ids(&view); - assert_eq!(ids.len(), 2); - assert!(ids.contains(&json.id) && ids.contains(&yml.id)); - assert!(view.is_filtering); + assert_eq!(fetched(&mut connection, &request), ["ci", "ops"]); } #[test] -fn the_language_filter_combines_with_the_other_criteria() { +fn facets_count_the_live_notes_of_the_space() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let target = create( + let work = space(&mut connection, "Work"); + let home = space(&mut connection, "Home"); + written( &mut connection, NoteDraft { - title: "deploy".to_string(), - ..written_in(&space_id, Language::Yml) + kind: NoteKind::Note, + ..tagged(&work, &["ops"]) }, - t0(), - ) - .unwrap(); - create(&mut connection, written_in(&space_id, Language::Yml), t0()).unwrap(); - create( + "2026-07-01T00:00:00.000Z", + ); + written( &mut connection, NoteDraft { - title: "deploy".to_string(), - ..written_in(&space_id, Language::Json) + priority: Priority::Low, + ..written_in(&work, Language::Sql) }, - t0(), - ) - .unwrap(); - - let view = query( - &mut connection, - &NotesQuery { - search: "deploy".to_string(), - languages: vec![Language::Yml], - ..all_notes() - }, - ) - .unwrap(); - - assert_eq!(matched_ids(&view), [target.id]); -} - -#[test] -fn available_languages_are_sorted_and_de_duplicated() { - let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - create(&mut connection, written_in(&space_id, Language::Yml), t0()).unwrap(); - create(&mut connection, written_in(&space_id, Language::Json), t0()).unwrap(); - create(&mut connection, written_in(&space_id, Language::Json), t1()).unwrap(); - - let view = query(&mut connection, &all_notes()).unwrap(); - - assert_eq!(view.available_languages, [Language::Json, Language::Yml]); -} - -#[test] -fn only_a_snippet_brings_its_language_to_the_rail_and_answers_to_it() { - let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - create(&mut connection, written_in(&space_id, Language::Json), t0()).unwrap(); - for kind in [NoteKind::Note, NoteKind::Checklist] { - let draft = NoteDraft { - kind, - ..written_in(&space_id, Language::Txt) - }; - create(&mut connection, draft, t0()).unwrap(); - } - - let view = query(&mut connection, &all_notes()).unwrap(); - let text = query( - &mut connection, - &NotesQuery { - languages: vec![Language::Txt], - ..all_notes() - }, - ) - .unwrap(); - - assert_eq!(view.available_languages, [Language::Json]); - assert_eq!(text.matched, 0); -} - -#[test] -fn available_languages_are_scoped_to_the_active_space() { - let mut connection = open_in_memory().unwrap(); - let here = space(&mut connection, "Personal"); - let elsewhere = space(&mut connection, "Boulot"); - create(&mut connection, written_in(&here, Language::Json), t0()).unwrap(); - create(&mut connection, written_in(&elsewhere, Language::Sql), t0()).unwrap(); - - let view = query( - &mut connection, - &NotesQuery { - space_id: Some(here), - ..all_notes() - }, - ) - .unwrap(); - - assert_eq!(view.available_languages, [Language::Json]); -} - -#[test] -fn available_languages_ignore_the_current_selection() { - let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - create(&mut connection, written_in(&space_id, Language::Json), t0()).unwrap(); - create(&mut connection, written_in(&space_id, Language::Yml), t0()).unwrap(); - - let view = query( - &mut connection, - &NotesQuery { - languages: vec![Language::Json], - ..all_notes() - }, - ) - .unwrap(); - - assert_eq!(view.available_languages, [Language::Json, Language::Yml]); - assert_eq!(view.matched, 1); -} - -fn of_kind(space_id: &str, kind: NoteKind) -> NoteDraft { - NoteDraft { - kind, - ..draft(space_id) - } -} - -#[test] -fn a_note_matches_when_it_is_of_one_of_the_selected_kinds() { - let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - create(&mut connection, of_kind(&space_id, NoteKind::Snippet), t0()).unwrap(); - let note = create(&mut connection, of_kind(&space_id, NoteKind::Note), t0()).unwrap(); - let list = create( - &mut connection, - of_kind(&space_id, NoteKind::Checklist), - t0(), - ) - .unwrap(); - - let view = query( + "2026-07-02T00:00:00.000Z", + ); + written( &mut connection, - &NotesQuery { - kinds: vec![NoteKind::Note, NoteKind::Checklist], - ..all_notes() - }, - ) - .unwrap(); - - let ids = matched_ids(&view); - assert_eq!(ids.len(), 2); - assert!(ids.contains(¬e.id) && ids.contains(&list.id)); - assert!(view.is_filtering); -} - -/// The space's counts, like its tags: counted from the selection, a chip would read 0 the -/// moment another one is pressed. -#[test] -fn every_kind_is_counted_over_the_space_whatever_is_selected() { - let mut connection = open_in_memory().unwrap(); - let here = space(&mut connection, "Personal"); - let elsewhere = space(&mut connection, "Boulot"); - for kind in [NoteKind::Snippet, NoteKind::Snippet, NoteKind::Note] { - create(&mut connection, of_kind(&here, kind), t0()).unwrap(); - } - create( + tagged(&home, &["home"]), + "2026-07-03T00:00:00.000Z", + ); + let gone = written( &mut connection, - of_kind(&elsewhere, NoteKind::Checklist), - t0(), - ) - .unwrap(); + tagged(&work, &["gone"]), + "2026-07-04T00:00:00.000Z", + ); + trash(&mut connection, &gone, t1()).unwrap(); - let view = query( - &mut connection, - &NotesQuery { - space_id: Some(here), - kinds: vec![NoteKind::Note], - ..all_notes() - }, - ) - .unwrap(); + let facets = fetch(&mut connection, &in_space(&work)).unwrap().1; - let counts: Vec<(NoteKind, u32)> = view - .kind_counts + let tags: Vec<_> = facets + .tags .iter() - .map(|counted| (counted.value, counted.count)) + .map(|tag| (tag.value.as_str(), tag.count)) .collect(); + assert_eq!(tags, [("api", 1), ("auth", 1), ("ops", 1)]); assert_eq!( - counts, - [ - (NoteKind::Snippet, 2), - (NoteKind::Note, 1), - (NoteKind::Checklist, 0), - (NoteKind::Calc, 0), - (NoteKind::Drawing, 0) - ] + facets.languages, + [FacetCount { + value: Language::Sql, + count: 1 + }] + ); + assert_eq!( + facets.kinds[0], + FacetCount { + value: NoteKind::Snippet, + count: 1 + } + ); + assert_eq!( + facets.kinds[1], + FacetCount { + value: NoteKind::Note, + count: 1 + } + ); + assert_eq!( + facets.priorities[1], + FacetCount { + value: Priority::Low, + count: 1 + } + ); + assert_eq!( + fetch(&mut connection, &all_notes()).unwrap().1.tags.len(), + 4 ); - assert_eq!(view.matched, 1); } -/// The space's counts, whatever is pressed, and a note answers to one of the levels asked. +/// Tags that differ in case only are one, as the column compares them. #[test] -fn a_priority_filters_on_one_of_its_levels_and_every_level_is_counted() { +fn facets_count_tags_alike_but_for_case_as_one() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let urgent = create( + let space_id = space(&mut connection, "Work"); + written( &mut connection, - NoteDraft { - priority: Priority::Urgent, - ..draft(&space_id) - }, - t0(), - ) - .unwrap(); - let high = create( - &mut connection, - NoteDraft { - priority: Priority::High, - ..draft(&space_id) - }, - t0(), - ) - .unwrap(); - create(&mut connection, draft(&space_id), t0()).unwrap(); - - let view = query( + tagged(&space_id, &["Ops"]), + "2026-07-01T00:00:00.000Z", + ); + written( &mut connection, - &NotesQuery { - priorities: vec![Priority::Urgent, Priority::High], - ..all_notes() - }, - ) - .unwrap(); - - let ids = matched_ids(&view); - assert_eq!(ids.len(), 2); - assert!(ids.contains(&urgent.id) && ids.contains(&high.id)); - let counts: Vec<(Priority, u32)> = view - .priority_counts - .iter() - .map(|counted| (counted.value, counted.count)) - .collect(); - assert_eq!( - counts, - [ - (Priority::None, 1), - (Priority::Low, 0), - (Priority::Medium, 0), - (Priority::High, 1), - (Priority::Urgent, 1) - ] + tagged(&space_id, &["ops"]), + "2026-07-02T00:00:00.000Z", ); -} - -#[test] -fn available_tags_are_sorted_and_de_duplicated() { - let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - create(&mut connection, tagged(&space_id, &["zeta", "alpha"]), t0()).unwrap(); - create(&mut connection, tagged(&space_id, &["alpha", "beta"]), t0()).unwrap(); - let view = query(&mut connection, &all_notes()).unwrap(); + let facets = fetch(&mut connection, &in_space(&space_id)).unwrap().1; - assert_eq!(view.available_tags, ["alpha", "beta", "zeta"]); - let counts: Vec<(&str, u32)> = view - .tag_counts + let ops: Vec<_> = facets + .tags .iter() - .map(|tag| (tag.value.as_str(), tag.count)) + .filter(|tag| tag.value.eq_ignore_ascii_case("ops")) + .map(|tag| tag.count) .collect(); - assert_eq!(counts, [("alpha", 2), ("beta", 1), ("zeta", 1)]); + assert_eq!(ops, [2]); } +/// The path the index replaced, end to end: what SQL keeps, then the view built on it. #[test] -fn available_tags_are_scoped_to_the_active_space() { +fn a_search_reads_through_the_store_and_the_view() { let mut connection = open_in_memory().unwrap(); - let here = space(&mut connection, "Personal"); - let elsewhere = space(&mut connection, "Boulot"); - create(&mut connection, tagged(&here, &["here-tag"]), t0()).unwrap(); - create( - &mut connection, - tagged(&elsewhere, &["elsewhere-tag"]), - t0(), - ) - .unwrap(); - - let view = query( + let space_id = space(&mut connection, "Work"); + written( &mut connection, - &NotesQuery { - space_id: Some(here), - ..all_notes() + NoteDraft { + content: "psql -h db".into(), + ..titled(&space_id, "connect") }, - ) - .unwrap(); - - assert_eq!(view.available_tags, ["here-tag"]); -} - -#[test] -fn available_tags_ignore_the_current_search_and_selection() { - let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - create(&mut connection, tagged(&space_id, &["urgent"]), t0()).unwrap(); - create(&mut connection, tagged(&space_id, &["later"]), t0()).unwrap(); - - let view = query( + "2026-07-01T00:00:00.000Z", + ); + written( &mut connection, - &NotesQuery { - tags: vec!["urgent".to_string()], - ..all_notes() - }, - ) - .unwrap(); + titled(&space_id, "other"), + "2026-07-02T00:00:00.000Z", + ); + let request = NotesQuery { + search: "PSQL".to_string(), + ..in_space(&space_id) + }; + + let view = query(&mut connection, &request).unwrap(); - assert_eq!(view.available_tags, ["later", "urgent"]); assert_eq!(view.matched, 1); + let card = view.cards().next().unwrap(); + assert_eq!(card.title, "connect"); + assert_eq!(card.hit.as_ref().unwrap().excerpt, "psql -h db"); } #[test] -fn a_search_matching_nothing_reports_filtering_with_zero_matches() { +fn the_criteria_combine_rather_than_replace_each_other() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - create(&mut connection, draft(&space_id), t0()).unwrap(); - - let view = query( + let space_id = space(&mut connection, "Work"); + let both = NoteDraft { + title: "both".into(), + tags: vec!["ops".into()], + ..written_in(&space_id, Language::Sql) + }; + written(&mut connection, both, "2026-07-01T00:00:00.000Z"); + written( &mut connection, - &NotesQuery { - search: "no-such-thing".to_string(), - ..all_notes() + NoteDraft { + title: "tag only".into(), + ..tagged(&space_id, &["ops"]) }, - ) - .unwrap(); - - assert!(view.is_filtering); - assert_eq!(view.matched, 0); -} - -#[test] -fn the_view_orders_notes_most_recently_updated_first() { - let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let older = create(&mut connection, draft(&space_id), t0()).unwrap(); - let newer = create(&mut connection, draft(&space_id), t1()).unwrap(); - - let view = query(&mut connection, &all_notes()).unwrap(); - - assert_eq!(matched_ids(&view), [newer.id, older.id]); -} - -fn long_body() -> String { - (1..=40) - .map(|n| format!("line {n}")) - .collect::>() - .join("\n") -} - -fn only_note(view: &NotesView) -> DisplayNote { - let mut cards = view.cards(); - let card = cards.next().expect("a note"); - assert!(cards.next().is_none(), "one note only"); - - view.display(card).clone() -} - -/// A list sends the head of a long body; the editor reads the rest with `get`. -#[test] -fn a_list_sends_the_head_of_a_long_body_and_get_the_whole_of_it() { - let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let note = create( + "2026-07-02T00:00:00.000Z", + ); + written( &mut connection, NoteDraft { - language: Language::Sh, - content: long_body(), - ..draft(&space_id) + title: "sql only".into(), + ..written_in(&space_id, Language::Sql) }, - t0(), - ) - .unwrap(); - - let view = query(&mut connection, &all_notes()).unwrap(); - let listed = only_note(&view); - assert!(listed.truncated); - assert_eq!(listed.content.lines().count(), PREVIEW_LINES); + "2026-07-03T00:00:00.000Z", + ); + let request = NotesQuery { + tags: vec!["ops".to_string()], + languages: vec![Language::Sql], + ..in_space(&space_id) + }; - assert_eq!(get(&mut connection, ¬e.id).unwrap().content, long_body()); + assert_eq!(fetched(&mut connection, &request), ["both"]); } -/// The search reads the whole body before the cut: a hit far down still shows its line. +/// Counted from the selection, a chip would read 0 the moment another one is pressed. #[test] -fn a_hit_past_the_preview_still_shows_its_line() { +fn facets_are_the_space_s_whatever_the_selection_or_the_search() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - create( + let space_id = space(&mut connection, "Work"); + written( &mut connection, - NoteDraft { - language: Language::Sh, - content: long_body(), - ..draft(&space_id) - }, - t0(), - ) - .unwrap(); - - let view = query( + tagged(&space_id, &["ops"]), + "2026-07-01T00:00:00.000Z", + ); + written( &mut connection, - &NotesQuery { - search: "line 40".to_string(), - ..all_notes() - }, - ) - .unwrap(); - let listed = only_note(&view); + written_in(&space_id, Language::Sql), + "2026-07-02T00:00:00.000Z", + ); + let narrowed = NotesQuery { + tags: vec!["ops".to_string()], + search: "nothing matches this".to_string(), + priorities: vec![Priority::Urgent], + ..in_space(&space_id) + }; - assert!(listed.truncated); - assert_eq!(listed.search_hit.as_ref().unwrap().excerpt, "line 40"); + let plain = fetch(&mut connection, &in_space(&space_id)).unwrap().1; + let selected = fetch(&mut connection, &narrowed).unwrap().1; + + assert_eq!(selected.tags, plain.tags); + assert_eq!(selected.languages, plain.languages); + assert_eq!(selected.kinds, plain.kinds); } +/// A list sends previews; the editor reads the body whole, by id. #[test] -fn get_finds_neither_a_trashed_note_nor_an_unknown_one() { +fn a_list_sends_the_head_of_a_long_body_and_opening_reads_all_of_it() { let mut connection = open_in_memory().unwrap(); - let space_id = space(&mut connection, "Personal"); - let note = create(&mut connection, draft(&space_id), t0()).unwrap(); - trash(&mut connection, ¬e.id, t1()).unwrap(); - - for id in [note.id.as_str(), "no-such-note"] { - assert!(matches!( - get(&mut connection, id), - Err(StorageError::NoteNotFound(missing)) if missing == id - )); - } + let space_id = space(&mut connection, "Work"); + let body: String = (1..=PREVIEW_LINES + 3) + .map(|n| format!("line {n}")) + .collect::>() + .join("\n"); + let long = NoteDraft { + content: body.clone(), + ..titled(&space_id, "long") + }; + let id = written(&mut connection, long, "2026-07-01T00:00:00.000Z"); + let request = NotesQuery { + search: format!("line {}", PREVIEW_LINES + 3), + ..in_space(&space_id) + }; + + let view = query(&mut connection, &request).unwrap(); + + let card = view.cards().next().unwrap(); + let shown = view.display(card); + assert!(shown.truncated); + assert_eq!(shown.content.lines().count(), PREVIEW_LINES); + assert_eq!( + shown.search_hit.as_ref().unwrap().excerpt, + format!("line {}", PREVIEW_LINES + 3) + ); + assert_eq!(get(&mut connection, &id).unwrap().content, body); } From 6c9dd6c7530d8ffa94501f0de18a6f4fbb6d7605 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:44:44 +0100 Subject: [PATCH 17/95] Notes services: unit tests rewritten (#1739) * Rewrite the tests of the notes' service functions The lock, the input checked before it, the codes failures answer, the normalisation each applies and what a write leaves in the index. * Take the restored id by reference Co-Authored-By: Claude Opus 5.5 * Drop the field spans service nothing calls Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/notes.rs | 5 - crates/engine/tests/commands/notes.rs | 750 ++++++++++++++------------ docs/architecture.md | 2 +- 3 files changed, 400 insertions(+), 357 deletions(-) diff --git a/crates/engine/src/notes.rs b/crates/engine/src/notes.rs index 73b320b0c..0c5b5b148 100644 --- a/crates/engine/src/notes.rs +++ b/crates/engine/src/notes.rs @@ -143,11 +143,6 @@ pub fn evaluate_calc(sheet: &str, today: chrono::NaiveDate) -> Result Vec { - placeholder::spans(content) -} - /// A copy to start another note from, attachments included and history left behind. The /// title is the front end's: its suffix is a translation. pub fn duplicate_note(engine: &Engine, id: &str, title: String) -> Result { diff --git a/crates/engine/tests/commands/notes.rs b/crates/engine/tests/commands/notes.rs index 2d32860b3..a717dbe22 100644 --- a/crates/engine/tests/commands/notes.rs +++ b/crates/engine/tests/commands/notes.rs @@ -1,508 +1,556 @@ use std::collections::BTreeMap; -use chrono::Utc; -use engine::error::ErrorCode; use engine::notes::checklist::ChecklistItem; +use engine::notes::drawing::{DrawingPictures, uri_of}; use engine::notes::kind::NoteKind; use engine::notes::model::{NoteDraft, NotePatch, SampleNote}; -use engine::notes::priority::Priority; use engine::notes::revision::DiffLine; -use engine::notes::trash::TrashedNote; use engine::notes::view::{Grouping, NoteFilter, NoteOrder, NotesQuery}; use engine::notes::{ convert_note, count_notes_tagged, create_note, delete_note, delete_notes, delete_tags, - duplicate_note, empty_trash, field_spans, fill_placeholders, get_note, - list_global_placeholders, list_revisions, list_tags, list_trash, move_notes, move_notes_back, - purge_notes, query_notes, remove_tag, rename_tags, restore_notes, restore_priorities, - restore_revision, restore_tags, restore_trash, revision_diff, seed_samples, - set_global_placeholders, set_pinned, set_placeholder_values, set_priority, tag_notes, - untag_notes, update_note, + drawing_picture, drawing_thumbnail, duplicate_note, empty_trash, fill_placeholders, get_note, + list_drawings, list_global_placeholders, list_revisions, list_tags, list_trash, purge_notes, + query_notes, remove_tag, rename_tags, restore_notes, restore_revision, restore_trash, + revision_diff, seed_samples, set_global_placeholders, set_placeholder_values, tag_notes, + update_note, }; use super::common::snippet; use super::{Session, code}; +use engine::error::ErrorCode; + +fn values(pairs: &[(&str, &str)]) -> BTreeMap { + pairs + .iter() + .map(|(name, value)| ((*name).to_string(), (*value).to_string())) + .collect() +} + +fn strings(values: &[&str]) -> Vec { + values.iter().map(|value| (*value).to_string()).collect() +} + +fn titled(space_id: &str, title: &str, content: &str) -> NoteDraft { + NoteDraft { + title: title.to_string(), + content: content.to_string(), + ..snippet(space_id) + } +} + +fn written(session: &Session, draft: NoteDraft) -> String { + session.call(|e| create_note(e, draft)).unwrap().note.id +} -fn everything(search: &str) -> NotesQuery { +fn everything() -> NotesQuery { NotesQuery { space_id: None, folder_id: None, - search: search.to_string(), + search: String::new(), filter: NoteFilter::All, tags: Vec::new(), languages: Vec::new(), kinds: Vec::new(), priorities: Vec::new(), order: NoteOrder::default(), - grouping: Grouping::default(), + grouping: Grouping::None, ranked: false, - now: Utc::now(), + now: chrono::Utc::now(), tz_offset_minutes: 0, - pinned_first: true, + pinned_first: false, } } -fn note(session: &Session, draft: NoteDraft) -> String { - session.call(|e| create_note(e, draft)).unwrap().note.id +fn listed(session: &Session) -> Vec { + let view = session.call(|e| query_notes(e, &everything())).unwrap(); + let mut titles: Vec = view.cards().map(|card| card.title.clone()).collect(); + titles.sort(); + titles } -fn values(pairs: &[(&str, &str)]) -> BTreeMap { - pairs - .iter() - .map(|(name, value)| ((*name).to_string(), (*value).to_string())) - .collect() +fn body(content: &str) -> NotePatch { + NotePatch { + content: Some(content.to_string()), + ..NotePatch::default() + } } -fn ids(of: &str) -> Vec { - vec![of.to_string()] +/// A PNG's eight signature bytes and one of its own, as a data URI. +fn png(mark: u8) -> String { + let mut bytes = b"\x89PNG\r\n\x1a\n".to_vec(); + bytes.push(mark); + uri_of(&bytes) } -/// The front end never builds the outlet before the unlock; a command that raced it answers -/// rather than unwrapping an empty `Mutex`. #[test] -fn a_command_run_before_the_unlock_answers_locked() { +fn nothing_answers_before_a_library_is_open() { let session = Session::locked(); - assert!(matches!( - code(session.call(|e| query_notes(e, &everything("")))), - ErrorCode::Locked - )); + let codes = [ + code(session.call(|e| get_note(e, "n"))), + code(session.call(|e| create_note(e, snippet("s")))), + code(session.call(|e| update_note(e, "n", &body("x")))), + code(session.call(|e| delete_note(e, "n"))), + code(session.call(|e| query_notes(e, &everything()))), + code(session.call(|e| list_trash(e, ""))), + code(session.call(list_tags)), + code(session.call(|e| fill_placeholders(e, "{{a}}", &BTreeMap::new()))), + code(session.call(|e| list_revisions(e, "n"))), + code(session.call(list_drawings)), + ]; + + assert!( + codes.iter().all(|found| *found == ErrorCode::Locked), + "{codes:?}" + ); } #[test] -fn a_note_written_through_the_commands_reads_back_and_is_found() { +fn a_note_created_is_answered_decorated_and_listed() { let session = Session::open(); - let space = session.space("Personal"); - let id = note(&session, snippet(&space)); + let space = session.space("Work"); - let patch = NotePatch { - title: Some("psql to prod".to_string()), - ..Default::default() - }; - let updated = session.call(|e| update_note(e, &id, &patch)).unwrap(); - let read = session.call(|e| get_note(e, &id)).unwrap(); - let found = session - .call(|e| query_notes(e, &everything("prod"))) + let created = session + .call(|e| create_note(e, titled(&space, "First", "psql -h {{host}}"))) .unwrap(); - assert_eq!(updated.note.title, "psql to prod"); - assert_eq!(read.note.title, "psql to prod"); - assert_eq!(found.matched, 1); - assert_eq!(found.sections[0].cards[0].id, id); + assert_eq!(created.placeholders[0].name, "host"); + assert_eq!(listed(&session), ["First"]); + assert_eq!( + session + .call(|e| get_note(e, &created.note.id)) + .unwrap() + .title, + "First" + ); } #[test] -fn a_note_that_does_not_exist_is_named_as_such() { +fn a_note_that_is_not_there_is_answered_by_its_code() { let session = Session::open(); - assert!(matches!( + assert_eq!( code(session.call(|e| get_note(e, "missing"))), ErrorCode::NoteNotFound - )); + ); + assert_eq!( + code(session.call(|e| update_note(e, "missing", &body("x")))), + ErrorCode::NoteNotFound + ); + assert_eq!( + code(session.call(|e| delete_note(e, "missing"))), + ErrorCode::NoteNotFound + ); } +/// Read before anything is locked: a picture that is no PNG is refused as input. #[test] -fn a_duplicate_takes_the_title_it_is_given() { +fn a_drawing_s_pictures_are_checked_before_the_library_is_asked() { + let session = Session::locked(); + let patch = NotePatch { + pictures: Some(DrawingPictures { + thumbnail: "data:image/svg+xml;base64,PHN2Zz4=".to_string(), + picture: png(2), + }), + ..NotePatch::default() + }; + + assert_eq!( + code(session.call(|e| update_note(e, "n", &patch))), + ErrorCode::InvalidInput + ); +} + +#[test] +fn a_drawing_saved_with_its_pictures_shows_each_and_is_listed_to_embed() { let session = Session::open(); - let space = session.space("Personal"); - let id = note(&session, snippet(&space)); + let space = session.space("Work"); + let id = written( + &session, + NoteDraft { + kind: NoteKind::Drawing, + title: "Plan".to_string(), + content: r#"{"scene":{"objects":[]}}"#.to_string(), + ..snippet(&space) + }, + ); + let saved = NotePatch { + pictures: Some(DrawingPictures { + thumbnail: png(1), + picture: png(2), + }), + ..NotePatch::default() + }; - let copy = session - .call(|e| duplicate_note(e, &id, "Titre (copie)".to_string())) - .unwrap(); + session.call(|e| update_note(e, &id, &saved)).unwrap(); - assert_ne!(copy.note.id, id); - assert_eq!(copy.note.title, "Titre (copie)"); - assert_eq!(copy.note.content, "Contenu"); + assert_eq!( + session.call(|e| drawing_thumbnail(e, &id)).unwrap(), + Some(png(1)) + ); + assert_eq!( + session.call(|e| drawing_picture(e, &id)).unwrap(), + Some(png(2)) + ); + let drawings = session.call(list_drawings).unwrap(); + assert_eq!(drawings.len(), 1); + assert_eq!(drawings[0].title, "Plan"); } #[test] -fn the_samples_arrive_in_one_space_with_their_folders() { +fn a_change_of_kind_answers_the_body_it_had_for_its_undo() { let session = Session::open(); - let sample = SampleNote { - folder: Some(1), - draft: snippet(""), - }; + let space = session.space("Work"); + let id = written(&session, titled(&space, "List", "- a\n- [x] b")); - let space = session - .call(|e| { - seed_samples( - e, - "Samples".to_string(), - &["Scripts".to_string(), "Notes".to_string()], - vec![sample], - ) - }) + let converted = session + .call(|e| convert_note(e, &id, NoteKind::Checklist)) .unwrap(); - let seeded = session.call(|e| query_notes(e, &everything(""))).unwrap(); - assert_eq!(session.spaces(), ["Samples"]); - assert_eq!(seeded.matched, 1); - assert_eq!(seeded.sections[0].cards[0].space_id, space.id); + assert_eq!(converted.previous.content, "- a\n- [x] b"); assert_eq!( - seeded - .display(&seeded.sections[0].cards[0]) - .folder - .as_ref() - .unwrap() - .name, - "Notes" + converted.note.items, + [ + ChecklistItem { + text: "a".to_string(), + done: false + }, + ChecklistItem { + text: "b".to_string(), + done: true + } + ] ); } -/// Checked before the lock: a blank name never reaches the transaction. #[test] -fn samples_under_a_blank_name_are_refused() { +fn a_duplicate_is_answered_and_listed_beside_its_original() { let session = Session::open(); + let space = session.space("Work"); + let id = written(&session, titled(&space, "Original", "body")); - assert!(matches!( - code(session.call(|e| seed_samples(e, " ".to_string(), &Vec::new(), Vec::new()))), - ErrorCode::InvalidInput - )); - assert!(session.spaces().is_empty()); + let copy = session + .call(|e| duplicate_note(e, &id, "Copy".to_string())) + .unwrap(); + + assert_ne!(copy.note.id, id); + assert_eq!(listed(&session), ["Copy", "Original"]); } #[test] -fn a_kept_body_is_listed_compared_and_put_back() { +fn a_kept_body_is_listed_compared_and_gone_back_to() { let session = Session::open(); - let space = session.space("Personal"); - let id = note(&session, snippet(&space)); - let edit = NotePatch { - content: Some("psql -h prod".to_string()), - ..Default::default() - }; - session.call(|e| update_note(e, &id, &edit)).unwrap(); - + let space = session.space("Work"); + let id = written(&session, titled(&space, "Query", "select 1")); + session + .call(|e| update_note(e, &id, &body("select 2"))) + .unwrap(); let kept = session.call(|e| list_revisions(e, &id)).unwrap(); - let revision = kept[0].id.clone(); + let diff = session - .call(|e| revision_diff(e, &id, revision.clone())) + .call(|e| revision_diff(e, &id, kept[0].id.clone())) .unwrap(); let restored = session - .call(|e| restore_revision(e, &id, &revision)) + .call(|e| restore_revision(e, &id, &kept[0].id)) .unwrap(); - assert_eq!(kept.len(), 1); - assert!(diff.contains(&DiffLine::Restored { - text: "Contenu".to_string() - })); - assert_eq!(restored.note.content, "Contenu"); + assert_eq!( + diff, + [ + DiffLine::Dropped { + text: "select 2".to_string() + }, + DiffLine::Restored { + text: "select 1".to_string() + } + ] + ); + assert_eq!(restored.content, "select 1"); + assert!(session.call(|e| list_revisions(e, &id)).unwrap().is_empty()); } #[test] -fn comparing_with_a_revision_that_is_not_kept_is_named_as_such() { +fn a_revision_that_is_not_kept_is_answered_by_its_code() { let session = Session::open(); - let space = session.space("Personal"); - let id = note(&session, snippet(&space)); + let space = session.space("Work"); + let id = written(&session, titled(&space, "Query", "select 1")); - assert!(matches!( + assert_eq!( code(session.call(|e| revision_diff(e, &id, "missing".to_string()))), ErrorCode::RevisionNotFound - )); + ); + assert_eq!( + code(session.call(|e| restore_revision(e, &id, "missing"))), + ErrorCode::RevisionNotFound + ); } +// --- The trash. + #[test] -fn the_trash_takes_notes_gives_them_back_and_forgets_them() { +fn deleted_notes_wait_in_the_trash_and_come_back() { let session = Session::open(); - let space = session.space("Personal"); - let first = note(&session, snippet(&space)); - let second = note(&session, snippet(&space)); + let space = session.space("Work"); + let first = written(&session, titled(&space, "First", "a")); + let second = written(&session, titled(&space, "Second", "b")); session.call(|e| delete_note(e, &first)).unwrap(); - let trashed = session.call(|e| list_trash(e, "")).unwrap(); - let restored = session.call(|e| restore_notes(e, &ids(&first))).unwrap(); - let deleted = session - .call(|e| delete_notes(e, &[first.clone(), second.clone()])) + .call(|e| delete_notes(e, &[second.clone(), "missing".to_string()])) .unwrap(); - let purged = session.call(|e| purge_notes(e, &ids(&first))).unwrap(); - let emptied = session.call(empty_trash).unwrap(); - assert_eq!(trashed.len(), 1); - assert_eq!(trashed[0].note.id, first); - assert_eq!((restored, deleted, purged, emptied), (1, 2, 1, 1)); - assert!(session.call(|e| list_trash(e, "")).unwrap().is_empty()); + assert_eq!(deleted, 1); + assert!(listed(&session).is_empty()); + assert_eq!(session.call(|e| list_trash(e, "")).unwrap().len(), 2); + assert_eq!( + session + .call(|e| restore_notes(e, std::slice::from_ref(&first))) + .unwrap(), + 1 + ); + assert_eq!(listed(&session), ["First"]); } -/// Found by a word the canvas search would find, folded; what was found is what comes back. #[test] -fn the_trash_is_searched_and_what_it_found_restored() { +fn the_trash_is_searched_and_restored_by_what_it_shows() { let session = Session::open(); - let space = session.space("Personal"); - let mut titled = snippet(&space); - titled.title = "Rotation du certificat".to_string(); - let found = note(&session, titled); - let other = note(&session, snippet(&space)); - session - .call(|e| delete_notes(e, &[found.clone(), other.clone()])) - .unwrap(); + let space = session.space("Work"); + let deploy = written(&session, titled(&space, "Déploiement", "kubectl apply")); + let other = written(&session, titled(&space, "Other", "nothing")); + session.call(|e| delete_notes(e, &[deploy, other])).unwrap(); - let narrowed = session.call(|e| list_trash(e, " CERTIFICAT ")).unwrap(); - let restored = session.call(|e| restore_trash(e, "certificat")).unwrap(); - let left = session.call(|e| list_trash(e, "")).unwrap(); - let rest = session.call(|e| restore_trash(e, "")).unwrap(); + let found = session.call(|e| list_trash(e, " DEPLOIEMENT ")).unwrap(); + let restored = session.call(|e| restore_trash(e, "kubectl")).unwrap(); - let ids = |notes: &[TrashedNote]| { - notes - .iter() - .map(|note| note.note.id.clone()) - .collect::>() - }; - assert_eq!(ids(&narrowed), [found]); + assert_eq!(found.len(), 1); + assert_eq!(found[0].preview, "kubectl apply"); assert_eq!(restored, 1); - assert_eq!(ids(&left), [other]); - assert_eq!(rest, 1); + assert_eq!(listed(&session), ["Déploiement"]); } #[test] -fn a_move_is_undone_by_the_placements_it_answered() { +fn notes_purged_or_the_trash_emptied_are_gone_for_good() { let session = Session::open(); - let personal = session.space("Personal"); - let work = session.space("Work"); - let id = note(&session, snippet(&personal)); - - let placements = session.call(|e| move_notes(e, &ids(&id), &work)).unwrap(); - let moved = session.call(|e| get_note(e, &id)).unwrap(); - let undone = session.call(|e| move_notes_back(e, &placements)).unwrap(); - let back = session.call(|e| get_note(e, &id)).unwrap(); - - assert_eq!(moved.note.space_id, work); - assert_eq!(undone, 1); - assert_eq!(back.note.space_id, personal); + let space = session.space("Work"); + let ids: Vec = (0..3) + .map(|n| written(&session, titled(&space, &n.to_string(), "x"))) + .collect(); + session.call(|e| delete_notes(e, &ids)).unwrap(); + + assert_eq!(session.call(|e| purge_notes(e, &ids[..1])).unwrap(), 1); + assert_eq!(session.call(empty_trash).unwrap(), 2); + assert!(session.call(|e| list_trash(e, "")).unwrap().is_empty()); + assert_eq!(session.call(|e| restore_notes(e, &ids)).unwrap(), 0); } +// --- Tags. + #[test] -fn a_priority_is_set_and_put_back_without_touching_the_modification_date() { +fn a_tag_typed_with_its_hash_joins_the_stored_one() { let session = Session::open(); - let space = session.space("Personal"); - let id = note(&session, snippet(&space)); - let before = session.call(|e| get_note(e, &id)).unwrap(); + let space = session.space("Work"); + let id = written( + &session, + NoteDraft { + tags: strings(&["ops"]), + ..titled(&space, "a", "x") + }, + ); + let other = written(&session, titled(&space, "b", "x")); - let previous = session - .call(|e| set_priority(e, &ids(&id), Priority::Urgent)) + let added = session + .call(|e| tag_notes(e, &[id.clone(), other.clone()], &strings(&["#OPS"]))) + .unwrap(); + let removed = session + .call(|e| remove_tag(e, &[id.clone(), other], "#ops".to_string())) .unwrap(); - let set = session.call(|e| get_note(e, &id)).unwrap(); - let restored = session.call(|e| restore_priorities(e, &previous)).unwrap(); - let back = session.call(|e| get_note(e, &id)).unwrap(); - assert_eq!(previous.len(), 1); - assert_eq!(set.note.priority, Priority::Urgent); - assert_eq!(set.note.updated_at, before.note.updated_at); - assert_eq!(restored, 1); - assert_eq!(back.note.priority, Priority::None); + assert_eq!(added.len(), 1); + assert_eq!(removed.len(), 2); + assert!( + session + .call(|e| remove_tag(e, &[id], " # ".to_string())) + .unwrap() + .is_empty() + ); } -/// The body before a conversion is in the history; writing that body back is the undo. #[test] -fn a_note_changes_kind_keeps_its_body_in_the_history_and_comes_back() { +fn the_tags_in_use_are_counted_and_renamed_by_the_count_they_announce() { let session = Session::open(); - let space = session.space("Personal"); - let mut draft = snippet(&space); - draft.content = "- [x] Freeze the merges\nDeploy".to_string(); - let original = draft.content.clone(); - let id = note(&session, draft); - - let converted = session - .call(|e| convert_note(e, &id, NoteKind::Checklist)) - .unwrap(); - let history = session.call(|e| list_revisions(e, &id)).unwrap(); - let previous = converted.previous.clone(); - let back = session - .call(|e| { - update_note( - e, - &id, - &NotePatch { - kind: Some(previous.kind), - language: Some(previous.language), - content: Some(previous.content.clone()), - items: Some(previous.items.clone()), - ..NotePatch::default() - }, - ) - }) + let space = session.space("Work"); + written( + &session, + NoteDraft { + tags: strings(&["auth", "api"]), + ..titled(&space, "a", "x") + }, + ); + written( + &session, + NoteDraft { + tags: strings(&["auth"]), + ..titled(&space, "b", "x") + }, + ); + let gone = written( + &session, + NoteDraft { + tags: strings(&["api"]), + ..titled(&space, "c", "x") + }, + ); + session.call(|e| delete_note(e, &gone)).unwrap(); + + let usage: Vec<_> = session + .call(list_tags) + .unwrap() + .into_iter() + .map(|tag| (tag.tag, tag.note_count)) + .collect(); + let announced = session + .call(|e| count_notes_tagged(e, &strings(&["#auth", "api"]))) .unwrap(); - let unchanged = session - .call(|e| convert_note(e, &id, NoteKind::Snippet)) + let renamed = session + .call(|e| rename_tags(e, &strings(&["auth", "api"]), "#security")) .unwrap(); - assert_eq!(converted.note.note.kind, NoteKind::Checklist); - assert_eq!(converted.note.note.content, ""); + assert_eq!(usage, [("api".to_string(), 1), ("auth".to_string(), 2)]); + assert_eq!((announced, renamed), (3, 3)); + let usage = session.call(list_tags).unwrap(); + assert_eq!(usage[0].tag, "security"); +} + +#[test] +fn a_rename_onto_nothing_readable_is_refused_as_input() { + let session = Session::open(); + assert_eq!( - converted.note.note.items, - [ - ChecklistItem { - text: "Freeze the merges".to_string(), - done: true - }, - ChecklistItem { - text: "Deploy".to_string(), - done: false - }, - ] + code(session.call(|e| rename_tags(e, &strings(&["auth"]), " # "))), + ErrorCode::InvalidInput ); - assert_eq!(history.len(), 1); - assert_eq!(previous.kind, NoteKind::Snippet); - assert_eq!(back.note.kind, NoteKind::Snippet); - assert_eq!(back.note.content, original); - assert!(back.note.items.is_empty()); - assert_eq!(unchanged.previous.content, original); } -/// Taken off the live notes that carry it, found as typed; put back pair by pair. #[test] -fn a_tag_is_taken_off_a_selection_and_put_back_exactly() { +fn deleting_tags_answers_the_notes_that_carried_them() { let session = Session::open(); - let space = session.space("Personal"); - let tagged = |tags: &[&str]| { - let mut draft = snippet(&space); - draft.tags = tags.iter().map(ToString::to_string).collect(); - note(&session, draft) - }; - let both = tagged(&["ops", "urgent"]); - let ops = tagged(&["ops"]); - let bare = tagged(&[]); - let trashed = tagged(&["ops"]); - session.call(|e| delete_note(e, &trashed)).unwrap(); - let tags_of = |id: &String| session.call(|e| get_note(e, id)).unwrap().note.tags; - - let mut removed = session - .call(|e| { - remove_tag( - e, - &[both.clone(), ops.clone(), bare.clone(), trashed.clone()], - " #OPS ".to_string(), - ) - }) - .unwrap(); - removed.sort_by(|a, b| a.note_id.cmp(&b.note_id)); - let after = (tags_of(&both), tags_of(&ops), tags_of(&bare)); - let restored = session.call(|e| restore_tags(e, &removed)).unwrap(); + let space = session.space("Work"); + written( + &session, + NoteDraft { + tags: strings(&["a", "b"]), + ..titled(&space, "1", "x") + }, + ); + written( + &session, + NoteDraft { + tags: strings(&["b"]), + ..titled(&space, "2", "x") + }, + ); - let mut expected = vec![both.clone(), ops.clone()]; - expected.sort(); assert_eq!( - removed - .iter() - .map(|pair| pair.note_id.clone()) - .collect::>(), - expected - ); - assert!(removed.iter().all(|pair| pair.tag == "ops")); - assert_eq!(after, (vec!["urgent".to_string()], vec![], vec![])); - assert_eq!(restored, 2); - assert_eq!(tags_of(&both), ["ops", "urgent"]); - assert_eq!(tags_of(&ops), ["ops"]); - assert!( session - .call(|e| remove_tag(e, &ids(&both), "#".to_string())) - .unwrap() - .is_empty() + .call(|e| delete_tags(e, &strings(&["#a", "B"]))) + .unwrap(), + 2 ); + assert!(session.call(list_tags).unwrap().is_empty()); } -/// Triage, like the priority: the modification date stays, and the undo is the other way round. +// --- Fields. + #[test] -fn notes_are_pinned_together_and_unpinned_back_without_touching_the_modification_date() { +fn a_note_s_values_are_kept_only_for_names_of_fields_with_something_typed() { let session = Session::open(); - let space = session.space("Personal"); - let loose = note(&session, snippet(&space)); - let mut held = snippet(&space); - held.pinned = true; - let held = note(&session, held); - let before = session.call(|e| get_note(e, &loose)).unwrap(); - - let changed = session - .call(|e| set_pinned(e, &[loose.clone(), held.clone()], true)) - .unwrap(); - let pinned = session.call(|e| get_note(e, &loose)).unwrap(); - let undone = session.call(|e| set_pinned(e, &changed, false)).unwrap(); - let pinned_after = |id: &String| session.call(|e| get_note(e, id)).unwrap().note.pinned; - - assert_eq!(changed, std::slice::from_ref(&loose)); - assert!(pinned.note.pinned); - assert_eq!(pinned.note.updated_at, before.note.updated_at); - assert_eq!(undone, std::slice::from_ref(&loose)); - assert!(!pinned_after(&loose)); - assert!(pinned_after(&held)); -} + let space = session.space("Work"); + let id = written( + &session, + titled(&space, "psql", "psql -h {{host}} -p {{port=5432}}"), + ); -/// The editor marks what Rust calls a field, and nothing it does not. -#[test] -fn the_fields_of_a_text_are_found_for_the_editor() { - let spans = field_spans("{{host}} {{ user.name }}"); + let shown = session + .call(|e| { + set_placeholder_values( + e, + &id, + values(&[("host", "db"), ("port", ""), ("a b", "x")]), + ) + }) + .unwrap(); - assert_eq!(spans.len(), 1); - assert_eq!((spans[0].from, spans[0].to), (0, 8)); + assert_eq!(shown.note.placeholder_values, values(&[("host", "db")])); + assert_eq!(shown.placeholders[1].default_value, "5432"); } -/// A typed `#urgent` joins `urgent`: the command normalises before the store sees it. #[test] -fn tags_are_normalised_counted_renamed_and_dropped() { +fn global_values_are_kept_the_same_way_and_suggested_under_a_note_s_own() { let session = Session::open(); - let space = session.space("Personal"); - let id = note(&session, snippet(&space)); - - let added = session - .call(|e| tag_notes(e, &ids(&id), &["#urgent".to_string()])) - .unwrap(); - let counted = session - .call(|e| count_notes_tagged(e, &["urgent".to_string()])) - .unwrap(); - let usage = session.call(list_tags).unwrap(); - let untagged = session.call(|e| untag_notes(e, &added)).unwrap(); - session - .call(|e| tag_notes(e, &ids(&id), &["urgent".to_string()])) - .unwrap(); - let renamed = session - .call(|e| rename_tags(e, &["urgent".to_string()], "later")) + let kept = session + .call(|e| { + set_global_placeholders( + e, + values(&[("host", "global"), ("port", "6543"), ("empty", "")]), + ) + }) .unwrap(); - let dropped = session - .call(|e| delete_tags(e, &["later".to_string()])) + let filled = session + .call(|e| { + fill_placeholders( + e, + "{{host}}:{{port=5432}}/{{db=main}}", + &values(&[("host", "mine")]), + ) + }) .unwrap(); - assert_eq!(added[0].tag, "urgent"); - assert_eq!(counted, 1); - assert_eq!((usage[0].tag.as_str(), usage[0].note_count), ("urgent", 1)); - assert_eq!((untagged, renamed, dropped), (1, 1, 1)); - assert!(session.call(list_tags).unwrap().is_empty()); + assert_eq!(kept, values(&[("host", "global"), ("port", "6543")])); + assert_eq!(session.call(list_global_placeholders).unwrap(), kept); + assert_eq!(filled, "mine:6543/main"); } +// --- The first launch. + #[test] -fn renaming_onto_a_blank_tag_is_refused() { +fn the_first_launch_writes_its_samples_and_answers_their_space() { let session = Session::open(); + let samples = vec![SampleNote { + folder: Some(0), + draft: titled("ignored", "Welcome", "Hello"), + }]; - assert!(matches!( - code(session.call(|e| rename_tags(e, &["urgent".to_string()], "#"))), - ErrorCode::InvalidInput - )); + let space = session + .call(|e| seed_samples(e, "Discover".to_string(), &strings(&["Start"]), samples)) + .unwrap(); + + assert_eq!(space.name, "Discover"); + assert_eq!(listed(&session), ["Welcome"]); } -/// A note's own value first, then the global one: the palette fills with both. #[test] -fn fields_fill_from_the_note_then_from_the_globals() { +fn the_first_launch_refuses_a_name_it_cannot_write_before_writing_anything() { let session = Session::open(); - let space = session.space("Personal"); - let id = note( - &session, - NoteDraft { - content: "psql -h {{host}} -U {{user}}".to_string(), - ..snippet(&space) - }, - ); - - let filled = session - .call(|e| set_placeholder_values(e, &id, values(&[("host", "db")]))) - .unwrap(); - let globals = session - .call(|e| set_global_placeholders(e, values(&[("user", "admin")]))) - .unwrap(); - let listed = session.call(list_global_placeholders).unwrap(); - let text = session - .call(|e| fill_placeholders(e, &filled.note.content, &filled.note.placeholder_values)) - .unwrap(); + let sample = || { + vec![SampleNote { + folder: None, + draft: titled("ignored", "Welcome", "Hello"), + }] + }; - assert_eq!(filled.note.placeholder_values, values(&[("host", "db")])); - assert_eq!(globals, listed); - assert_eq!(text, "psql -h db -U admin"); + assert_eq!( + code(session.call(|e| seed_samples(e, " ".to_string(), &[], sample()))), + ErrorCode::InvalidInput + ); + assert_eq!( + code(session.call(|e| seed_samples( + e, + "Discover".to_string(), + &strings(&[" "]), + sample() + ))), + ErrorCode::InvalidInput + ); + assert!(session.spaces().is_empty()); } diff --git a/docs/architecture.md b/docs/architecture.md index d6e7996b8..34aea6457 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -3479,7 +3479,7 @@ as a field is decided in `notes::placeholder` and nowhere else: the name is rest into a form on every copy. Values arrive parsed on `DisplayNote.placeholders`, and `fill_placeholders` — a pure command, no database — does the substitution. -**The code marks them where they are written**, from Rust too: `field_spans` answers each +**The code marks them where they are written**, from Rust too: `placeholder::spans` answers each token's range and its default's, in UTF-16 units — the editor's offsets — from the same `scan` that `parse` and `fill` walk. `FieldMarksStore` asks 250 ms after the typing pauses and keeps the text an answer was found in; the code field (`code-editor/field-marks.ts`) marks only that From 3ef0c4c7a99f972bdc698116af2c37519318cbf2 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:56:39 +0100 Subject: [PATCH 18/95] Revisions: a line kept in both texts no longer shows as removed (#1733) A last line without its newline was read as another line. --- crates/engine/src/notes/revision.rs | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/notes/revision.rs b/crates/engine/src/notes/revision.rs index bade108da..9515b798f 100644 --- a/crates/engine/src/notes/revision.rs +++ b/crates/engine/src/notes/revision.rs @@ -2,6 +2,7 @@ //! //! What the trash does for a deletion, for an edit: the version that worked stays recoverable. +use std::borrow::Cow; use std::time::Duration; use chrono::{DateTime, Utc}; @@ -71,9 +72,10 @@ const DIFF_TIMEOUT: Duration = Duration::from_millis(300); /// are the same text. #[must_use] pub fn diff(current: &str, version: &str) -> Vec { + let (current, version) = (terminated(current), terminated(version)); let diff = TextDiff::configure() .timeout(DIFF_TIMEOUT) - .diff_lines(current, version); + .diff_lines(current.as_ref(), version.as_ref()); if diff.ops().iter().all(|op| op.tag() == DiffTag::Equal) { return Vec::new(); } @@ -113,6 +115,15 @@ fn skip(lines: &mut Vec, count: usize) { } } +/// `text` ending with a newline: a last line without one is otherwise another line. +fn terminated(text: &str) -> Cow<'_, str> { + if text.is_empty() || text.ends_with('\n') { + Cow::Borrowed(text) + } else { + Cow::Owned(format!("{text}\n")) + } +} + #[cfg(test)] mod tests { use super::*; @@ -186,6 +197,20 @@ mod tests { ); } + /// A body typed in the editor seldom ends with a newline. + #[test] + fn a_line_both_texts_hold_shows_once_whichever_ends_without_a_newline() { + assert_eq!( + diff("a", "a\nb"), + [kept("a"), DiffLine::Restored { text: "b".into() }] + ); + assert_eq!( + diff("a\nb", "a"), + [kept("a"), DiffLine::Dropped { text: "b".into() }] + ); + assert!(diff("a\nb\n", "a\nb").is_empty()); + } + #[test] fn a_line_s_ending_is_not_part_of_its_text() { assert_eq!( From 0e8408b41254383e6549bc007ae7b07d5f9605c9 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:56:46 +0100 Subject: [PATCH 19/95] Spaces: unit tests rewritten (#1740) * Rewrite the tests of spaces around their rules Names readable and unique case aside, the order pinned then by name, what a deletion moves, trashes and takes, and the services' lock, input checks and codes. * Keep what the old spaces tests held: pin through a rename, attachments through the trash Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/name.rs | 31 +- crates/engine/src/spaces/model.rs | 30 +- crates/engine/tests/commands/spaces.rs | 246 ++++++++------- crates/engine/tests/spaces.rs | 397 +++++++++++-------------- 4 files changed, 325 insertions(+), 379 deletions(-) diff --git a/crates/engine/src/name.rs b/crates/engine/src/name.rs index 363c57efb..55fc42051 100644 --- a/crates/engine/src/name.rs +++ b/crates/engine/src/name.rs @@ -34,26 +34,35 @@ mod tests { use super::*; #[test] - fn a_name_is_trimmed_before_being_stored() { - assert_eq!(readable(" Perf ", "folder").unwrap(), "Perf"); + fn a_name_is_kept_trimmed() { + assert_eq!(readable(" Perf \t", "space"), Ok("Perf".to_string())); } #[test] - fn a_blank_name_is_refused_with_its_field() { - for blank in ["", " ", "\t\n"] { - assert_eq!(readable(blank, "space").unwrap_err().field, "name"); + fn a_name_with_nothing_readable_is_refused_as_the_name_field() { + for raw in ["", " ", "\n\t"] { + let refused = readable(raw, "folder").unwrap_err(); + + assert_eq!(refused.field, "name", "{raw:?}"); } } #[test] - fn a_name_is_taken_whatever_its_case() { - assert!(is_taken([("s-1", "Personal")], "PERSONAL", None)); - assert!(!is_taken([("s-1", "Personal")], "Work", None)); + fn a_name_is_taken_by_another_whatever_its_case() { + let held = [("a", "Work"), ("b", "Ãrchive")]; + + assert!(is_taken(held, "WORK", None)); + assert!(is_taken(held, "ãrchive", None)); + assert!(!is_taken(held, "Home", None)); + assert!(!is_taken([], "Work", None)); } + /// So a rename can correct its own case. #[test] - fn a_name_does_not_collide_with_itself() { - assert!(!is_taken([("s-1", "personal")], "Personal", Some("s-1"))); - assert!(is_taken([("s-1", "personal")], "Personal", Some("s-2"))); + fn a_name_held_by_the_one_being_renamed_is_not_taken() { + let held = [("a", "work"), ("b", "Home")]; + + assert!(!is_taken(held, "Work", Some("a"))); + assert!(is_taken(held, "home", Some("a"))); } } diff --git a/crates/engine/src/spaces/model.rs b/crates/engine/src/spaces/model.rs index 5e9ee6843..d4df1572c 100644 --- a/crates/engine/src/spaces/model.rs +++ b/crates/engine/src/spaces/model.rs @@ -54,26 +54,28 @@ pub fn validate_move_target(id: &str, target_id: &str) -> Result<(), ValidationE mod tests { use super::*; - fn draft(name: &str) -> SpaceDraft { - SpaceDraft { - name: name.to_string(), - } - } - #[test] - fn a_name_is_trimmed_before_being_stored() { - assert_eq!(draft(" Personal ").validated_name().unwrap(), "Personal"); + fn a_space_s_name_is_read_trimmed_and_never_blank() { + let named = |name: &str| SpaceDraft { name: name.into() }.validated_name(); + + assert_eq!(named(" Work "), Ok("Work".to_string())); + assert_eq!(named(" ").unwrap_err().field, "name"); } #[test] - fn a_space_cannot_be_its_own_move_target() { - let error = validate_move_target("s-1", "s-1").unwrap_err(); - - assert_eq!(error.field, "targetSpaceId"); + fn a_space_cannot_be_its_own_refuge() { + assert_eq!( + validate_move_target("a", "a").unwrap_err().field, + "targetSpaceId" + ); + assert_eq!(validate_move_target("a", "b"), Ok(())); } + /// An export written before spaces could be pinned stays readable. #[test] - fn another_space_is_an_acceptable_move_target() { - assert!(validate_move_target("s-1", "s-2").is_ok()); + fn a_space_from_an_export_without_a_pin_reads_back_unpinned() { + let space: Space = serde_json::from_str(r#"{"id":"s-1","name":"Work"}"#).unwrap(); + + assert!(!space.pinned); } } diff --git a/crates/engine/tests/commands/spaces.rs b/crates/engine/tests/commands/spaces.rs index c3e53a55a..ff069ddbf 100644 --- a/crates/engine/tests/commands/spaces.rs +++ b/crates/engine/tests/commands/spaces.rs @@ -2,10 +2,9 @@ use engine::attachments::{attach_file, list_attachments}; use engine::error::ErrorCode; use engine::folders::create_folder; use engine::folders::model::FolderDraft; -use engine::notes::model::HeldNotes; +use engine::notes::model::{HeldNotes, NoteDraft}; use engine::notes::{create_note, get_note, list_trash, restore_notes}; -use engine::spaces::model::SpaceContents; -use engine::spaces::model::SpaceDraft; +use engine::spaces::model::{SpaceContents, SpaceDraft}; use engine::spaces::{ count_space_contents, create_space, delete_space, list_spaces, pin_space, rename_space, }; @@ -19,177 +18,172 @@ fn named(name: &str) -> SpaceDraft { } } -/// Pinned first, then by name: the one order a space has. #[test] -fn a_space_is_renamed_and_pinned_to_the_head_of_the_list() { +fn nothing_answers_before_a_library_is_open() { + let session = Session::locked(); + + let codes = [ + code(session.call(list_spaces)), + code(session.call(|e| create_space(e, &named("Work")))), + code(session.call(|e| rename_space(e, "s", &named("Work")))), + code(session.call(|e| pin_space(e, "s", true))), + code(session.call(|e| count_space_contents(e, "s"))), + code(session.call(|e| delete_space(e, "s", "t", HeldNotes::Keep))), + ]; + + assert!( + codes.iter().all(|found| *found == ErrorCode::Locked), + "{codes:?}" + ); +} + +/// Checked before the lock: a blank name or a space as its own refuge never reaches it. +#[test] +fn a_blank_name_or_a_space_as_its_own_refuge_is_refused_as_input_first() { + let session = Session::locked(); + + for answer in [ + code(session.call(|e| create_space(e, &named(" ")))), + code(session.call(|e| rename_space(e, "s", &named("")))), + code(session.call(|e| delete_space(e, "s", "s", HeldNotes::Keep))), + ] { + assert_eq!(answer, ErrorCode::InvalidInput); + } +} + +#[test] +fn a_space_is_created_trimmed_renamed_and_pinned_to_the_head_of_the_list() { let session = Session::open(); session.space("Archive"); - let id = session.space("Personal"); + let id = session + .call(|e| create_space(e, &named(" Personal "))) + .unwrap() + .id; let renamed = session - .call(|e| rename_space(e, &id, &named("Work"))) + .call(|e| rename_space(e, &id, &named(" Work "))) .unwrap(); let pinned = session.call(|e| pin_space(e, &id, true)).unwrap(); - let listed = session.call(list_spaces).unwrap(); assert_eq!(renamed.name, "Work"); assert!(pinned.pinned); - assert_eq!(listed[0].id, id); + assert_eq!(session.spaces(), ["Work", "Archive"]); } #[test] -fn a_second_space_of_the_same_name_is_refused() { +fn a_name_taken_or_a_space_gone_is_answered_by_its_code() { let session = Session::open(); - session.space("Personal"); + session.space("Work"); - assert!(matches!( - code(session.call(|e| create_space(e, &named("personal")))), + assert_eq!( + code(session.call(|e| create_space(e, &named("work")))), ErrorCode::DuplicateSpaceName - )); -} - -#[test] -fn a_space_without_a_readable_name_is_refused() { - let session = Session::open(); - - assert!(matches!( - code(session.call(|e| create_space(e, &named(" ")))), - ErrorCode::InvalidInput - )); + ); + assert_eq!( + code(session.call(|e| rename_space(e, "missing", &named("x")))), + ErrorCode::SpaceNotFound + ); + assert_eq!( + code(session.call(|e| count_space_contents(e, "missing"))), + ErrorCode::SpaceNotFound + ); } #[test] -fn a_deleted_space_hands_its_notes_to_its_refuge() { +fn a_space_deleted_says_what_it_held_and_hands_its_notes_to_the_refuge() { let session = Session::open(); - let doomed = session.space("Personal"); - let refuge = session.space("Work"); - let note = session - .call(|e| create_note(e, snippet(&doomed))) + let work = session.space("Work"); + let home = session.space("Home"); + let folder = FolderDraft { + space_id: work.clone(), + parent_id: None, + name: "Infra".to_string(), + }; + session.call(|e| create_folder(e, &folder)).unwrap(); + let id = session + .call(|e| create_note(e, snippet(&work))) .unwrap() .note .id; - session - .call(|e| delete_space(e, &doomed, &refuge, HeldNotes::Keep)) - .unwrap(); - let moved = session.call(|e| get_note(e, ¬e)).unwrap(); - - assert_eq!(session.spaces(), ["Work"]); - assert_eq!(moved.note.space_id, refuge); -} - -/// Checked before the lock: the cascade would take the notes the moment they arrived. -#[test] -fn a_space_cannot_be_its_own_refuge() { - let session = Session::open(); - let id = session.space("Personal"); - - assert!(matches!( - code(session.call(|e| delete_space(e, &id, &id, HeldNotes::Keep))), - ErrorCode::InvalidInput - )); - assert_eq!(session.spaces(), ["Personal"]); -} - -/// What the confirmation names before a deletion, counted under the lock. -#[test] -fn a_space_counts_what_its_deletion_would_move_and_take() { - let session = Session::open(); - let id = session.space("Personal"); - session.call(|e| create_note(e, snippet(&id))).unwrap(); - session - .call(|e| { - create_folder( - e, - &FolderDraft { - space_id: id.clone(), - parent_id: None, - name: "Perf".to_string(), - }, - ) - }) + let held = session.call(|e| count_space_contents(e, &work)).unwrap(); + let moved = session + .call(|e| delete_space(e, &work, &home, HeldNotes::Keep)) .unwrap(); assert_eq!( - session.call(|e| count_space_contents(e, &id)).unwrap(), + held, SpaceContents { notes: 1, folders: 1 } ); - assert!(matches!( - code(session.call(|e| count_space_contents(e, "ghost"))), - ErrorCode::SpaceNotFound - )); + assert_eq!(moved, 1); + assert_eq!(session.spaces(), ["Home"]); + assert_eq!(session.call(|e| get_note(e, &id)).unwrap().space_id, home); + assert_eq!(session.call(engine::Engine::index_matches_library), Ok(())); } -/// Nothing is erased: the notes wait in the trash, and come back into the refuge chosen. +/// Trashed, they still go to the refuge, which a restore brings them back into. +/// Nothing is erased: a note trashed on the way keeps its attachment and comes back into the +/// refuge, out of its folder; the refuge's own notes are not touched. #[test] -fn a_space_deleted_with_its_notes_trashes_them_for_the_refuge_to_take_back() { +fn a_space_deleted_with_its_notes_to_the_trash_lets_them_come_back_in_the_refuge() { let scratch = tempfile::tempdir().unwrap(); let session = Session::on_disk(scratch.path()); - let doomed = session.space("Personal"); - let refuge = session.space("Work"); - let shelf = session - .call(|e| { - let draft = FolderDraft { - space_id: doomed.clone(), - parent_id: None, - name: "Shelf".to_string(), - }; - create_folder(e, &draft) - }) - .unwrap() - .id; - let doomed_note = session - .call(|e| create_note(e, snippet(&doomed))) - .unwrap() - .note - .id; - session - .call(|e| { - let ids = [doomed_note.clone()]; - let lines = engine::folders::board::PreviewLines::default(); - engine::folders::file_notes(e, &ids, Some(&shelf), lines) - }) - .unwrap(); - let kept = session - .call(|e| create_note(e, snippet(&refuge))) + let work = session.space("Work"); + let home = session.space("Home"); + let shelf = FolderDraft { + space_id: work.clone(), + parent_id: None, + name: "Shelf".to_string(), + }; + let shelf = session.call(|e| create_folder(e, &shelf)).unwrap().id; + let filed = NoteDraft { + folder_id: Some(shelf), + ..snippet(&work) + }; + let id = session.call(|e| create_note(e, filed)).unwrap().note.id; + let resident = session + .call(|e| create_note(e, snippet(&home))) .unwrap() .note .id; - let source = scratch.path().join("capture.png"); - std::fs::write(&source, b"\x89PNG").unwrap(); - session - .wait(|e| attach_file(e, doomed_note.clone(), source.to_string_lossy().to_string())) - .unwrap(); + let picture = scratch.path().join("capture.png"); + std::fs::write(&picture, b"\x89PNG").unwrap(); + let path = picture.to_string_lossy().to_string(); + session.wait(|e| attach_file(e, id.clone(), path)).unwrap(); - let moved = session - .call(|e| delete_space(e, &doomed, &refuge, HeldNotes::Trash)) + let trashed = session + .call(|e| delete_space(e, &work, &home, HeldNotes::Trash)) .unwrap(); - assert_eq!(moved, 1); - assert_eq!(session.spaces(), ["Work"]); + assert_eq!(trashed, 1); let trash = session.call(|e| list_trash(e, "")).unwrap(); - let trashed: Vec<&str> = trash.iter().map(|row| row.note.id.as_str()).collect(); assert_eq!( - trashed, - [doomed_note.as_str()], - "the refuge's own notes stay" + trash.iter().map(|row| &row.note.id).collect::>(), + [&id] ); - assert!(session.call(|e| get_note(e, &kept)).is_ok()); - + assert!(session.call(|e| get_note(e, &resident)).is_ok()); session - .call(|e| restore_notes(e, std::slice::from_ref(&doomed_note))) + .call(|e| restore_notes(e, std::slice::from_ref(&id))) .unwrap(); - let back = session.call(|e| get_note(e, &doomed_note)).unwrap(); - assert_eq!(back.note.space_id, refuge); - assert_eq!(back.note.folder_id, None); + let back = session.call(|e| get_note(e, &id)).unwrap(); assert_eq!( - session - .call(|e| list_attachments(e, &doomed_note)) - .unwrap() - .len(), - 1 + (back.space_id.as_str(), back.folder_id.as_deref()), + (home.as_str(), None) ); + assert_eq!(session.call(|e| list_attachments(e, &id)).unwrap().len(), 1); +} + +#[test] +fn a_space_deleted_into_a_refuge_that_does_not_exist_is_answered_by_its_code() { + let session = Session::open(); + let work = session.space("Work"); + + assert_eq!( + code(session.call(|e| delete_space(e, &work, "nowhere", HeldNotes::Keep))), + ErrorCode::SpaceNotFound + ); + assert_eq!(session.spaces(), ["Work"]); } diff --git a/crates/engine/tests/spaces.rs b/crates/engine/tests/spaces.rs index 83101d631..8b8d3b8eb 100644 --- a/crates/engine/tests/spaces.rs +++ b/crates/engine/tests/spaces.rs @@ -1,33 +1,16 @@ use diesel::prelude::*; use engine::db::Library; - use engine::db::open_in_memory; -use engine::db::schema::notes; +use engine::db::schema::{notes, spaces as spaces_table}; use engine::error::StorageError; +use engine::notes::model::NoteDraft; +use engine::notes::store as note_store; use engine::spaces::model::SpaceContents; use engine::spaces::store::{contents, create, delete, exists, list, rename, set_pinned}; -const T0: &str = "2026-07-25T09:00:00.000Z"; - -/// A note written straight into the database: going through `notes::create` would -/// drag its own rules in. -fn note_in(connection: &mut Library, space_id: &str) { - diesel::insert_into(notes::table) - .values(( - notes::id.eq("n-1"), - notes::space_id.eq(space_id), - notes::title.eq("A"), - notes::language.eq("txt"), - notes::content.eq(""), - notes::source.eq(""), - notes::pinned.eq(false), - notes::created_at.eq(T0), - notes::updated_at.eq(T0), - notes::lifecycle_kind.eq("permanent"), - )) - .execute(connection.db()) - .unwrap(); -} +#[path = "common/mod.rs"] +mod common; +use common::{snippet, t0, t1}; fn names(connection: &mut Library) -> Vec { list(connection) @@ -37,286 +20,244 @@ fn names(connection: &mut Library) -> Vec { .collect() } -#[test] -fn a_created_space_is_listed_back() { - let mut connection = open_in_memory().unwrap(); - - let created = create(&mut connection, "Personal").unwrap(); - let listed = list(&mut connection).unwrap(); - - assert_eq!(listed.len(), 1); - assert_eq!(listed[0].id, created.id); - assert_eq!(listed[0].name, "Personal"); -} - -#[test] -fn each_space_gets_its_own_identifier() { - let mut connection = open_in_memory().unwrap(); - - let first = create(&mut connection, "Personal").unwrap(); - let second = create(&mut connection, "Boulot").unwrap(); - - assert_ne!(first.id, second.id); +fn note_in(connection: &mut Library, space_id: &str, folder_id: Option) -> String { + let draft = NoteDraft { + folder_id, + ..snippet(space_id) + }; + note_store::create(connection, draft, t0()).unwrap().id } -#[test] -fn spaces_are_listed_in_name_order() { - let mut connection = open_in_memory().unwrap(); - - create(&mut connection, "Veille").unwrap(); - create(&mut connection, "Boulot").unwrap(); - create(&mut connection, "personal").unwrap(); - - assert_eq!(names(&mut connection), ["Boulot", "personal", "Veille"]); -} - -/// Name order alone put the space opened every morning wherever its initial fell, -/// under archives nobody touches. Pinning is the gesture the app already has for -/// "keep this within reach", and it hoists here the way it does on the canvas. -#[test] -fn a_pinned_space_comes_first_whatever_its_name() { - let mut connection = open_in_memory().unwrap(); - create(&mut connection, "Boulot").unwrap(); - let veille = create(&mut connection, "Veille").unwrap(); - create(&mut connection, "Archive").unwrap(); - - set_pinned(&mut connection, &veille.id, true).unwrap(); - - assert_eq!(names(&mut connection), ["Veille", "Archive", "Boulot"]); +fn folder_in(connection: &mut Library, space_id: &str, name: &str) -> String { + engine::folders::store::create(connection, space_id, None, name, t0()) + .unwrap() + .id } #[test] -fn pinned_spaces_are_still_sorted_among_themselves() { +fn a_library_starts_with_no_space() { let mut connection = open_in_memory().unwrap(); - let veille = create(&mut connection, "Veille").unwrap(); - let boulot = create(&mut connection, "Boulot").unwrap(); - create(&mut connection, "Archive").unwrap(); - - set_pinned(&mut connection, &veille.id, true).unwrap(); - set_pinned(&mut connection, &boulot.id, true).unwrap(); - assert_eq!(names(&mut connection), ["Boulot", "Veille", "Archive"]); + assert!(list(&mut connection).unwrap().is_empty()); } #[test] -fn unpinning_lets_a_space_fall_back_among_the_others() { +fn a_space_created_is_listed_under_its_name_and_exists() { let mut connection = open_in_memory().unwrap(); - let veille = create(&mut connection, "Veille").unwrap(); - create(&mut connection, "Archive").unwrap(); - set_pinned(&mut connection, &veille.id, true).unwrap(); - let unpinned = set_pinned(&mut connection, &veille.id, false).unwrap(); + let space = create(&mut connection, "Work").unwrap(); - assert!(!unpinned.pinned); - assert_eq!(names(&mut connection), ["Archive", "Veille"]); + assert_eq!((space.name.as_str(), space.pinned), ("Work", false)); + assert_eq!(names(&mut connection), ["Work"]); + assert!(exists(connection.db(), &space.id).unwrap()); + assert!(!exists(connection.db(), "missing").unwrap()); } -/// A rename answers with the row it read back, not with what it was sent — which -/// is what keeps it from quietly reporting a pinned space as unpinned. #[test] -fn renaming_a_pinned_space_leaves_it_pinned() { +fn a_space_s_name_is_sealed_in_its_column() { let mut connection = open_in_memory().unwrap(); - let space = create(&mut connection, "Veille").unwrap(); - set_pinned(&mut connection, &space.id, true).unwrap(); + create(&mut connection, "Secret project").unwrap(); - let renamed = rename(&mut connection, &space.id, "Veille technique").unwrap(); + let stored: String = spaces_table::table + .select(spaces_table::name) + .first(connection.db()) + .unwrap(); - assert!(renamed.pinned); + assert!(!stored.contains("Secret")); } #[test] -fn pinning_a_space_that_is_gone_says_which_one() { +fn a_name_held_by_another_space_whatever_its_case_is_refused() { let mut connection = open_in_memory().unwrap(); + create(&mut connection, "Work").unwrap(); + let home = create(&mut connection, "Home").unwrap(); - let error = set_pinned(&mut connection, "missing", true).unwrap_err(); - - assert!(matches!(error, StorageError::SpaceNotFound(id) if id == "missing")); + assert!(matches!( + create(&mut connection, "WORK"), + Err(StorageError::DuplicateSpaceName(name)) if name == "WORK" + )); + assert!(matches!( + rename(&mut connection, &home.id, "work"), + Err(StorageError::DuplicateSpaceName(_)) + )); + assert_eq!(names(&mut connection), ["Home", "Work"]); } #[test] -fn a_duplicate_name_is_refused_regardless_of_case() { +fn a_space_renamed_may_correct_its_own_case() { let mut connection = open_in_memory().unwrap(); - create(&mut connection, "Personal").unwrap(); - - let error = create(&mut connection, "PERSONAL").unwrap_err(); + let space = create(&mut connection, "work").unwrap(); - assert!(matches!(error, StorageError::DuplicateSpaceName(_))); - assert_eq!(list(&mut connection).unwrap().len(), 1); -} - -#[test] -fn exists_distinguishes_known_from_unknown_identifiers() { - let mut connection = open_in_memory().unwrap(); - let space = create(&mut connection, "Personal").unwrap(); + let renamed = rename(&mut connection, &space.id, "Work").unwrap(); - assert!(exists(connection.db(), &space.id).unwrap()); - assert!(!exists(connection.db(), "unknown").unwrap()); + assert_eq!(renamed.name, "Work"); + assert_eq!(names(&mut connection), ["Work"]); } +/// A rename answers the row read back, not what it was sent: a pinned space stays pinned. #[test] -fn a_renamed_space_keeps_its_identifier() { +fn a_space_renamed_keeps_its_identifier_and_its_pin() { let mut connection = open_in_memory().unwrap(); let space = create(&mut connection, "Personal").unwrap(); + set_pinned(&mut connection, &space.id, true).unwrap(); let renamed = rename(&mut connection, &space.id, "Personnel").unwrap(); - assert_eq!(renamed.id, space.id); - assert_eq!(renamed.name, "Personnel"); - assert_eq!(list(&mut connection).unwrap()[0].name, "Personnel"); + assert_eq!((renamed.id, renamed.pinned), (space.id, true)); } #[test] -fn a_space_can_be_renamed_to_a_different_case_of_its_own_name() { +fn renaming_or_pinning_a_space_that_is_not_there_fails_by_name() { let mut connection = open_in_memory().unwrap(); - let space = create(&mut connection, "personal").unwrap(); - - let renamed = rename(&mut connection, &space.id, "Personal").unwrap(); - assert_eq!(renamed.name, "Personal"); + assert!(matches!( + rename(&mut connection, "missing", "x"), + Err(StorageError::SpaceNotFound(id)) if id == "missing" + )); + assert!(matches!( + set_pinned(&mut connection, "missing", true), + Err(StorageError::SpaceNotFound(_)) + )); } +/// The names are sealed: the order is decided in Rust, case aside. #[test] -fn renaming_onto_another_space_name_is_refused() { +fn spaces_list_pinned_first_then_by_name_case_aside() { let mut connection = open_in_memory().unwrap(); - create(&mut connection, "Boulot").unwrap(); - let space = create(&mut connection, "Personal").unwrap(); - - let error = rename(&mut connection, &space.id, "BOULOT").unwrap_err(); - - assert!(matches!(error, StorageError::DuplicateSpaceName(_))); - assert_eq!(list(&mut connection).unwrap()[1].name, "Personal"); + for name in ["zebra", "Alpha", "beta", "Gamma"] { + create(&mut connection, name).unwrap(); + } + let id = |connection: &mut Library, name: &str| { + let spaces = list(connection).unwrap(); + spaces + .into_iter() + .find(|space| space.name == name) + .unwrap() + .id + }; + let (zebra, gamma) = (id(&mut connection, "zebra"), id(&mut connection, "Gamma")); + + let pinned = set_pinned(&mut connection, &zebra, true).unwrap(); + set_pinned(&mut connection, &gamma, true).unwrap(); + + assert!(pinned.pinned); + assert_eq!(names(&mut connection), ["Gamma", "zebra", "Alpha", "beta"]); + set_pinned(&mut connection, &gamma, false).unwrap(); + assert_eq!(names(&mut connection), ["zebra", "Alpha", "beta", "Gamma"]); } #[test] -fn renaming_an_unknown_space_reports_an_error() { +fn a_space_s_contents_are_its_live_notes_and_its_folders() { let mut connection = open_in_memory().unwrap(); + let work = create(&mut connection, "Work").unwrap().id; + let home = create(&mut connection, "Home").unwrap().id; + folder_in(&mut connection, &work, "Infra"); + note_in(&mut connection, &work, None); + let trashed = note_in(&mut connection, &work, None); + note_store::trash::trash(&mut connection, &trashed, t1()).unwrap(); + note_in(&mut connection, &home, None); - let error = rename(&mut connection, "unknown", "Personal").unwrap_err(); - - assert!(matches!(error, StorageError::SpaceNotFound(_))); + assert_eq!( + contents(&mut connection, &work).unwrap(), + SpaceContents { + notes: 1, + folders: 1 + } + ); + assert!(matches!( + contents(&mut connection, "missing"), + Err(StorageError::SpaceNotFound(_)) + )); } +/// The notes move to the refuge, out of their folder, the trashed ones too; the folders go. #[test] -fn deleting_a_space_moves_its_notes_to_the_target() { +fn deleting_a_space_gives_its_notes_to_the_refuge_and_takes_its_folders() { let mut connection = open_in_memory().unwrap(); - let doomed = create(&mut connection, "Personal").unwrap(); - let refuge = create(&mut connection, "Boulot").unwrap(); - note_in(&mut connection, &doomed.id); - - delete(&mut connection, &doomed.id, &refuge.id, None).unwrap(); - - let space_id = notes::table - .find("n-1") + let work = create(&mut connection, "Work").unwrap().id; + let home = create(&mut connection, "Home").unwrap().id; + let folder = folder_in(&mut connection, &work, "Infra"); + let filed = note_in(&mut connection, &work, Some(folder)); + let trashed = note_in(&mut connection, &work, None); + note_store::trash::trash(&mut connection, &trashed, t1()).unwrap(); + let already_home = note_in(&mut connection, &home, None); + + let moved = delete(&mut connection, &work, &home, None).unwrap(); + + assert_eq!(moved, 1); + assert_eq!(names(&mut connection), ["Home"]); + let read = note_store::get(&mut connection, &filed).unwrap(); + assert_eq!( + (read.space_id.as_str(), read.folder_id), + (home.as_str(), None) + ); + assert_eq!(read.updated_at, t0()); + let trashed_space: String = notes::table + .find(&trashed) .select(notes::space_id) - .first::(connection.db()) + .first(connection.db()) .unwrap(); - assert_eq!(space_id, refuge.id); - assert_eq!(list(&mut connection).unwrap().len(), 1); -} - -#[test] -fn moving_notes_out_of_a_deleted_space_does_not_touch_their_timestamps() { - let mut connection = open_in_memory().unwrap(); - let doomed = create(&mut connection, "Personal").unwrap(); - let refuge = create(&mut connection, "Boulot").unwrap(); - note_in(&mut connection, &doomed.id); - - delete(&mut connection, &doomed.id, &refuge.id, None).unwrap(); - - let updated_at = notes::table - .find("n-1") - .select(notes::updated_at) - .first::(connection.db()) - .unwrap(); - assert_eq!(updated_at, T0); -} - -#[test] -fn deleting_an_empty_space_leaves_the_others_alone() { - let mut connection = open_in_memory().unwrap(); - let doomed = create(&mut connection, "Personal").unwrap(); - let refuge = create(&mut connection, "Boulot").unwrap(); - - delete(&mut connection, &doomed.id, &refuge.id, None).unwrap(); - - assert_eq!(names(&mut connection), ["Boulot"]); -} - -#[test] -fn deleting_an_unknown_space_reports_an_error() { - let mut connection = open_in_memory().unwrap(); - let refuge = create(&mut connection, "Boulot").unwrap(); - - let error = delete(&mut connection, "unknown", &refuge.id, None).unwrap_err(); - - assert!(matches!(error, StorageError::SpaceNotFound(_))); + assert_eq!(trashed_space, home); + assert!( + engine::folders::store::list(&mut connection, None) + .unwrap() + .is_empty() + ); + assert_eq!( + note_store::get(&mut connection, &already_home) + .unwrap() + .space_id, + home + ); } #[test] -fn deleting_into_an_unknown_space_changes_nothing() { +fn deleting_a_space_may_send_its_live_notes_to_the_trash_on_the_way() { let mut connection = open_in_memory().unwrap(); - let doomed = create(&mut connection, "Personal").unwrap(); - note_in(&mut connection, &doomed.id); - - let error = delete(&mut connection, &doomed.id, "unknown", None).unwrap_err(); - - assert!(matches!(error, StorageError::SpaceNotFound(_))); - assert_eq!(list(&mut connection).unwrap().len(), 1); - assert_eq!( - notes::table - .count() - .get_result::(connection.db()) - .unwrap(), - 1 + let work = create(&mut connection, "Work").unwrap().id; + let home = create(&mut connection, "Home").unwrap().id; + let first = note_in(&mut connection, &work, None); + note_in(&mut connection, &work, None); + let resident = note_in(&mut connection, &home, None); + + let trashed = delete(&mut connection, &work, &home, Some(t1())).unwrap(); + + assert_eq!(trashed, 2); + let in_trash = note_store::trash::list_trashed(&mut connection).unwrap(); + assert_eq!(in_trash.len(), 2); + assert!( + in_trash + .iter() + .all(|(note, at)| note.space_id == home && *at == t1()) ); + assert!(in_trash.iter().any(|(note, _)| note.id == first)); + assert!(note_store::get(&mut connection, &resident).is_ok()); } -/// What the confirmation names before a deletion: the live notes and the folders. #[test] -fn a_space_counts_its_notes_and_its_folders_for_the_confirmation() { +fn deleting_into_a_refuge_that_does_not_exist_changes_nothing() { let mut connection = open_in_memory().unwrap(); - let doomed = create(&mut connection, "Perso").unwrap(); - let other = create(&mut connection, "Boulot").unwrap(); - note_in(&mut connection, &doomed.id); - engine::folders::store::create( - &mut connection, - &doomed.id, - None, - "Perf", - T0.parse().unwrap(), - ) - .unwrap(); - engine::folders::store::create( - &mut connection, - &other.id, - None, - "Ailleurs", - T0.parse().unwrap(), - ) - .unwrap(); + let work = create(&mut connection, "Work").unwrap().id; + let id = note_in(&mut connection, &work, None); + assert!(matches!( + delete(&mut connection, &work, "nowhere", None), + Err(StorageError::SpaceNotFound(space)) if space == "nowhere" + )); + assert_eq!(names(&mut connection), ["Work"]); assert_eq!( - contents(&mut connection, &doomed.id).unwrap(), - SpaceContents { - notes: 1, - folders: 1 - } - ); - assert_eq!( - contents(&mut connection, &other.id).unwrap(), - SpaceContents { - notes: 0, - folders: 1 - } + note_store::get(&mut connection, &id).unwrap().space_id, + work ); } #[test] -fn counting_a_space_that_is_gone_says_which_one() { +fn deleting_a_space_that_is_not_there_fails_by_name() { let mut connection = open_in_memory().unwrap(); + let home = create(&mut connection, "Home").unwrap().id; assert!(matches!( - contents(&mut connection, "ghost"), - Err(StorageError::SpaceNotFound(id)) if id == "ghost" + delete(&mut connection, "missing", &home, None), + Err(StorageError::SpaceNotFound(id)) if id == "missing" )); } From a17217531502eed07ce9c1879fb3f0f78e3311db Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 07:04:42 +0100 Subject: [PATCH 20/95] Folders: unit tests rewritten for the store and the tree (#1742) Co-authored-by: Claude Opus 5.5 --- crates/engine/src/folders/model.rs | 274 ++- crates/engine/tests/folders.rs | 2113 ------------------ crates/engine/tests/folders/board.rs | 722 ++++++ crates/engine/tests/folders/gesture.rs | 458 ++++ crates/engine/tests/folders/main.rs | 67 + crates/engine/tests/folders/nested_boards.rs | 179 ++ crates/engine/tests/folders/nesting.rs | 270 +++ crates/engine/tests/folders/store.rs | 662 ++++++ 8 files changed, 2539 insertions(+), 2206 deletions(-) delete mode 100644 crates/engine/tests/folders.rs create mode 100644 crates/engine/tests/folders/board.rs create mode 100644 crates/engine/tests/folders/gesture.rs create mode 100644 crates/engine/tests/folders/main.rs create mode 100644 crates/engine/tests/folders/nested_boards.rs create mode 100644 crates/engine/tests/folders/nesting.rs create mode 100644 crates/engine/tests/folders/store.rs diff --git a/crates/engine/src/folders/model.rs b/crates/engine/src/folders/model.rs index 7f28d7342..b54b8167b 100644 --- a/crates/engine/src/folders/model.rs +++ b/crates/engine/src/folders/model.rs @@ -292,138 +292,226 @@ impl FolderDraft { mod tests { use super::*; + fn tree(links: &[(&str, Option<&str>)]) -> Lineage { + Lineage::new( + links + .iter() + .map(|(id, parent)| ((*id).to_string(), parent.map(str::to_string))), + ) + } + + /// a ─ b ─ c, and a ─ d, made in that order; e alone at the top. + fn sample() -> Lineage { + tree(&[ + ("a", None), + ("b", Some("a")), + ("c", Some("b")), + ("d", Some("a")), + ("e", None), + ]) + } + + /// f1 ─ f2 ─ … ─ f8, as deep as folders nest, beside `others`. + fn deepest(others: &[(&str, Option<&str>)]) -> Lineage { + let ids: Vec = (1..=MAX_DEPTH).map(|n| format!("f{n}")).collect(); + let chain = ids + .iter() + .enumerate() + .map(|(at, id)| (id.clone(), at.checked_sub(1).map(|up| ids[up].clone()))); + let others = others + .iter() + .map(|(id, parent)| ((*id).to_string(), parent.map(str::to_string))); + Lineage::new(chain.chain(others)) + } + #[test] - fn a_name_is_trimmed_before_being_stored() { - assert_eq!(validated_name(" Perf ").unwrap(), "Perf"); + fn colours_are_handed_out_round_the_palette() { + let first: Vec = (0..6).map(FolderColour::nth).collect(); + + assert_eq!( + first, + [ + FolderColour::Blue, + FolderColour::Amber, + FolderColour::Purple, + FolderColour::Green, + FolderColour::Red, + FolderColour::Blue, + ] + ); } + /// A file written before folders nested or had a colour. #[test] - fn the_palette_rotates_and_wraps() { - assert_eq!(FolderColour::nth(0), FolderColour::Blue); - assert_eq!(FolderColour::nth(1), FolderColour::Amber); + fn a_folder_read_without_a_parent_or_a_colour_is_blue_at_the_top() { + let folder: Folder = serde_json::from_str( + r#"{"id":"f","spaceId":"s","name":"Perf","createdAt":"2026-07-25T09:00:00Z"}"#, + ) + .unwrap(); + assert_eq!( - FolderColour::nth(FolderColour::ALL.len()), - FolderColour::Blue + (folder.parent_id, folder.colour), + (None, FolderColour::Blue) ); } - fn tree() -> Lineage { - // sql ─ perf ─ index - // └ migrations - // angular - Lineage::new([ - ("sql".to_string(), None), - ("perf".to_string(), Some("sql".to_string())), - ("migrations".to_string(), Some("sql".to_string())), - ("index".to_string(), Some("perf".to_string())), - ("angular".to_string(), None), - ("orphan".to_string(), Some("gone".to_string())), - ]) + #[test] + fn a_folder_s_name_is_read_trimmed_and_never_blank() { + let draft = |name: &str| FolderDraft { + space_id: "s".to_string(), + name: name.to_string(), + parent_id: None, + }; + + assert_eq!(draft(" Perf\t").validated_name(), Ok("Perf".to_string())); + assert_eq!(validated_name(" ").unwrap_err().field, "name"); } #[test] - fn a_sub_tree_holds_the_folder_and_everything_under_it() { - let lineage = tree(); + fn a_folder_whose_parent_is_not_in_the_list_stands_at_the_top() { + let lineage = tree(&[("a", Some("gone"))]); - assert_eq!( - lineage.subtree("sql"), - ["sql", "perf", "migrations", "index"] - ); - assert_eq!(lineage.subtree("index"), ["index"]); - assert!(lineage.subtree("nowhere").is_empty()); + assert_eq!(lineage.parent("a"), None); + assert_eq!(lineage.children(None), ["a"]); + assert!(!lineage.contains("gone")); + } + + #[test] + fn children_are_listed_in_the_order_the_folders_were_handed_over() { + let lineage = sample(); + + assert_eq!(lineage.children(None), ["a", "e"]); + assert_eq!(lineage.children(Some("a")), ["b", "d"]); + assert!(lineage.children(Some("c")).is_empty()); + assert!(lineage.children(Some("unknown")).is_empty()); } #[test] - fn a_path_runs_from_the_top_down_and_a_lost_parent_is_the_top() { - let lineage = tree(); + fn a_subtree_is_the_folder_first_then_everything_under_it() { + let lineage = sample(); - assert_eq!(lineage.path("index"), ["sql", "perf", "index"]); - assert_eq!(lineage.path("orphan"), ["orphan"]); - assert_eq!(lineage.children(None), ["sql", "angular", "orphan"]); - assert_eq!(lineage.depth("index"), 3); - assert_eq!(lineage.height("sql"), 3); - assert_eq!(lineage.height("angular"), 1); + assert_eq!(lineage.subtree("a"), ["a", "b", "d", "c"]); + assert_eq!(lineage.subtree("c"), ["c"]); + assert!(lineage.subtree("unknown").is_empty()); } #[test] - fn a_cycle_a_damaged_row_makes_is_walked_once() { - let lineage = Lineage::new([ - ("a".to_string(), Some("b".to_string())), - ("b".to_string(), Some("a".to_string())), - ]); + fn a_path_runs_from_the_top_of_the_space_down_and_its_length_is_the_depth() { + let lineage = sample(); - assert_eq!(lineage.subtree("a"), ["a", "b"]); - assert_eq!(lineage.path("a"), ["b", "a"]); + assert_eq!(lineage.path("c"), ["a", "b", "c"]); + assert_eq!((lineage.depth("a"), lineage.depth("c")), (1, 3)); + assert!(lineage.path("unknown").is_empty()); + assert_eq!(lineage.depth("unknown"), 0); } #[test] - fn a_note_sits_in_the_zone_of_the_child_that_holds_its_folder() { - let lineage = tree(); + fn the_height_is_how_many_levels_a_folder_takes_with_it() { + let lineage = sample(); + assert_eq!(lineage.height("a"), 3); + assert_eq!(lineage.height("b"), 2); + assert_eq!(lineage.height("e"), 1); + assert_eq!(lineage.height("unknown"), 0); + } + + /// Two rows naming each other, which only a damaged library holds. + #[test] + fn a_cycle_is_walked_once() { + let lineage = tree(&[("x", Some("y")), ("y", Some("x"))]); + + assert_eq!(lineage.subtree("x"), ["x", "y"]); + assert_eq!(lineage.path("x"), ["y", "x"]); + } + + #[test] + fn a_note_sits_in_the_zone_of_the_board_s_child_that_holds_its_folder() { + let lineage = sample(); + let zone = |id: &str| Seat::Zone(id.to_string()); + let cases = [ + (None, None, Seat::Free), + (Some("a"), Some("a"), Seat::Free), + (Some("a"), None, Seat::Elsewhere), + (None, Some("c"), zone("a")), + (Some("a"), Some("c"), zone("b")), + (Some("a"), Some("d"), zone("d")), + (Some("b"), Some("d"), Seat::Elsewhere), + (Some("e"), Some("c"), Seat::Elsewhere), + (None, Some("unknown"), Seat::Elsewhere), + ]; + + for (root, folder, seat) in cases { + assert_eq!(lineage.seat(root, folder), seat, "{root:?} {folder:?}"); + } + } + + #[test] + fn a_folder_is_made_at_the_top_or_under_a_folder_of_the_space_short_of_the_deepest() { + let lineage = deepest(&[]); + + assert_eq!(lineage.check_child(None), Ok(())); + assert_eq!(lineage.check_child(Some("f7")), Ok(())); assert_eq!( - lineage.seat(None, Some("index")), - Seat::Zone("sql".to_string()) + lineage.check_child(Some("f8")).unwrap_err().field, + "parentId" ); - assert_eq!(lineage.seat(None, None), Seat::Free); assert_eq!( - lineage.seat(Some("sql"), Some("index")), - Seat::Zone("perf".to_string()) + lineage.check_child(Some("elsewhere")).unwrap_err().field, + "parentId" ); - assert_eq!(lineage.seat(Some("sql"), Some("sql")), Seat::Free); - assert_eq!(lineage.seat(Some("sql"), Some("angular")), Seat::Elsewhere); - assert_eq!(lineage.seat(Some("sql"), None), Seat::Elsewhere); } #[test] - fn a_folder_never_moves_into_itself_nor_out_of_its_space() { - let lineage = tree(); - - assert!(lineage.check_move("sql", Some("index")).is_err()); - assert!(lineage.check_move("sql", Some("sql")).is_err()); - assert!(lineage.check_move("perf", Some("elsewhere")).is_err()); - assert!(lineage.check_move("perf", None).is_ok()); - assert!(lineage.check_move("angular", Some("index")).is_ok()); + fn a_folder_never_moves_into_itself_or_what_it_holds() { + let lineage = sample(); + + for into in ["a", "b", "c"] { + assert_eq!( + lineage.check_move("a", Some(into)).unwrap_err().field, + "parentId" + ); + } + assert_eq!(lineage.check_move("b", Some("e")), Ok(())); + assert_eq!(lineage.check_move("b", None), Ok(())); } + /// The sub-tree counts whole: f7 under f6 brings f8 with it. #[test] - fn nesting_stops_at_its_depth_and_counts_what_a_folder_brings() { - let chain: Vec<(String, Option)> = (0..MAX_DEPTH) - .map(|level| { - ( - format!("f{level}"), - level.checked_sub(1).map(|up| format!("f{up}")), - ) - }) - .chain([ - ("tall".to_string(), None), - ("below".to_string(), Some("tall".to_string())), - ]) - .collect(); - let lineage = Lineage::new(chain); - let deepest = format!("f{}", MAX_DEPTH - 1); - - assert!(lineage.check_child(Some(&deepest)).is_err()); - assert!( - lineage - .check_child(Some(&format!("f{}", MAX_DEPTH - 2))) - .is_ok() - ); - assert!( - lineage - .check_move("tall", Some(&format!("f{}", MAX_DEPTH - 2))) - .is_err() + fn a_folder_moves_only_where_everything_it_holds_stays_within_the_deepest_level() { + let lineage = deepest(&[("g", None), ("h", Some("g"))]); + + assert_eq!(lineage.check_move("g", Some("f6")), Ok(())); + assert_eq!( + lineage.check_move("g", Some("f7")).unwrap_err().field, + "parentId" ); - assert!( + assert_eq!(lineage.check_move("h", Some("f7")), Ok(())); + assert_eq!(lineage.check_move("unknown", Some("f7")), Ok(())); + assert_eq!( lineage - .check_move("tall", Some(&format!("f{}", MAX_DEPTH - 3))) - .is_ok() + .check_move("g", Some("elsewhere")) + .unwrap_err() + .field, + "parentId" ); } #[test] - fn every_colour_survives_its_stored_spelling() { - for colour in FolderColour::ALL { - assert_eq!(colour.as_str().parse::(), Ok(colour)); - } + fn a_sub_tree_arriving_from_another_space_counts_its_levels_under_its_new_parent() { + let lineage = deepest(&[]); + + assert_eq!(lineage.check_arrival(Some("f6"), 2), Ok(())); + assert_eq!( + lineage.check_arrival(Some("f7"), 2).unwrap_err().field, + "parentId" + ); + assert_eq!(lineage.check_arrival(None, MAX_DEPTH), Ok(())); + assert_eq!( + lineage + .check_arrival(Some("elsewhere"), 1) + .unwrap_err() + .field, + "parentId" + ); } } diff --git a/crates/engine/tests/folders.rs b/crates/engine/tests/folders.rs deleted file mode 100644 index 81527d96a..000000000 --- a/crates/engine/tests/folders.rs +++ /dev/null @@ -1,2113 +0,0 @@ -//! The folder as data: a region of a space that notes are filed into, and that never -//! takes a note with it when it goes. - -use std::collections::HashMap; - -use engine::db::{Library, iso8601, open_in_memory}; -use engine::error::StorageError; -use engine::folders::model::{FolderColour, Lineage, NoteFiling}; -use engine::folders::store::{create, delete, file_many, list, recolour, rename, restore_filings}; -use engine::notes::kind::NoteKind; -use engine::notes::language::Language; -use engine::notes::model::{Note, NoteDraft, NotePatch}; -use engine::notes::priority::Priority; -use engine::notes::store::{create as create_note, update}; -use engine::spaces::store as spaces; - -/// A four-line card, the default `PreviewLines`: what the board's geometry is sized from. -const CARD: i32 = 140; - -mod common; -use common::{at, snippet as draft, space, t0, t1}; - -fn note_in(connection: &mut Library, space_id: &str) -> Note { - create_note(connection, draft(space_id), t0()).unwrap() -} - -fn folder_of(connection: &mut Library, note_id: &str) -> Option { - use diesel::prelude::*; - use engine::db::schema::notes; - - notes::table - .find(note_id) - .select(notes::folder_id) - .first::>(connection.db()) - .unwrap() -} - -fn updated_at_of(connection: &mut Library, note_id: &str) -> String { - use diesel::prelude::*; - use engine::db::schema::notes; - - notes::table - .find(note_id) - .select(notes::updated_at) - .first::(connection.db()) - .unwrap() -} - -fn names(connection: &mut Library, space_id: &str) -> Vec { - list(connection, Some(space_id)) - .unwrap() - .into_iter() - .map(|folder| folder.name) - .collect() -} - -#[test] -fn a_created_folder_is_listed_back_inside_its_space() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let other = space(&mut connection, "Veille"); - - let created = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - create(&mut connection, &other, None, "Liens", t0()).unwrap(); - - let listed = list(&mut connection, Some(&sql)).unwrap(); - assert_eq!(listed.len(), 1); - assert_eq!(listed[0].id, created.id); - assert_eq!(listed[0].name, "Perf"); - assert_eq!(listed[0].space_id, sql); -} - -/// Reading order, which is the order the board lays its zones out in — and which a -/// rename must not reshuffle. -#[test] -fn folders_come_back_in_the_order_they_were_made() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - - create( - &mut connection, - &sql, - None, - "Migrations", - at("2026-07-25T09:00:00.000Z"), - ) - .unwrap(); - create( - &mut connection, - &sql, - None, - "Perf", - at("2026-07-25T09:30:00.000Z"), - ) - .unwrap(); - let reporting = create( - &mut connection, - &sql, - None, - "Reporting", - at("2026-07-25T10:00:00.000Z"), - ) - .unwrap(); - - rename(&mut connection, &reporting.id, "Analytics").unwrap(); - - assert_eq!( - names(&mut connection, &sql), - ["Migrations", "Perf", "Analytics"] - ); -} - -/// Assigned rather than chosen: drawing a folder stays one gesture, and two made back -/// to back must not come out the same colour. -#[test] -fn the_palette_rotates_so_neighbours_differ() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - - let first = create(&mut connection, &sql, None, "Migrations", t0()).unwrap(); - let second = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - - assert_ne!(first.colour, second.colour); - assert_eq!(first.colour, FolderColour::nth(0)); - assert_eq!(second.colour, FolderColour::nth(1)); -} - -/// Each space starts the rotation over: its own board is what a colour tells apart. -#[test] -fn the_rotation_is_counted_inside_one_space() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let veille = space(&mut connection, "Veille"); - - create(&mut connection, &sql, None, "Migrations", t0()).unwrap(); - create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let elsewhere = create(&mut connection, &veille, None, "Liens", t0()).unwrap(); - - assert_eq!(elsewhere.colour, FolderColour::nth(0)); -} - -#[test] -fn a_folder_can_be_given_another_colour() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let folder = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - - let recoloured = recolour(&mut connection, &folder.id, FolderColour::Red).unwrap(); - - assert_eq!(recoloured.colour, FolderColour::Red); - assert_eq!( - list(&mut connection, Some(&sql)).unwrap()[0].colour, - FolderColour::Red - ); -} - -#[test] -fn two_folders_of_one_space_cannot_share_a_name_whatever_the_case() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - - let refused = create(&mut connection, &sql, None, "perf", t0()); - - assert!(matches!(refused, Err(StorageError::DuplicateFolderName(_)))); - assert_eq!(names(&mut connection, &sql).len(), 1); -} - -/// Uniqueness is per space, not per library: two spaces both wanting a "Perf" is the -/// normal case, not a collision. -#[test] -fn the_same_name_is_free_again_in_another_space() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let veille = space(&mut connection, "Veille"); - create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - - assert!(create(&mut connection, &veille, None, "Perf", t0()).is_ok()); -} - -#[test] -fn correcting_the_case_of_a_name_is_not_a_duplicate_of_itself() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let folder = create(&mut connection, &sql, None, "perf", t0()).unwrap(); - - let renamed = rename(&mut connection, &folder.id, "Perf").unwrap(); - - assert_eq!(renamed.name, "Perf"); -} - -#[test] -fn a_folder_of_an_unknown_space_is_refused() { - let mut connection = open_in_memory().unwrap(); - - let refused = create(&mut connection, "nowhere", None, "Perf", t0()); - - assert!(matches!(refused, Err(StorageError::SpaceNotFound(_)))); -} - -#[test] -fn filing_a_note_answers_where_it_came_from() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let note = note_in(&mut connection, &sql); - - let filed = file_many( - &mut connection, - std::slice::from_ref(¬e.id), - Some(&perf.id), - CARD, - ) - .unwrap(); - - assert_eq!( - filed, - [NoteFiling { - note_id: note.id.clone(), - folder_id: None - }] - ); - assert_eq!(folder_of(&mut connection, ¬e.id), Some(perf.id)); -} - -#[test] -fn filing_with_no_folder_takes_a_note_back_out() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let note = note_in(&mut connection, &sql); - file_many( - &mut connection, - std::slice::from_ref(¬e.id), - Some(&perf.id), - CARD, - ) - .unwrap(); - - let unfiled = file_many(&mut connection, std::slice::from_ref(¬e.id), None, CARD).unwrap(); - - assert_eq!(unfiled[0].folder_id, Some(perf.id)); - assert_eq!(folder_of(&mut connection, ¬e.id), None); -} - -/// A batch reports what it actually changed, so the undo cannot unfile a note the batch -/// never touched. -#[test] -fn a_note_already_in_the_folder_is_not_reported_as_filed() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let already = note_in(&mut connection, &sql); - let moving = note_in(&mut connection, &sql); - file_many( - &mut connection, - std::slice::from_ref(&already.id), - Some(&perf.id), - CARD, - ) - .unwrap(); - - let filed = file_many( - &mut connection, - &[already.id.clone(), moving.id.clone()], - Some(&perf.id), - CARD, - ) - .unwrap(); - - assert_eq!(filed.len(), 1); - assert_eq!(filed[0].note_id, moving.id); -} - -/// A folder belongs to one space, so filing across spaces would show a chip the space -/// switcher can never reach. -#[test] -fn a_note_of_another_space_is_left_where_it_is() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let veille = space(&mut connection, "Veille"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let elsewhere = note_in(&mut connection, &veille); - - let filed = file_many( - &mut connection, - std::slice::from_ref(&elsewhere.id), - Some(&perf.id), - CARD, - ) - .unwrap(); - - assert!(filed.is_empty()); - assert_eq!(folder_of(&mut connection, &elsewhere.id), None); -} - -#[test] -fn undoing_a_filing_puts_every_note_back_where_it_was() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let migrations = create(&mut connection, &sql, None, "Migrations", t0()).unwrap(); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let loose = note_in(&mut connection, &sql); - let filed = note_in(&mut connection, &sql); - file_many( - &mut connection, - std::slice::from_ref(&filed.id), - Some(&migrations.id), - CARD, - ) - .unwrap(); - - let batch = file_many( - &mut connection, - &[loose.id.clone(), filed.id.clone()], - Some(&perf.id), - CARD, - ) - .unwrap(); - restore_filings(&mut connection, &batch, CARD).unwrap(); - - assert_eq!(folder_of(&mut connection, &loose.id), None); - assert_eq!(folder_of(&mut connection, &filed.id), Some(migrations.id)); -} - -/// Filing is not editing, nor is its undo, and the canvas sorts on that column. -#[test] -fn filing_and_its_undo_leave_the_instant_alone() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let note = note_in(&mut connection, &sql); - - let batch = file_many( - &mut connection, - std::slice::from_ref(¬e.id), - Some(&perf.id), - CARD, - ) - .unwrap(); - assert_eq!( - updated_at_of(&mut connection, ¬e.id), - iso8601::format(t0()) - ); - restore_filings(&mut connection, &batch, CARD).unwrap(); - - assert_eq!( - updated_at_of(&mut connection, ¬e.id), - iso8601::format(t0()) - ); -} - -/// The one thing a folder must never do. -#[test] -fn deleting_a_folder_leaves_its_notes_loose_rather_than_deleting_them() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let note = note_in(&mut connection, &sql); - file_many( - &mut connection, - std::slice::from_ref(¬e.id), - Some(&perf.id), - CARD, - ) - .unwrap(); - - delete(&mut connection, &perf.id, CARD, None).unwrap(); - - assert!(list(&mut connection, Some(&sql)).unwrap().is_empty()); - assert_eq!(folder_of(&mut connection, ¬e.id), None); -} - -#[test] -fn deleting_an_unknown_folder_says_so_rather_than_answering_ok() { - let mut connection = open_in_memory().unwrap(); - - assert!(matches!( - delete(&mut connection, "nowhere", CARD, None), - Err(StorageError::FolderNotFound(_)) - )); -} - -/// The folders go with their space through the cascade; their notes went to the refuge -/// first, and come out of it loose. -#[test] -fn deleting_a_space_takes_its_folders_and_unfiles_the_notes_it_hands_over() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let refuge = space(&mut connection, "Veille"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let note = note_in(&mut connection, &sql); - file_many( - &mut connection, - std::slice::from_ref(¬e.id), - Some(&perf.id), - CARD, - ) - .unwrap(); - - spaces::delete(&mut connection, &sql, &refuge, None).unwrap(); - - assert!(list(&mut connection, Some(&sql)).unwrap().is_empty()); - assert_eq!(folder_of(&mut connection, ¬e.id), None); -} - -/// The chip would otherwise name a folder the space switcher can never reach. -#[test] -fn moving_a_note_to_another_space_takes_it_out_of_its_folder() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let veille = space(&mut connection, "Veille"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let note = note_in(&mut connection, &sql); - file_many( - &mut connection, - std::slice::from_ref(¬e.id), - Some(&perf.id), - CARD, - ) - .unwrap(); - - let patch = NotePatch { - space_id: Some(veille.clone()), - ..NotePatch::default() - }; - update(&mut connection, ¬e.id, &patch, t1()).unwrap(); - - assert_eq!(folder_of(&mut connection, ¬e.id), None); -} - -/// Editing a note is not refiling it. -#[test] -fn a_patch_that_says_nothing_about_the_space_leaves_the_folder_alone() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let note = note_in(&mut connection, &sql); - file_many( - &mut connection, - std::slice::from_ref(¬e.id), - Some(&perf.id), - CARD, - ) - .unwrap(); - - let patch = NotePatch { - title: Some("Autre".to_string()), - ..NotePatch::default() - }; - update(&mut connection, ¬e.id, &patch, t1()).unwrap(); - - assert_eq!(folder_of(&mut connection, ¬e.id), Some(perf.id)); -} - -/// A note created inside a folder arrives already filed — one of the two places that do. -#[test] -fn a_draft_can_name_the_folder_it_is_born_in() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - - let born = create_note( - &mut connection, - NoteDraft { - folder_id: Some(perf.id.clone()), - ..draft(&sql) - }, - t0(), - ) - .unwrap(); - - assert_eq!(born.folder_id, Some(perf.id)); -} - -mod board { - use super::*; - - use engine::folders::board::{ - self, BoardFrame, BoardPoint, BoardQuery, BoardView, PreviewLines, - }; - use engine::folders::store::board as geometry; - use engine::notes::store::fetch; - use engine::notes::view::{Grouping, NoteFilter, NoteOrder, NotesQuery}; - - pub(super) fn request(space_id: &str) -> BoardQuery { - BoardQuery { - space_id: space_id.to_string(), - root_id: None, - search: String::new(), - filter: NoteFilter::All, - tags: Vec::new(), - languages: Vec::new(), - kinds: Vec::new(), - priorities: Vec::new(), - now: t1(), - tz_offset_minutes: 0, - preview_lines: PreviewLines::default(), - } - } - - /// What `board_view` does, minus the decoration passes that need a connection. - pub(super) fn view(connection: &mut Library, query: &BoardQuery) -> BoardView { - let folders = list(connection, Some(&query.space_id)).unwrap(); - let (notes, facets) = fetch( - connection, - &NotesQuery { - space_id: Some(query.space_id.clone()), - folder_id: None, - search: String::new(), - filter: NoteFilter::All, - tags: Vec::new(), - languages: Vec::new(), - kinds: Vec::new(), - priorities: Vec::new(), - order: NoteOrder::default(), - grouping: Grouping::default(), - ranked: false, - now: query.now, - tz_offset_minutes: 0, - pinned_first: true, - }, - ) - .unwrap(); - - let lineage = Lineage::of(&folders); - let root = query.root_id.as_deref(); - let zones: Vec<(String, bool)> = lineage - .children(root) - .iter() - .map(|id| (id.clone(), !lineage.children(Some(id)).is_empty())) - .collect(); - let (frames, positions) = geometry::geometry( - connection, - &query.space_id, - &zones, - &board::Occupancy::on(¬es, &lineage, root), - CARD, - ) - .unwrap(); - - board::build(notes, &folders, &frames, &positions, &facets, query) - } - - pub(super) fn titled(connection: &mut Library, space_id: &str, title: &str) -> Note { - create_note( - connection, - NoteDraft { - title: title.to_string(), - ..draft(space_id) - }, - t0(), - ) - .unwrap() - } - - #[test] - fn a_board_draws_every_folder_as_a_zone_holding_its_notes() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - // Distinct instants: `list` orders by `(created_at, id)`, so two folders made - // in the same millisecond fall back to their UUIDs — stable across launches, which - // is what the board needs, but not something a test can name. - let migrations = create(&mut connection, &sql, None, "Migrations", t0()).unwrap(); - create(&mut connection, &sql, None, "Perf", t1()).unwrap(); - let filed = note_in(&mut connection, &sql); - note_in(&mut connection, &sql); - file_many( - &mut connection, - std::slice::from_ref(&filed.id), - Some(&migrations.id), - CARD, - ) - .unwrap(); - - let board = view(&mut connection, &request(&sql)); - - assert_eq!(board.zones.len(), 2); - assert_eq!(board.zones[0].folder.name, "Migrations"); - assert_eq!(board.zones[0].notes.len(), 1); - assert!(board.zones[1].notes.is_empty()); - assert_eq!(board.loose.len(), 1); - } - - /// A board is a list like the canvas: filed or loose, a card carries a preview. - #[test] - fn a_board_card_carries_the_head_of_a_long_body() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - // A snippet: a Note's preview is its words, not its lines. - let long = || NoteDraft { - language: Language::Sh, - content: "1\n2\n3\n4\n5\n6\n7".to_string(), - ..draft(&sql) - }; - let filed = create_note(&mut connection, long(), t0()).unwrap(); - create_note(&mut connection, long(), t0()).unwrap(); - file_many( - &mut connection, - std::slice::from_ref(&filed.id), - Some(&perf.id), - CARD, - ) - .unwrap(); - - let mut board = view(&mut connection, &request(&sql)); - - assert_eq!(board.notes_mut().count(), 2); - assert!( - board - .notes_mut() - .all(|note| note.truncated && note.content == "1\n2\n3\n4\n5") - ); - } - - /// A filed card flows inside its zone; only a loose one carries a place of its own. - #[test] - fn a_filed_card_has_no_position_and_a_loose_one_does() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let filed = note_in(&mut connection, &sql); - note_in(&mut connection, &sql); - file_many( - &mut connection, - std::slice::from_ref(&filed.id), - Some(&perf.id), - CARD, - ) - .unwrap(); - - let board = view(&mut connection, &request(&sql)); - - assert!(board.zones[0].notes[0].position.is_none()); - assert!(board.loose[0].position.is_some()); - } - - /// The board would look shuffled at every launch otherwise. - #[test] - fn the_first_layout_is_written_down_and_read_back_unchanged() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - create(&mut connection, &sql, None, "Migrations", t0()).unwrap(); - create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - note_in(&mut connection, &sql); - - let first = view(&mut connection, &request(&sql)); - let second = view(&mut connection, &request(&sql)); - - assert_eq!( - first - .zones - .iter() - .map(|zone| zone.frame) - .collect::>(), - second - .zones - .iter() - .map(|zone| zone.frame) - .collect::>(), - ); - assert_eq!(first.loose[0].position, second.loose[0].position); - } - - /// A frame is computed once: the gesture that files a card into a full zone is the one - /// that makes room, or the card flows out of sight. - #[test] - fn filing_a_card_into_a_full_zone_makes_room_for_it() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let filled: Vec = ["a", "b"] - .iter() - .map(|title| titled(&mut connection, &sql, title).id) - .collect(); - file_many(&mut connection, &filled, Some(&perf.id), CARD).unwrap(); - let before = view(&mut connection, &request(&sql)).zones[0].frame; - - let extra = titled(&mut connection, &sql, "c"); - file_many( - &mut connection, - std::slice::from_ref(&extra.id), - Some(&perf.id), - CARD, - ) - .unwrap(); - - let after = view(&mut connection, &request(&sql)).zones[0].frame; - assert!( - after.height > before.height, - "the zone stayed {}px tall for three cards", - before.height - ); - assert_eq!(after.width, before.width, "the width must not move"); - } - - /// A zone slightly narrower than nominal still flows two across, so the next card filed - /// in needs at most one more row. - #[test] - fn filing_into_a_zone_shaved_narrower_than_nominal_adds_one_row_and_not_two() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - view(&mut connection, &request(&sql)); - - let shaved = BoardFrame { - x: 0, - y: 40, - width: board::default_zone_width() - 14, - height: board::zone_height(2, 2, false, CARD), - }; - connection - .transaction(|connection, _vault| geometry::set_frame(connection, &perf.id, shaved)) - .unwrap(); - - let notes: Vec = ["a", "b", "c"] - .iter() - .map(|title| titled(&mut connection, &sql, title).id) - .collect(); - file_many(&mut connection, ¬es, Some(&perf.id), CARD).unwrap(); - - let after = view(&mut connection, &request(&sql)).zones[0].frame; - assert_eq!(after.width, shaved.width, "the width must not move"); - assert_eq!( - after.height, - board::zone_height(3, 2, false, CARD), - "three cards two across are two rows, not three" - ); - } - - /// Grow only: shrinking would move the board under the pointer every time a card - /// is taken out, and a zone somebody stretched is a zone they chose the size of. - #[test] - fn a_zone_made_bigger_by_hand_keeps_its_size() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - view(&mut connection, &request(&sql)); - - let stretched = BoardFrame { - x: 40, - y: 40, - width: 600, - height: 900, - }; - connection - .transaction(|connection, _vault| geometry::set_frame(connection, &perf.id, stretched)) - .unwrap(); - - let note = titled(&mut connection, &sql, "a"); - file_many( - &mut connection, - std::slice::from_ref(¬e.id), - Some(&perf.id), - CARD, - ) - .unwrap(); - - assert_eq!( - view(&mut connection, &request(&sql)).zones[0].frame, - stretched - ); - } - - /// Taking a card out leaves the room it needed: the board must not move on its own. - #[test] - fn unfiling_a_card_does_not_close_the_zone_again() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let notes: Vec = ["a", "b", "c"] - .iter() - .map(|title| titled(&mut connection, &sql, title).id) - .collect(); - file_many(&mut connection, ¬es, Some(&perf.id), CARD).unwrap(); - let grown = view(&mut connection, &request(&sql)).zones[0].frame; - - file_many(&mut connection, ¬es[..1], None, CARD).unwrap(); - - assert_eq!(view(&mut connection, &request(&sql)).zones[0].frame, grown); - } - - /// Undoing puts notes back into a zone that may no longer be tall enough for them. - #[test] - fn undoing_a_filing_makes_room_for_what_comes_back() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let notes: Vec = ["a", "b", "c"] - .iter() - .map(|title| titled(&mut connection, &sql, title).id) - .collect(); - file_many(&mut connection, ¬es, Some(&perf.id), CARD).unwrap(); - let grown = view(&mut connection, &request(&sql)).zones[0].frame; - - // Squashed back down behind the zone's back, as a resize would. - connection - .transaction(|connection, _vault| { - geometry::set_frame( - connection, - &perf.id, - BoardFrame { - height: 212, - ..grown - }, - ) - }) - .unwrap(); - let left = file_many(&mut connection, ¬es[..1], None, CARD).unwrap(); - restore_filings(&mut connection, &left, CARD).unwrap(); - - assert_eq!( - view(&mut connection, &request(&sql)).zones[0].frame.height, - grown.height - ); - } - - #[test] - fn a_stored_frame_survives_the_next_read() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - view(&mut connection, &request(&sql)); - - let moved = BoardFrame { - x: 700, - y: 500, - width: 300, - height: 200, - }; - connection - .transaction(|connection, _vault| geometry::set_frame(connection, &perf.id, moved)) - .unwrap(); - - assert_eq!(view(&mut connection, &request(&sql)).zones[0].frame, moved); - } - - #[test] - fn a_folder_added_later_lands_beside_the_others_rather_than_on_top() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - create(&mut connection, &sql, None, "Migrations", t0()).unwrap(); - let first = view(&mut connection, &request(&sql)).zones[0].frame; - - create(&mut connection, &sql, None, "Perf", t1()).unwrap(); - let board = view(&mut connection, &request(&sql)); - - assert_eq!(board.zones[0].frame, first); - assert_ne!(board.zones[1].frame, first); - } - - /// Dimmed, never dropped: reflowing the survivors throws away the only thing the board - /// has that the date view does not. - #[test] - fn a_search_dims_what_it_does_not_match_and_removes_nothing() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let wanted = titled(&mut connection, &sql, "Index sur orders"); - titled(&mut connection, &sql, "Dump nocturne"); - file_many( - &mut connection, - std::slice::from_ref(&wanted.id), - Some(&perf.id), - CARD, - ) - .unwrap(); - - let board = view( - &mut connection, - &BoardQuery { - search: "orders".to_string(), - ..request(&sql) - }, - ); - - assert_eq!(board.zones[0].notes.len(), 1); - assert_eq!(board.loose.len(), 1); - assert!(board.zones[0].notes[0].matches); - assert!(!board.loose[0].matches); - assert_eq!(board.matched, 1); - assert!(board.is_filtering); - } - - /// Accents fold both ways here too: it is `notes::view`'s own matcher, not a second one. - #[test] - fn the_board_search_folds_accents_like_the_canvas_does() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - titled(&mut connection, &sql, "Étape suivante"); - - let board = view( - &mut connection, - &BoardQuery { - search: "etape".to_string(), - ..request(&sql) - }, - ); - - assert!(board.loose[0].matches); - } - - #[test] - fn a_quick_filter_dims_rather_than_narrows_too() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - create_note( - &mut connection, - NoteDraft { - pinned: true, - ..draft(&sql) - }, - t0(), - ) - .unwrap(); - create_note(&mut connection, draft(&sql), t0()).unwrap(); - - let board = view( - &mut connection, - &BoardQuery { - filter: NoteFilter::Pinned, - ..request(&sql) - }, - ); - - assert_eq!(board.loose.len(), 2); - assert_eq!(board.matched, 1); - } - - #[test] - fn a_priority_dims_rather_than_narrows_too() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - create_note(&mut connection, draft(&sql), t0()).unwrap(); - create_note( - &mut connection, - NoteDraft { - priority: Priority::High, - ..draft(&sql) - }, - t0(), - ) - .unwrap(); - - let board = view( - &mut connection, - &BoardQuery { - priorities: vec![Priority::High], - ..request(&sql) - }, - ); - - assert_eq!(board.loose.len(), 2); - assert_eq!(board.matched, 1); - } - - #[test] - fn a_kind_dims_rather_than_narrows_too() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - create_note(&mut connection, draft(&sql), t0()).unwrap(); - create_note( - &mut connection, - NoteDraft { - kind: NoteKind::Note, - ..draft(&sql) - }, - t0(), - ) - .unwrap(); - - let board = view( - &mut connection, - &BoardQuery { - kinds: vec![NoteKind::Note], - ..request(&sql) - }, - ); - - assert_eq!(board.loose.len(), 2); - assert_eq!(board.matched, 1); - assert!(board.is_filtering); - } - - /// The two views answer the same question, and must not answer it differently. Tags - /// are compared as the column compares them — ASCII case only, `#` stripped — and a - /// tag that normalises to nothing asks for nothing. - #[test] - fn the_board_and_the_date_view_agree_on_what_matches() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - for (title, tags) in [ - ("accented", vec!["étape"]), - ("capital", vec!["Étape"]), - ("urgent", vec!["URGENT"]), - ("plain", Vec::new()), - ] { - create_note( - &mut connection, - NoteDraft { - title: title.to_string(), - tags: tags.into_iter().map(ToString::to_string).collect(), - ..draft(&sql) - }, - t0(), - ) - .unwrap(); - } - - for asked in [vec!["étape"], vec!["#urgent"], vec![" # "], Vec::new()] { - let tags: Vec = asked.iter().map(ToString::to_string).collect(); - - let query = NotesQuery { - space_id: Some(sql.clone()), - folder_id: None, - search: String::new(), - filter: NoteFilter::All, - tags: tags.clone(), - languages: Vec::new(), - kinds: Vec::new(), - priorities: Vec::new(), - order: NoteOrder::default(), - grouping: Grouping::default(), - ranked: false, - now: t1(), - tz_offset_minutes: 0, - pinned_first: true, - }; - let (notes, facets) = fetch(&mut connection, &query).unwrap(); - let dated = engine::notes::view::build(notes, facets, &query); - let mut on_the_date_view: Vec = dated - .sections - .iter() - .flat_map(|section| section.cards.iter().map(|card| card.title.clone())) - .collect(); - - let board = view( - &mut connection, - &BoardQuery { - tags, - ..request(&sql) - }, - ); - let mut lit_on_the_board: Vec = board - .loose - .iter() - .filter(|entry| entry.matches) - .map(|entry| entry.note.title.clone()) - .collect(); - - on_the_date_view.sort(); - lit_on_the_board.sort(); - assert_eq!(on_the_date_view, lit_on_the_board, "asked for {asked:?}"); - assert_eq!( - dated.is_filtering, board.is_filtering, - "asked for {asked:?}" - ); - } - } - - /// Filing a card into a zone drops the place it had on the background. - #[test] - fn filing_a_loose_note_forgets_where_it_sat() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let note = note_in(&mut connection, &sql); - view(&mut connection, &request(&sql)); - - let placed = connection - .transaction(|connection, _vault| geometry::positions(connection, &sql)) - .unwrap(); - assert!(placed.contains_key(¬e.id)); - - file_many( - &mut connection, - std::slice::from_ref(¬e.id), - Some(&perf.id), - CARD, - ) - .unwrap(); - - let after = connection - .transaction(|connection, _vault| geometry::positions(connection, &sql)) - .unwrap(); - assert!(!after.contains_key(¬e.id)); - } - - #[test] - fn a_stored_position_is_what_a_later_read_hands_back() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let note = note_in(&mut connection, &sql); - view(&mut connection, &request(&sql)); - - let chosen = BoardPoint { x: 640, y: 480 }; - connection - .transaction(|connection, _vault| geometry::set_position(connection, ¬e.id, chosen)) - .unwrap(); - - assert_eq!( - view(&mut connection, &request(&sql)).loose[0].position, - Some(chosen) - ); - } - - /// A new note is the most recently updated, so it comes first in the list: it must not - /// be handed seat zero, where another card already sits. - #[test] - fn a_note_created_later_is_placed_beside_the_cards_rather_than_on_one() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - titled(&mut connection, &sql, "Dump nocturne"); - let already_there = view(&mut connection, &request(&sql)).loose[0].position; - - create_note( - &mut connection, - NoteDraft { - title: "Collé du presse-papiers".to_string(), - ..draft(&sql) - }, - t1(), - ) - .unwrap(); - - let board = view(&mut connection, &request(&sql)); - let places: Vec<_> = board.loose.iter().map(|entry| entry.position).collect(); - - assert_eq!(places.len(), 2); - assert!( - places.contains(&already_there), - "the card already there did not move" - ); - assert_ne!(places[0], places[1], "two cards were written to one place"); - } - - /// Every unplaced card in the same pass, not just the first one. - #[test] - fn a_first_read_of_several_loose_notes_gives_each_its_own_place() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - for title in ["Un", "Deux", "Trois", "Quatre", "Cinq"] { - titled(&mut connection, &sql, title); - } - - let board = view(&mut connection, &request(&sql)); - let mut places: Vec<_> = board - .loose - .iter() - .map(|entry| entry.position.expect("a loose card is always placed")) - .map(|at| (at.x, at.y)) - .collect(); - places.sort_unstable(); - places.dedup(); - - assert_eq!(places.len(), 5); - } - - #[test] - fn the_surface_grows_to_hold_whatever_is_furthest_out() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let note = note_in(&mut connection, &sql); - view(&mut connection, &request(&sql)); - - connection - .transaction(|connection, _vault| { - geometry::set_position(connection, ¬e.id, BoardPoint { x: 3000, y: 2000 }) - }) - .unwrap(); - - let board = view(&mut connection, &request(&sql)); - assert!(board.width > 3000); - assert!(board.height > 2000); - } - - /// A board of one space says nothing about the next one. - #[test] - fn a_board_never_reaches_into_another_space() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let veille = space(&mut connection, "Veille"); - create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - create(&mut connection, &veille, None, "Liens", t0()).unwrap(); - note_in(&mut connection, &veille); - - let board = view(&mut connection, &request(&sql)); - - assert_eq!(board.zones.len(), 1); - assert!(board.loose.is_empty()); - } -} - -mod gesture { - use super::*; - - use engine::folders::board::{ - BoardFrame, BoardPoint, CardPlacement, MIN_ZONE_HEIGHT, MIN_ZONE_WIDTH, ZonePlacement, - clamp, clamp_point, zone_at, - }; - use engine::folders::store::board as geometry; - - fn frames(connection: &mut Library, space_id: &str) -> HashMap { - connection - .transaction(|connection, _vault| geometry::frames(connection, space_id)) - .unwrap() - } - - fn positions(connection: &mut Library, space_id: &str) -> HashMap { - connection - .transaction(|connection, _vault| geometry::positions(connection, space_id)) - .unwrap() - } - - /// Puts a zone and a card exactly where a drag would have left them. - fn place(connection: &mut Library, zones: &[ZonePlacement], cards: &[CardPlacement]) { - geometry::save_layout(connection, None, zones, cards).unwrap(); - } - - fn zone_at_frame(folder_id: &str, frame: BoardFrame) -> ZonePlacement { - ZonePlacement { - folder_id: folder_id.to_string(), - frame, - } - } - - fn card_at(note_id: &str, position: BoardPoint) -> CardPlacement { - CardPlacement { - note_id: note_id.to_string(), - position, - } - } - - #[test] - fn a_moved_zone_and_a_moved_card_are_written_as_one_batch() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let note = note_in(&mut connection, &sql); - - let frame = BoardFrame { - x: 600, - y: 320, - width: 520, - height: 400, - }; - let point = BoardPoint { x: 48, y: 720 }; - geometry::save_layout( - &mut connection, - None, - &[ZonePlacement { - folder_id: perf.id.clone(), - frame, - }], - &[CardPlacement { - note_id: note.id.clone(), - position: point, - }], - ) - .unwrap(); - - assert_eq!(frames(&mut connection, &sql).get(&perf.id), Some(&frame)); - assert_eq!(positions(&mut connection, &sql).get(¬e.id), Some(&point)); - } - - /// A zone nothing can be dropped into is not a zone. Clamped rather than refused: - /// answering an error mid-gesture leaves the interface holding a frame nothing stored. - #[test] - fn a_zone_squashed_to_nothing_keeps_room_for_one_card() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - - geometry::save_layout( - &mut connection, - None, - &[ZonePlacement { - folder_id: perf.id.clone(), - frame: BoardFrame { - x: -50, - y: -50, - width: 4, - height: 4, - }, - }], - &[], - ) - .unwrap(); - - let stored = frames(&mut connection, &sql); - let frame = stored.get(&perf.id).unwrap(); - assert_eq!(frame.x, 0); - assert_eq!(frame.y, 0); - assert_eq!(frame.width, MIN_ZONE_WIDTH); - assert_eq!(frame.height, MIN_ZONE_HEIGHT); - } - - /// A filed card flows inside its zone. Writing a position for one would put back the - /// row `file_many` had just dropped, and the table would stop meaning "this is loose". - #[test] - fn a_card_filed_since_the_drag_is_not_given_a_position_back() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let note = note_in(&mut connection, &sql); - file_many( - &mut connection, - std::slice::from_ref(¬e.id), - Some(&perf.id), - CARD, - ) - .unwrap(); - - geometry::save_layout( - &mut connection, - None, - &[], - &[CardPlacement { - note_id: note.id.clone(), - position: BoardPoint { x: 10, y: 10 }, - }], - ) - .unwrap(); - - assert!(!positions(&mut connection, &sql).contains_key(¬e.id)); - } - - /// Every zone or none: half a board is a board nobody arranged. - #[test] - fn a_batch_naming_a_folder_that_is_gone_writes_nothing_at_all() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let note = note_in(&mut connection, &sql); - - let refused = geometry::save_layout( - &mut connection, - None, - &[ - ZonePlacement { - folder_id: perf.id.clone(), - frame: BoardFrame { - x: 600, - y: 320, - width: 520, - height: 400, - }, - }, - ZonePlacement { - folder_id: "gone".to_string(), - frame: BoardFrame { - x: 0, - y: 0, - width: 520, - height: 400, - }, - }, - ], - &[CardPlacement { - note_id: note.id.clone(), - position: BoardPoint { x: 48, y: 720 }, - }], - ); - - assert!(matches!(refused, Err(StorageError::FolderNotFound(_)))); - assert!(frames(&mut connection, &sql).is_empty()); - assert!(positions(&mut connection, &sql).is_empty()); - } - - #[test] - fn an_empty_batch_is_not_an_error() { - let mut connection = open_in_memory().unwrap(); - - assert!(geometry::save_layout(&mut connection, None, &[], &[]).is_ok()); - } - - /// Membership comes from the drop, and from nothing else. - #[test] - fn a_point_names_the_zone_it_falls_in() { - let zones = vec![ - ( - "a".to_string(), - BoardFrame { - x: 0, - y: 0, - width: 100, - height: 100, - }, - ), - ( - "b".to_string(), - BoardFrame { - x: 200, - y: 0, - width: 100, - height: 100, - }, - ), - ]; - - assert_eq!( - zone_at(&zones, BoardPoint { x: 50, y: 50 }), - Some("a".into()) - ); - assert_eq!( - zone_at(&zones, BoardPoint { x: 250, y: 50 }), - Some("b".into()) - ); - } - - /// The free background is a legitimate answer: dropping there unfiles the note. - #[test] - fn a_point_on_the_background_names_no_zone() { - let zones = vec![( - "a".to_string(), - BoardFrame { - x: 0, - y: 0, - width: 100, - height: 100, - }, - )]; - - assert_eq!(zone_at(&zones, BoardPoint { x: 150, y: 50 }), None); - // The far edges belong to the next zone along, not to this one. - assert_eq!(zone_at(&zones, BoardPoint { x: 100, y: 50 }), None); - assert_eq!(zone_at(&zones, BoardPoint { x: 0, y: 0 }), Some("a".into())); - } - - /// Drawn later means drawn on top, so it is what a drop lands in. - #[test] - fn overlapping_zones_hand_the_drop_to_the_topmost() { - let zones = vec![ - ( - "under".to_string(), - BoardFrame { - x: 0, - y: 0, - width: 200, - height: 200, - }, - ), - ( - "over".to_string(), - BoardFrame { - x: 50, - y: 50, - width: 100, - height: 100, - }, - ), - ]; - - assert_eq!( - zone_at(&zones, BoardPoint { x: 100, y: 100 }), - Some("over".into()) - ); - } - - #[test] - fn a_runaway_drag_cannot_put_anything_off_the_board() { - assert_eq!(clamp_point(BoardPoint { x: -40, y: -40 }).x, 0); - assert_eq!( - clamp(BoardFrame { - x: 10, - y: 10, - width: 1_000_000, - height: 10 - }) - .width, - engine::folders::board::MAX_SIDE - ); - } - - /// The one board gesture that cannot be walked back by dragging: it moves everything at - /// once and overwrites sizes chosen by hand. - mod tidy_up { - use super::*; - - use engine::folders::board::{BoardScope, default_zone_height, default_zone_width}; - - const DRAGGED: BoardFrame = BoardFrame { - x: 900, - y: 640, - width: 900, - height: 700, - }; - - #[test] - fn a_zone_dragged_away_comes_back_to_its_seat() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - place(&mut connection, &[zone_at_frame(&perf.id, DRAGGED)], &[]); - - geometry::arrange(&mut connection, &sql, None, BoardScope::Everything, CARD).unwrap(); - - let frame = *frames(&mut connection, &sql).get(&perf.id).unwrap(); - assert_eq!(frame.x, 16); - assert_eq!(frame.y, 16); - assert_eq!(frame.width, default_zone_width()); - assert_eq!(frame.height, default_zone_height(0, false, CARD)); - } - - /// The half that makes it a tidy-up: a zone too small for what it holds is reopened. - #[test] - fn a_zone_is_resized_to_what_it_actually_holds() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let notes: Vec = (0..5).map(|_| note_in(&mut connection, &sql).id).collect(); - file_many(&mut connection, ¬es, Some(&perf.id), CARD).unwrap(); - - geometry::arrange(&mut connection, &sql, None, BoardScope::Everything, CARD).unwrap(); - - let frame = *frames(&mut connection, &sql).get(&perf.id).unwrap(); - assert_eq!(frame.height, default_zone_height(5, false, CARD)); - } - - #[test] - fn the_loose_cards_flow_under_the_zones() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let filed = note_in(&mut connection, &sql).id; - file_many(&mut connection, &[filed], Some(&perf.id), CARD).unwrap(); - let loose = note_in(&mut connection, &sql).id; - - geometry::arrange(&mut connection, &sql, None, BoardScope::Everything, CARD).unwrap(); - - let zone = *frames(&mut connection, &sql).get(&perf.id).unwrap(); - let at = *positions(&mut connection, &sql).get(&loose).unwrap(); - assert!(at.y > zone.y + zone.height); - } - - /// What the undo reads. Restoring the answer has to put the board back exactly as - /// it was, or the tidy-up is a one-way gesture. - #[test] - fn it_answers_the_layout_it_replaced() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let note = note_in(&mut connection, &sql); - let seat = BoardPoint { x: 96, y: 900 }; - place( - &mut connection, - &[zone_at_frame(&perf.id, DRAGGED)], - &[card_at(¬e.id, seat)], - ); - - let before = - geometry::arrange(&mut connection, &sql, None, BoardScope::Everything, CARD) - .unwrap() - .previous; - place(&mut connection, &before.zones, &before.cards); - - assert_eq!(frames(&mut connection, &sql).get(&perf.id), Some(&DRAGGED)); - assert_eq!(positions(&mut connection, &sql).get(¬e.id), Some(&seat)); - } - - /// A folder the board has never drawn had no place to go back to, and inventing - /// one on the undo would leave it somewhere nobody chose. - #[test] - fn a_zone_that_never_had_a_place_is_not_offered_back() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - note_in(&mut connection, &sql); - - let before = - geometry::arrange(&mut connection, &sql, None, BoardScope::Everything, CARD) - .unwrap(); - - assert!(before.previous.zones.is_empty()); - assert!(before.previous.cards.is_empty()); - } - - /// The half worth a single click: what goes to pieces is the cards outside the - /// zones, and a zone somebody sized by hand is the only manual work the board holds. - #[test] - fn aligning_the_loose_cards_leaves_every_zone_exactly_where_it_was() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let note = note_in(&mut connection, &sql); - place( - &mut connection, - &[zone_at_frame(&perf.id, DRAGGED)], - &[card_at(¬e.id, BoardPoint { x: 640, y: 1200 })], - ); - - let done = geometry::arrange(&mut connection, &sql, None, BoardScope::LooseCards, CARD) - .unwrap(); - - assert_eq!(frames(&mut connection, &sql).get(&perf.id), Some(&DRAGGED)); - assert!(done.previous.zones.is_empty()); - assert_eq!(done.moved, 1); - } - - /// The cards flow under the zones **as they stand**, not under where a full - /// reorganisation would have put them. - #[test] - fn the_aligned_cards_clear_the_zones_where_they_actually_are() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let note = note_in(&mut connection, &sql); - place(&mut connection, &[zone_at_frame(&perf.id, DRAGGED)], &[]); - - geometry::arrange(&mut connection, &sql, None, BoardScope::LooseCards, CARD).unwrap(); - - let at = *positions(&mut connection, &sql).get(¬e.id).unwrap(); - assert!(at.y > DRAGGED.y + DRAGGED.height); - } - - /// What the undo bar reads. A board nobody disturbed must open no undo window, - /// or the bar offers to put back an arrangement that never changed. - #[test] - fn a_board_already_in_order_reports_nothing_moved() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - note_in(&mut connection, &sql); - geometry::arrange(&mut connection, &sql, None, BoardScope::Everything, CARD).unwrap(); - - let again = - geometry::arrange(&mut connection, &sql, None, BoardScope::Everything, CARD) - .unwrap(); - - assert_eq!(again.moved, 0); - } - - #[test] - fn a_trashed_note_takes_no_room_in_the_zone_it_was_in() { - use engine::notes::store::trash::trash_many; - - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let notes: Vec = (0..4).map(|_| note_in(&mut connection, &sql).id).collect(); - file_many(&mut connection, ¬es, Some(&perf.id), CARD).unwrap(); - trash_many(&mut connection, ¬es[..3], t1()).unwrap(); - - geometry::arrange(&mut connection, &sql, None, BoardScope::Everything, CARD).unwrap(); - - let frame = *frames(&mut connection, &sql).get(&perf.id).unwrap(); - assert_eq!(frame.height, default_zone_height(1, false, CARD)); - } - } -} - -/// Folders inside folders: one tree per space, a board per level. -mod nesting { - use super::board::{request, titled, view}; - use super::*; - - use engine::folders::board::{BoardFrame, BoardPoint, CardPlacement, ZonePlacement}; - use engine::folders::model::Folder; - use engine::folders::store::board as geometry; - use engine::folders::store::{move_back, move_to, subtree}; - use engine::notes::store::fetch; - use engine::notes::view::{Grouping, NoteFilter, NoteOrder, NotesQuery}; - - /// `SQL › Perf › Index` and `SQL › Migrations`, and `Angular` beside them. - struct Tree { - space: String, - sql: Folder, - perf: Folder, - index: Folder, - migrations: Folder, - angular: Folder, - } - - fn tree(connection: &mut Library) -> Tree { - // A millisecond apart: folders made in one instant would come back in the order of - // their ids. - let after = |ms: i64| t0() + chrono::TimeDelta::milliseconds(ms); - let space = space(connection, "Découverte"); - let sql = create(connection, &space, None, "SQL", after(0)).unwrap(); - let perf = create(connection, &space, Some(&sql.id), "Perf", after(1)).unwrap(); - let index = create(connection, &space, Some(&perf.id), "Index", after(2)).unwrap(); - let migrations = create(connection, &space, Some(&sql.id), "Migrations", after(3)).unwrap(); - let angular = create(connection, &space, None, "Angular", after(4)).unwrap(); - Tree { - space, - sql, - perf, - index, - migrations, - angular, - } - } - - fn filed(connection: &mut Library, tree: &Tree, title: &str, folder: &Folder) -> Note { - let note = titled(connection, &tree.space, title); - file_many( - connection, - std::slice::from_ref(¬e.id), - Some(&folder.id), - CARD, - ) - .unwrap(); - note - } - - fn parent_of(connection: &mut Library, id: &str) -> Option { - list(connection, None) - .unwrap() - .into_iter() - .find(|folder| folder.id == id) - .and_then(|folder| folder.parent_id) - } - - fn frame_of(connection: &mut Library, id: &str) -> Option { - connection - .transaction(|connection, _vault| geometry::frame_of(connection, id)) - .unwrap() - } - - #[test] - fn a_sub_tree_holds_the_folder_and_everything_under_it() { - let mut connection = open_in_memory().unwrap(); - let tree = tree(&mut connection); - - let mut held = subtree(connection.db(), &tree.sql.id).unwrap(); - held.sort(); - let mut expected = vec![ - tree.sql.id.clone(), - tree.perf.id.clone(), - tree.index.id.clone(), - tree.migrations.id.clone(), - ]; - expected.sort(); - - assert_eq!(held, expected); - assert_eq!( - parent_of(&mut connection, &tree.index.id), - Some(tree.perf.id) - ); - } - - /// Two folders may each hold a « Perf », as two spaces may; two siblings may not. - #[test] - fn a_name_is_unique_among_siblings_only() { - let mut connection = open_in_memory().unwrap(); - let tree = tree(&mut connection); - - assert!( - create( - &mut connection, - &tree.space, - Some(&tree.angular.id), - "Perf", - t0() - ) - .is_ok() - ); - assert!(matches!( - create( - &mut connection, - &tree.space, - Some(&tree.sql.id), - "perf", - t0() - ), - Err(StorageError::DuplicateFolderName(_)) - )); - let at_top = create(&mut connection, &tree.space, None, "Perf", t0()).unwrap(); - assert!(matches!( - move_to( - &mut connection, - &at_top.id, - (&tree.space, Some(&tree.sql.id)) - ), - Err(StorageError::DuplicateFolderName(_)) - )); - } - - #[test] - fn a_folder_never_moves_into_itself_nor_under_a_folder_outside_the_space_named() { - let mut connection = open_in_memory().unwrap(); - let tree = tree(&mut connection); - let other = space(&mut connection, "Ailleurs"); - let elsewhere = create(&mut connection, &other, None, "Ops", t0()).unwrap(); - - assert!(matches!( - move_to( - &mut connection, - &tree.sql.id, - (&tree.space, Some(&tree.index.id)) - ), - Err(StorageError::Invalid(_)) - )); - assert!(matches!( - move_to( - &mut connection, - &tree.sql.id, - (&tree.space, Some(&tree.sql.id)) - ), - Err(StorageError::Invalid(_)) - )); - assert!(matches!( - move_to( - &mut connection, - &tree.perf.id, - (&tree.space, Some(&elsewhere.id)) - ), - Err(StorageError::Invalid(_)) - )); - assert!(matches!( - create( - &mut connection, - &tree.space, - Some(&elsewhere.id), - "Ici", - t0() - ), - Err(StorageError::Invalid(_)) - )); - } - - /// Its frame belongs to the board it left: it takes a free slot on the new one, and the - /// undo gives it both back. - #[test] - fn a_moved_folder_takes_what_it_holds_and_leaves_its_frame_behind() { - let mut connection = open_in_memory().unwrap(); - let tree = tree(&mut connection); - let note = filed(&mut connection, &tree, "EXPLAIN", &tree.index); - view(&mut connection, &request(&tree.space)); - let mut inside = request(&tree.space); - inside.root_id = Some(tree.sql.id.clone()); - view(&mut connection, &inside); - let before = frame_of(&mut connection, &tree.perf.id).unwrap(); - - let was = move_to( - &mut connection, - &tree.perf.id, - (&tree.space, Some(&tree.angular.id)), - ) - .unwrap(); - - assert_eq!(was.parent_id.as_deref(), Some(tree.sql.id.as_str())); - assert_eq!(was.frame, Some(before)); - assert_eq!( - parent_of(&mut connection, &tree.perf.id), - Some(tree.angular.id.clone()) - ); - assert_eq!(frame_of(&mut connection, &tree.perf.id), None); - assert_eq!( - parent_of(&mut connection, &tree.index.id), - Some(tree.perf.id.clone()) - ); - assert_eq!( - folder_of(&mut connection, ¬e.id), - Some(tree.index.id.clone()) - ); - - assert!(move_back(&mut connection, &was).unwrap().is_some()); - assert_eq!( - parent_of(&mut connection, &tree.perf.id), - Some(tree.sql.id.clone()) - ); - assert_eq!(frame_of(&mut connection, &tree.perf.id), Some(before)); - } - - #[test] - fn an_undo_whose_parent_is_gone_leaves_the_folder_where_it_is() { - let mut connection = open_in_memory().unwrap(); - let tree = tree(&mut connection); - let was = move_to(&mut connection, &tree.migrations.id, (&tree.space, None)).unwrap(); - delete(&mut connection, &tree.sql.id, CARD, None).unwrap(); - - assert!(move_back(&mut connection, &was).unwrap().is_none()); - assert_eq!(parent_of(&mut connection, &tree.migrations.id), None); - } - - /// Nothing is lost, and nothing lands out of reach: the parent takes what it held. - #[test] - fn deleting_a_folder_hands_its_notes_and_sub_folders_to_its_parent() { - let mut connection = open_in_memory().unwrap(); - let tree = tree(&mut connection); - let held = filed(&mut connection, &tree, "EXPLAIN", &tree.perf); - let below = filed(&mut connection, &tree, "Index partiel", &tree.index); - - delete(&mut connection, &tree.perf.id, CARD, None).unwrap(); - - assert_eq!( - folder_of(&mut connection, &held.id), - Some(tree.sql.id.clone()) - ); - assert_eq!( - folder_of(&mut connection, &below.id), - Some(tree.index.id.clone()) - ); - assert_eq!( - parent_of(&mut connection, &tree.index.id), - Some(tree.sql.id.clone()) - ); - } - - #[test] - fn deleting_a_folder_at_the_top_leaves_its_notes_loose_and_its_children_at_the_top() { - let mut connection = open_in_memory().unwrap(); - let tree = tree(&mut connection); - let held = filed(&mut connection, &tree, "Requête", &tree.sql); - - delete(&mut connection, &tree.sql.id, CARD, None).unwrap(); - - assert_eq!(folder_of(&mut connection, &held.id), None); - assert_eq!(parent_of(&mut connection, &tree.perf.id), None); - assert_eq!(parent_of(&mut connection, &tree.migrations.id), None); - } - - /// The space's board shows its top folders; each gathers its whole sub-tree. - #[test] - fn a_zone_gathers_the_notes_of_everything_under_it() { - let mut connection = open_in_memory().unwrap(); - let tree = tree(&mut connection); - filed(&mut connection, &tree, "Requête", &tree.sql); - filed(&mut connection, &tree, "EXPLAIN", &tree.perf); - filed(&mut connection, &tree, "Index partiel", &tree.index); - titled(&mut connection, &tree.space, "Loose"); - - let board = view(&mut connection, &request(&tree.space)); - - let zones: Vec<&str> = board - .zones - .iter() - .map(|zone| zone.folder.name.as_str()) - .collect(); - assert_eq!(zones, ["SQL", "Angular"]); - assert_eq!(board.zones[0].notes.len(), 3); - let children: Vec<(&str, u32)> = board.zones[0] - .children - .iter() - .map(|child| (child.name.as_str(), child.count)) - .collect(); - assert_eq!(children, [("Migrations", 0), ("Perf", 2)]); - assert!(board.zones[1].children.is_empty()); - assert_eq!(board.loose.len(), 1); - } - - /// A folder's board: its sub-folders as zones, what is filed in it free on its ground, and - /// nothing from outside it. - #[test] - fn a_folders_board_draws_its_sub_folders_and_its_own_notes_free() { - let mut connection = open_in_memory().unwrap(); - let tree = tree(&mut connection); - let own = filed(&mut connection, &tree, "Requête", &tree.sql); - filed(&mut connection, &tree, "Index partiel", &tree.index); - filed(&mut connection, &tree, "Composant", &tree.angular); - titled(&mut connection, &tree.space, "Loose"); - let mut inside = request(&tree.space); - inside.root_id = Some(tree.sql.id.clone()); - - let board = view(&mut connection, &inside); - - let zones: Vec<(&str, usize)> = board - .zones - .iter() - .map(|zone| (zone.folder.name.as_str(), zone.notes.len())) - .collect(); - assert_eq!(zones, [("Perf", 1), ("Migrations", 0)]); - assert_eq!(board.loose.len(), 1); - assert_eq!(board.loose[0].note.id, own.id); - assert!(board.loose[0].position.is_some()); - assert_eq!(board.matched, 2); - } - - /// A row of chips under the title is height the cards must not pay for. - #[test] - fn a_zone_with_sub_folders_is_taller_by_their_row() { - let mut connection = open_in_memory().unwrap(); - let tree = tree(&mut connection); - - let board = view(&mut connection, &request(&tree.space)); - - assert_eq!( - board.zones[0].frame.height - board.zones[1].frame.height, - engine::folders::board::ZONE_SUBFOLDERS - ); - } - - /// Filed three levels down, it shows in its zone on every board above it. - #[test] - fn filing_deep_makes_room_in_every_zone_above_it() { - let mut connection = open_in_memory().unwrap(); - let tree = tree(&mut connection); - view(&mut connection, &request(&tree.space)); - let top = frame_of(&mut connection, &tree.sql.id).unwrap(); - - let notes: Vec = (0..5) - .map(|index| titled(&mut connection, &tree.space, &format!("n{index}")).id) - .collect(); - file_many(&mut connection, ¬es, Some(&tree.index.id), CARD).unwrap(); - - assert!(frame_of(&mut connection, &tree.sql.id).unwrap().height > top.height); - } - - /// A card's place is on its own folder's board: saved from another board, it is refused. - #[test] - fn a_place_is_kept_only_on_the_board_of_the_cards_own_folder() { - let mut connection = open_in_memory().unwrap(); - let tree = tree(&mut connection); - let own = filed(&mut connection, &tree, "Requête", &tree.sql); - let deeper = filed(&mut connection, &tree, "EXPLAIN", &tree.perf); - let place = BoardPoint { x: 640, y: 480 }; - let cards = [own.id.clone(), deeper.id.clone()].map(|note_id| CardPlacement { - note_id, - position: place, - }); - - geometry::save_layout(&mut connection, Some(&tree.sql.id), &[], &cards).unwrap(); - - let placed = connection - .transaction(|connection, _vault| geometry::positions(connection, &tree.space)) - .unwrap(); - assert_eq!(placed.get(&own.id), Some(&place)); - assert!(!placed.contains_key(&deeper.id)); - } - - /// Filed elsewhere, a card leaves its place behind: it means nothing on another board. - #[test] - fn filing_a_note_forgets_its_place() { - let mut connection = open_in_memory().unwrap(); - let tree = tree(&mut connection); - let note = titled(&mut connection, &tree.space, "Loose"); - view(&mut connection, &request(&tree.space)); - - file_many( - &mut connection, - std::slice::from_ref(¬e.id), - Some(&tree.perf.id), - CARD, - ) - .unwrap(); - - let placed = connection - .transaction(|connection, _vault| geometry::positions(connection, &tree.space)) - .unwrap(); - assert!(!placed.contains_key(¬e.id)); - } - - #[test] - fn a_folders_board_is_tidied_on_its_own() { - let mut connection = open_in_memory().unwrap(); - let tree = tree(&mut connection); - let frame = BoardFrame { - x: 2000, - y: 2000, - width: 600, - height: 400, - }; - geometry::save_layout( - &mut connection, - None, - &[ZonePlacement { - folder_id: tree.angular.id.clone(), - frame, - }], - &[], - ) - .unwrap(); - - geometry::arrange( - &mut connection, - &tree.space, - Some(&tree.sql.id), - engine::folders::board::BoardScope::Everything, - CARD, - ) - .unwrap(); - - assert_eq!(frame_of(&mut connection, &tree.angular.id), Some(frame)); - assert!(frame_of(&mut connection, &tree.perf.id).is_some()); - } - - /// The list view's opened folder is the zone's rule: everything under it. - #[test] - fn an_opened_folder_lists_its_whole_sub_tree() { - let mut connection = open_in_memory().unwrap(); - let tree = tree(&mut connection); - filed(&mut connection, &tree, "Requête", &tree.sql); - filed(&mut connection, &tree, "Index partiel", &tree.index); - filed(&mut connection, &tree, "Composant", &tree.angular); - - let (notes, _) = fetch( - &mut connection, - &NotesQuery { - space_id: Some(tree.space.clone()), - folder_id: Some(tree.sql.id.clone()), - search: String::new(), - filter: NoteFilter::All, - tags: Vec::new(), - languages: Vec::new(), - kinds: Vec::new(), - priorities: Vec::new(), - order: NoteOrder::default(), - grouping: Grouping::default(), - ranked: false, - now: t1(), - tz_offset_minutes: 0, - pinned_first: true, - }, - ) - .unwrap(); - - let mut titles: Vec = notes.into_iter().map(|note| note.title).collect(); - titles.sort(); - assert_eq!(titles, ["Index partiel", "Requête"]); - } -} diff --git a/crates/engine/tests/folders/board.rs b/crates/engine/tests/folders/board.rs new file mode 100644 index 000000000..61c97cc60 --- /dev/null +++ b/crates/engine/tests/folders/board.rs @@ -0,0 +1,722 @@ +use super::*; + +// Read with the board's, to be rewritten with it. +use common::snippet as draft; +use engine::folders::model::Lineage; +use engine::folders::store::{file_many, restore_filings}; +use engine::notes::kind::NoteKind; +use engine::notes::language::Language; +use engine::notes::priority::Priority; + +use engine::folders::board::{self, BoardFrame, BoardPoint, BoardQuery, BoardView, PreviewLines}; +use engine::folders::store::board as geometry; +use engine::notes::store::fetch; +use engine::notes::view::{Grouping, NoteFilter, NoteOrder, NotesQuery}; + +pub(super) fn request(space_id: &str) -> BoardQuery { + BoardQuery { + space_id: space_id.to_string(), + root_id: None, + search: String::new(), + filter: NoteFilter::All, + tags: Vec::new(), + languages: Vec::new(), + kinds: Vec::new(), + priorities: Vec::new(), + now: t1(), + tz_offset_minutes: 0, + preview_lines: PreviewLines::default(), + } +} + +/// What `board_view` does, minus the decoration passes that need a connection. +pub(super) fn view(connection: &mut Library, query: &BoardQuery) -> BoardView { + let folders = list(connection, Some(&query.space_id)).unwrap(); + let (notes, facets) = fetch( + connection, + &NotesQuery { + space_id: Some(query.space_id.clone()), + folder_id: None, + search: String::new(), + filter: NoteFilter::All, + tags: Vec::new(), + languages: Vec::new(), + kinds: Vec::new(), + priorities: Vec::new(), + order: NoteOrder::default(), + grouping: Grouping::default(), + ranked: false, + now: query.now, + tz_offset_minutes: 0, + pinned_first: true, + }, + ) + .unwrap(); + + let lineage = Lineage::of(&folders); + let root = query.root_id.as_deref(); + let zones: Vec<(String, bool)> = lineage + .children(root) + .iter() + .map(|id| (id.clone(), !lineage.children(Some(id)).is_empty())) + .collect(); + let (frames, positions) = geometry::geometry( + connection, + &query.space_id, + &zones, + &board::Occupancy::on(¬es, &lineage, root), + CARD, + ) + .unwrap(); + + board::build(notes, &folders, &frames, &positions, &facets, query) +} + +pub(super) fn titled(connection: &mut Library, space_id: &str, title: &str) -> Note { + create_note( + connection, + NoteDraft { + title: title.to_string(), + ..draft(space_id) + }, + t0(), + ) + .unwrap() +} + +#[test] +fn a_board_draws_every_folder_as_a_zone_holding_its_notes() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + // Distinct instants: `list` orders by `(created_at, id)`, so two folders made + // in the same millisecond fall back to their UUIDs — stable across launches, which + // is what the board needs, but not something a test can name. + let migrations = create(&mut connection, &sql, None, "Migrations", t0()).unwrap(); + create(&mut connection, &sql, None, "Perf", t1()).unwrap(); + let filed = note_in(&mut connection, &sql); + note_in(&mut connection, &sql); + file_many( + &mut connection, + std::slice::from_ref(&filed.id), + Some(&migrations.id), + CARD, + ) + .unwrap(); + + let board = view(&mut connection, &request(&sql)); + + assert_eq!(board.zones.len(), 2); + assert_eq!(board.zones[0].folder.name, "Migrations"); + assert_eq!(board.zones[0].notes.len(), 1); + assert!(board.zones[1].notes.is_empty()); + assert_eq!(board.loose.len(), 1); +} + +/// A board is a list like the canvas: filed or loose, a card carries a preview. +#[test] +fn a_board_card_carries_the_head_of_a_long_body() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); + // A snippet: a Note's preview is its words, not its lines. + let long = || NoteDraft { + language: Language::Sh, + content: "1\n2\n3\n4\n5\n6\n7".to_string(), + ..draft(&sql) + }; + let filed = create_note(&mut connection, long(), t0()).unwrap(); + create_note(&mut connection, long(), t0()).unwrap(); + file_many( + &mut connection, + std::slice::from_ref(&filed.id), + Some(&perf.id), + CARD, + ) + .unwrap(); + + let mut board = view(&mut connection, &request(&sql)); + + assert_eq!(board.notes_mut().count(), 2); + assert!( + board + .notes_mut() + .all(|note| note.truncated && note.content == "1\n2\n3\n4\n5") + ); +} + +/// A filed card flows inside its zone; only a loose one carries a place of its own. +#[test] +fn a_filed_card_has_no_position_and_a_loose_one_does() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); + let filed = note_in(&mut connection, &sql); + note_in(&mut connection, &sql); + file_many( + &mut connection, + std::slice::from_ref(&filed.id), + Some(&perf.id), + CARD, + ) + .unwrap(); + + let board = view(&mut connection, &request(&sql)); + + assert!(board.zones[0].notes[0].position.is_none()); + assert!(board.loose[0].position.is_some()); +} + +/// The board would look shuffled at every launch otherwise. +#[test] +fn the_first_layout_is_written_down_and_read_back_unchanged() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + create(&mut connection, &sql, None, "Migrations", t0()).unwrap(); + create(&mut connection, &sql, None, "Perf", t0()).unwrap(); + note_in(&mut connection, &sql); + + let first = view(&mut connection, &request(&sql)); + let second = view(&mut connection, &request(&sql)); + + assert_eq!( + first + .zones + .iter() + .map(|zone| zone.frame) + .collect::>(), + second + .zones + .iter() + .map(|zone| zone.frame) + .collect::>(), + ); + assert_eq!(first.loose[0].position, second.loose[0].position); +} + +/// A frame is computed once: the gesture that files a card into a full zone is the one +/// that makes room, or the card flows out of sight. +#[test] +fn filing_a_card_into_a_full_zone_makes_room_for_it() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); + let filled: Vec = ["a", "b"] + .iter() + .map(|title| titled(&mut connection, &sql, title).id) + .collect(); + file_many(&mut connection, &filled, Some(&perf.id), CARD).unwrap(); + let before = view(&mut connection, &request(&sql)).zones[0].frame; + + let extra = titled(&mut connection, &sql, "c"); + file_many( + &mut connection, + std::slice::from_ref(&extra.id), + Some(&perf.id), + CARD, + ) + .unwrap(); + + let after = view(&mut connection, &request(&sql)).zones[0].frame; + assert!( + after.height > before.height, + "the zone stayed {}px tall for three cards", + before.height + ); + assert_eq!(after.width, before.width, "the width must not move"); +} + +/// A zone slightly narrower than nominal still flows two across, so the next card filed +/// in needs at most one more row. +#[test] +fn filing_into_a_zone_shaved_narrower_than_nominal_adds_one_row_and_not_two() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); + view(&mut connection, &request(&sql)); + + let shaved = BoardFrame { + x: 0, + y: 40, + width: board::default_zone_width() - 14, + height: board::zone_height(2, 2, false, CARD), + }; + connection + .transaction(|connection, _vault| geometry::set_frame(connection, &perf.id, shaved)) + .unwrap(); + + let notes: Vec = ["a", "b", "c"] + .iter() + .map(|title| titled(&mut connection, &sql, title).id) + .collect(); + file_many(&mut connection, ¬es, Some(&perf.id), CARD).unwrap(); + + let after = view(&mut connection, &request(&sql)).zones[0].frame; + assert_eq!(after.width, shaved.width, "the width must not move"); + assert_eq!( + after.height, + board::zone_height(3, 2, false, CARD), + "three cards two across are two rows, not three" + ); +} + +/// Grow only: shrinking would move the board under the pointer every time a card +/// is taken out, and a zone somebody stretched is a zone they chose the size of. +#[test] +fn a_zone_made_bigger_by_hand_keeps_its_size() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); + view(&mut connection, &request(&sql)); + + let stretched = BoardFrame { + x: 40, + y: 40, + width: 600, + height: 900, + }; + connection + .transaction(|connection, _vault| geometry::set_frame(connection, &perf.id, stretched)) + .unwrap(); + + let note = titled(&mut connection, &sql, "a"); + file_many( + &mut connection, + std::slice::from_ref(¬e.id), + Some(&perf.id), + CARD, + ) + .unwrap(); + + assert_eq!( + view(&mut connection, &request(&sql)).zones[0].frame, + stretched + ); +} + +/// Taking a card out leaves the room it needed: the board must not move on its own. +#[test] +fn unfiling_a_card_does_not_close_the_zone_again() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); + let notes: Vec = ["a", "b", "c"] + .iter() + .map(|title| titled(&mut connection, &sql, title).id) + .collect(); + file_many(&mut connection, ¬es, Some(&perf.id), CARD).unwrap(); + let grown = view(&mut connection, &request(&sql)).zones[0].frame; + + file_many(&mut connection, ¬es[..1], None, CARD).unwrap(); + + assert_eq!(view(&mut connection, &request(&sql)).zones[0].frame, grown); +} + +/// Undoing puts notes back into a zone that may no longer be tall enough for them. +#[test] +fn undoing_a_filing_makes_room_for_what_comes_back() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); + let notes: Vec = ["a", "b", "c"] + .iter() + .map(|title| titled(&mut connection, &sql, title).id) + .collect(); + file_many(&mut connection, ¬es, Some(&perf.id), CARD).unwrap(); + let grown = view(&mut connection, &request(&sql)).zones[0].frame; + + // Squashed back down behind the zone's back, as a resize would. + connection + .transaction(|connection, _vault| { + geometry::set_frame( + connection, + &perf.id, + BoardFrame { + height: 212, + ..grown + }, + ) + }) + .unwrap(); + let left = file_many(&mut connection, ¬es[..1], None, CARD).unwrap(); + restore_filings(&mut connection, &left, CARD).unwrap(); + + assert_eq!( + view(&mut connection, &request(&sql)).zones[0].frame.height, + grown.height + ); +} + +#[test] +fn a_stored_frame_survives_the_next_read() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); + view(&mut connection, &request(&sql)); + + let moved = BoardFrame { + x: 700, + y: 500, + width: 300, + height: 200, + }; + connection + .transaction(|connection, _vault| geometry::set_frame(connection, &perf.id, moved)) + .unwrap(); + + assert_eq!(view(&mut connection, &request(&sql)).zones[0].frame, moved); +} + +#[test] +fn a_folder_added_later_lands_beside_the_others_rather_than_on_top() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + create(&mut connection, &sql, None, "Migrations", t0()).unwrap(); + let first = view(&mut connection, &request(&sql)).zones[0].frame; + + create(&mut connection, &sql, None, "Perf", t1()).unwrap(); + let board = view(&mut connection, &request(&sql)); + + assert_eq!(board.zones[0].frame, first); + assert_ne!(board.zones[1].frame, first); +} + +/// Dimmed, never dropped: reflowing the survivors throws away the only thing the board +/// has that the date view does not. +#[test] +fn a_search_dims_what_it_does_not_match_and_removes_nothing() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); + let wanted = titled(&mut connection, &sql, "Index sur orders"); + titled(&mut connection, &sql, "Dump nocturne"); + file_many( + &mut connection, + std::slice::from_ref(&wanted.id), + Some(&perf.id), + CARD, + ) + .unwrap(); + + let board = view( + &mut connection, + &BoardQuery { + search: "orders".to_string(), + ..request(&sql) + }, + ); + + assert_eq!(board.zones[0].notes.len(), 1); + assert_eq!(board.loose.len(), 1); + assert!(board.zones[0].notes[0].matches); + assert!(!board.loose[0].matches); + assert_eq!(board.matched, 1); + assert!(board.is_filtering); +} + +/// Accents fold both ways here too: it is `notes::view`'s own matcher, not a second one. +#[test] +fn the_board_search_folds_accents_like_the_canvas_does() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + titled(&mut connection, &sql, "Étape suivante"); + + let board = view( + &mut connection, + &BoardQuery { + search: "etape".to_string(), + ..request(&sql) + }, + ); + + assert!(board.loose[0].matches); +} + +#[test] +fn a_quick_filter_dims_rather_than_narrows_too() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + create_note( + &mut connection, + NoteDraft { + pinned: true, + ..draft(&sql) + }, + t0(), + ) + .unwrap(); + create_note(&mut connection, draft(&sql), t0()).unwrap(); + + let board = view( + &mut connection, + &BoardQuery { + filter: NoteFilter::Pinned, + ..request(&sql) + }, + ); + + assert_eq!(board.loose.len(), 2); + assert_eq!(board.matched, 1); +} + +#[test] +fn a_priority_dims_rather_than_narrows_too() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + create_note(&mut connection, draft(&sql), t0()).unwrap(); + create_note( + &mut connection, + NoteDraft { + priority: Priority::High, + ..draft(&sql) + }, + t0(), + ) + .unwrap(); + + let board = view( + &mut connection, + &BoardQuery { + priorities: vec![Priority::High], + ..request(&sql) + }, + ); + + assert_eq!(board.loose.len(), 2); + assert_eq!(board.matched, 1); +} + +#[test] +fn a_kind_dims_rather_than_narrows_too() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + create_note(&mut connection, draft(&sql), t0()).unwrap(); + create_note( + &mut connection, + NoteDraft { + kind: NoteKind::Note, + ..draft(&sql) + }, + t0(), + ) + .unwrap(); + + let board = view( + &mut connection, + &BoardQuery { + kinds: vec![NoteKind::Note], + ..request(&sql) + }, + ); + + assert_eq!(board.loose.len(), 2); + assert_eq!(board.matched, 1); + assert!(board.is_filtering); +} + +/// The two views answer the same question, and must not answer it differently. Tags +/// are compared as the column compares them — ASCII case only, `#` stripped — and a +/// tag that normalises to nothing asks for nothing. +#[test] +fn the_board_and_the_date_view_agree_on_what_matches() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + for (title, tags) in [ + ("accented", vec!["étape"]), + ("capital", vec!["Étape"]), + ("urgent", vec!["URGENT"]), + ("plain", Vec::new()), + ] { + create_note( + &mut connection, + NoteDraft { + title: title.to_string(), + tags: tags.into_iter().map(ToString::to_string).collect(), + ..draft(&sql) + }, + t0(), + ) + .unwrap(); + } + + for asked in [vec!["étape"], vec!["#urgent"], vec![" # "], Vec::new()] { + let tags: Vec = asked.iter().map(ToString::to_string).collect(); + + let query = NotesQuery { + space_id: Some(sql.clone()), + folder_id: None, + search: String::new(), + filter: NoteFilter::All, + tags: tags.clone(), + languages: Vec::new(), + kinds: Vec::new(), + priorities: Vec::new(), + order: NoteOrder::default(), + grouping: Grouping::default(), + ranked: false, + now: t1(), + tz_offset_minutes: 0, + pinned_first: true, + }; + let (notes, facets) = fetch(&mut connection, &query).unwrap(); + let dated = engine::notes::view::build(notes, facets, &query); + let mut on_the_date_view: Vec = dated + .sections + .iter() + .flat_map(|section| section.cards.iter().map(|card| card.title.clone())) + .collect(); + + let board = view( + &mut connection, + &BoardQuery { + tags, + ..request(&sql) + }, + ); + let mut lit_on_the_board: Vec = board + .loose + .iter() + .filter(|entry| entry.matches) + .map(|entry| entry.note.title.clone()) + .collect(); + + on_the_date_view.sort(); + lit_on_the_board.sort(); + assert_eq!(on_the_date_view, lit_on_the_board, "asked for {asked:?}"); + assert_eq!( + dated.is_filtering, board.is_filtering, + "asked for {asked:?}" + ); + } +} + +/// Filing a card into a zone drops the place it had on the background. +#[test] +fn filing_a_loose_note_forgets_where_it_sat() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); + let note = note_in(&mut connection, &sql); + view(&mut connection, &request(&sql)); + + let placed = connection + .transaction(|connection, _vault| geometry::positions(connection, &sql)) + .unwrap(); + assert!(placed.contains_key(¬e.id)); + + file_many( + &mut connection, + std::slice::from_ref(¬e.id), + Some(&perf.id), + CARD, + ) + .unwrap(); + + let after = connection + .transaction(|connection, _vault| geometry::positions(connection, &sql)) + .unwrap(); + assert!(!after.contains_key(¬e.id)); +} + +#[test] +fn a_stored_position_is_what_a_later_read_hands_back() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + let note = note_in(&mut connection, &sql); + view(&mut connection, &request(&sql)); + + let chosen = BoardPoint { x: 640, y: 480 }; + connection + .transaction(|connection, _vault| geometry::set_position(connection, ¬e.id, chosen)) + .unwrap(); + + assert_eq!( + view(&mut connection, &request(&sql)).loose[0].position, + Some(chosen) + ); +} + +/// A new note is the most recently updated, so it comes first in the list: it must not +/// be handed seat zero, where another card already sits. +#[test] +fn a_note_created_later_is_placed_beside_the_cards_rather_than_on_one() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + titled(&mut connection, &sql, "Dump nocturne"); + let already_there = view(&mut connection, &request(&sql)).loose[0].position; + + create_note( + &mut connection, + NoteDraft { + title: "Collé du presse-papiers".to_string(), + ..draft(&sql) + }, + t1(), + ) + .unwrap(); + + let board = view(&mut connection, &request(&sql)); + let places: Vec<_> = board.loose.iter().map(|entry| entry.position).collect(); + + assert_eq!(places.len(), 2); + assert!( + places.contains(&already_there), + "the card already there did not move" + ); + assert_ne!(places[0], places[1], "two cards were written to one place"); +} + +/// Every unplaced card in the same pass, not just the first one. +#[test] +fn a_first_read_of_several_loose_notes_gives_each_its_own_place() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + for title in ["Un", "Deux", "Trois", "Quatre", "Cinq"] { + titled(&mut connection, &sql, title); + } + + let board = view(&mut connection, &request(&sql)); + let mut places: Vec<_> = board + .loose + .iter() + .map(|entry| entry.position.expect("a loose card is always placed")) + .map(|at| (at.x, at.y)) + .collect(); + places.sort_unstable(); + places.dedup(); + + assert_eq!(places.len(), 5); +} + +#[test] +fn the_surface_grows_to_hold_whatever_is_furthest_out() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + let note = note_in(&mut connection, &sql); + view(&mut connection, &request(&sql)); + + connection + .transaction(|connection, _vault| { + geometry::set_position(connection, ¬e.id, BoardPoint { x: 3000, y: 2000 }) + }) + .unwrap(); + + let board = view(&mut connection, &request(&sql)); + assert!(board.width > 3000); + assert!(board.height > 2000); +} + +/// A board of one space says nothing about the next one. +#[test] +fn a_board_never_reaches_into_another_space() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + let veille = space(&mut connection, "Veille"); + create(&mut connection, &sql, None, "Perf", t0()).unwrap(); + create(&mut connection, &veille, None, "Liens", t0()).unwrap(); + note_in(&mut connection, &veille); + + let board = view(&mut connection, &request(&sql)); + + assert_eq!(board.zones.len(), 1); + assert!(board.loose.is_empty()); +} diff --git a/crates/engine/tests/folders/gesture.rs b/crates/engine/tests/folders/gesture.rs new file mode 100644 index 000000000..696a3c2fd --- /dev/null +++ b/crates/engine/tests/folders/gesture.rs @@ -0,0 +1,458 @@ +use super::*; + +// Read with the board's, to be rewritten with it. +use std::collections::HashMap; + +use engine::error::StorageError; +use engine::folders::store::file_many; + +use engine::folders::board::{ + BoardFrame, BoardPoint, CardPlacement, MIN_ZONE_HEIGHT, MIN_ZONE_WIDTH, ZonePlacement, clamp, + clamp_point, zone_at, +}; +use engine::folders::store::board as geometry; + +fn frames(connection: &mut Library, space_id: &str) -> HashMap { + connection + .transaction(|connection, _vault| geometry::frames(connection, space_id)) + .unwrap() +} + +fn positions(connection: &mut Library, space_id: &str) -> HashMap { + connection + .transaction(|connection, _vault| geometry::positions(connection, space_id)) + .unwrap() +} + +/// Puts a zone and a card exactly where a drag would have left them. +fn place(connection: &mut Library, zones: &[ZonePlacement], cards: &[CardPlacement]) { + geometry::save_layout(connection, None, zones, cards).unwrap(); +} + +fn zone_at_frame(folder_id: &str, frame: BoardFrame) -> ZonePlacement { + ZonePlacement { + folder_id: folder_id.to_string(), + frame, + } +} + +fn card_at(note_id: &str, position: BoardPoint) -> CardPlacement { + CardPlacement { + note_id: note_id.to_string(), + position, + } +} + +#[test] +fn a_moved_zone_and_a_moved_card_are_written_as_one_batch() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); + let note = note_in(&mut connection, &sql); + + let frame = BoardFrame { + x: 600, + y: 320, + width: 520, + height: 400, + }; + let point = BoardPoint { x: 48, y: 720 }; + geometry::save_layout( + &mut connection, + None, + &[ZonePlacement { + folder_id: perf.id.clone(), + frame, + }], + &[CardPlacement { + note_id: note.id.clone(), + position: point, + }], + ) + .unwrap(); + + assert_eq!(frames(&mut connection, &sql).get(&perf.id), Some(&frame)); + assert_eq!(positions(&mut connection, &sql).get(¬e.id), Some(&point)); +} + +/// A zone nothing can be dropped into is not a zone. Clamped rather than refused: +/// answering an error mid-gesture leaves the interface holding a frame nothing stored. +#[test] +fn a_zone_squashed_to_nothing_keeps_room_for_one_card() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); + + geometry::save_layout( + &mut connection, + None, + &[ZonePlacement { + folder_id: perf.id.clone(), + frame: BoardFrame { + x: -50, + y: -50, + width: 4, + height: 4, + }, + }], + &[], + ) + .unwrap(); + + let stored = frames(&mut connection, &sql); + let frame = stored.get(&perf.id).unwrap(); + assert_eq!(frame.x, 0); + assert_eq!(frame.y, 0); + assert_eq!(frame.width, MIN_ZONE_WIDTH); + assert_eq!(frame.height, MIN_ZONE_HEIGHT); +} + +/// A filed card flows inside its zone. Writing a position for one would put back the +/// row `file_many` had just dropped, and the table would stop meaning "this is loose". +#[test] +fn a_card_filed_since_the_drag_is_not_given_a_position_back() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); + let note = note_in(&mut connection, &sql); + file_many( + &mut connection, + std::slice::from_ref(¬e.id), + Some(&perf.id), + CARD, + ) + .unwrap(); + + geometry::save_layout( + &mut connection, + None, + &[], + &[CardPlacement { + note_id: note.id.clone(), + position: BoardPoint { x: 10, y: 10 }, + }], + ) + .unwrap(); + + assert!(!positions(&mut connection, &sql).contains_key(¬e.id)); +} + +/// Every zone or none: half a board is a board nobody arranged. +#[test] +fn a_batch_naming_a_folder_that_is_gone_writes_nothing_at_all() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); + let note = note_in(&mut connection, &sql); + + let refused = geometry::save_layout( + &mut connection, + None, + &[ + ZonePlacement { + folder_id: perf.id.clone(), + frame: BoardFrame { + x: 600, + y: 320, + width: 520, + height: 400, + }, + }, + ZonePlacement { + folder_id: "gone".to_string(), + frame: BoardFrame { + x: 0, + y: 0, + width: 520, + height: 400, + }, + }, + ], + &[CardPlacement { + note_id: note.id.clone(), + position: BoardPoint { x: 48, y: 720 }, + }], + ); + + assert!(matches!(refused, Err(StorageError::FolderNotFound(_)))); + assert!(frames(&mut connection, &sql).is_empty()); + assert!(positions(&mut connection, &sql).is_empty()); +} + +#[test] +fn an_empty_batch_is_not_an_error() { + let mut connection = open_in_memory().unwrap(); + + assert!(geometry::save_layout(&mut connection, None, &[], &[]).is_ok()); +} + +/// Membership comes from the drop, and from nothing else. +#[test] +fn a_point_names_the_zone_it_falls_in() { + let zones = vec![ + ( + "a".to_string(), + BoardFrame { + x: 0, + y: 0, + width: 100, + height: 100, + }, + ), + ( + "b".to_string(), + BoardFrame { + x: 200, + y: 0, + width: 100, + height: 100, + }, + ), + ]; + + assert_eq!( + zone_at(&zones, BoardPoint { x: 50, y: 50 }), + Some("a".into()) + ); + assert_eq!( + zone_at(&zones, BoardPoint { x: 250, y: 50 }), + Some("b".into()) + ); +} + +/// The free background is a legitimate answer: dropping there unfiles the note. +#[test] +fn a_point_on_the_background_names_no_zone() { + let zones = vec![( + "a".to_string(), + BoardFrame { + x: 0, + y: 0, + width: 100, + height: 100, + }, + )]; + + assert_eq!(zone_at(&zones, BoardPoint { x: 150, y: 50 }), None); + // The far edges belong to the next zone along, not to this one. + assert_eq!(zone_at(&zones, BoardPoint { x: 100, y: 50 }), None); + assert_eq!(zone_at(&zones, BoardPoint { x: 0, y: 0 }), Some("a".into())); +} + +/// Drawn later means drawn on top, so it is what a drop lands in. +#[test] +fn overlapping_zones_hand_the_drop_to_the_topmost() { + let zones = vec![ + ( + "under".to_string(), + BoardFrame { + x: 0, + y: 0, + width: 200, + height: 200, + }, + ), + ( + "over".to_string(), + BoardFrame { + x: 50, + y: 50, + width: 100, + height: 100, + }, + ), + ]; + + assert_eq!( + zone_at(&zones, BoardPoint { x: 100, y: 100 }), + Some("over".into()) + ); +} + +#[test] +fn a_runaway_drag_cannot_put_anything_off_the_board() { + assert_eq!(clamp_point(BoardPoint { x: -40, y: -40 }).x, 0); + assert_eq!( + clamp(BoardFrame { + x: 10, + y: 10, + width: 1_000_000, + height: 10 + }) + .width, + engine::folders::board::MAX_SIDE + ); +} + +/// The one board gesture that cannot be walked back by dragging: it moves everything at +/// once and overwrites sizes chosen by hand. +mod tidy_up { + use super::*; + + use engine::folders::board::{BoardScope, default_zone_height, default_zone_width}; + + const DRAGGED: BoardFrame = BoardFrame { + x: 900, + y: 640, + width: 900, + height: 700, + }; + + #[test] + fn a_zone_dragged_away_comes_back_to_its_seat() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); + place(&mut connection, &[zone_at_frame(&perf.id, DRAGGED)], &[]); + + geometry::arrange(&mut connection, &sql, None, BoardScope::Everything, CARD).unwrap(); + + let frame = *frames(&mut connection, &sql).get(&perf.id).unwrap(); + assert_eq!(frame.x, 16); + assert_eq!(frame.y, 16); + assert_eq!(frame.width, default_zone_width()); + assert_eq!(frame.height, default_zone_height(0, false, CARD)); + } + + /// The half that makes it a tidy-up: a zone too small for what it holds is reopened. + #[test] + fn a_zone_is_resized_to_what_it_actually_holds() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); + let notes: Vec = (0..5).map(|_| note_in(&mut connection, &sql).id).collect(); + file_many(&mut connection, ¬es, Some(&perf.id), CARD).unwrap(); + + geometry::arrange(&mut connection, &sql, None, BoardScope::Everything, CARD).unwrap(); + + let frame = *frames(&mut connection, &sql).get(&perf.id).unwrap(); + assert_eq!(frame.height, default_zone_height(5, false, CARD)); + } + + #[test] + fn the_loose_cards_flow_under_the_zones() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); + let filed = note_in(&mut connection, &sql).id; + file_many(&mut connection, &[filed], Some(&perf.id), CARD).unwrap(); + let loose = note_in(&mut connection, &sql).id; + + geometry::arrange(&mut connection, &sql, None, BoardScope::Everything, CARD).unwrap(); + + let zone = *frames(&mut connection, &sql).get(&perf.id).unwrap(); + let at = *positions(&mut connection, &sql).get(&loose).unwrap(); + assert!(at.y > zone.y + zone.height); + } + + /// What the undo reads. Restoring the answer has to put the board back exactly as + /// it was, or the tidy-up is a one-way gesture. + #[test] + fn it_answers_the_layout_it_replaced() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); + let note = note_in(&mut connection, &sql); + let seat = BoardPoint { x: 96, y: 900 }; + place( + &mut connection, + &[zone_at_frame(&perf.id, DRAGGED)], + &[card_at(¬e.id, seat)], + ); + + let before = geometry::arrange(&mut connection, &sql, None, BoardScope::Everything, CARD) + .unwrap() + .previous; + place(&mut connection, &before.zones, &before.cards); + + assert_eq!(frames(&mut connection, &sql).get(&perf.id), Some(&DRAGGED)); + assert_eq!(positions(&mut connection, &sql).get(¬e.id), Some(&seat)); + } + + /// A folder the board has never drawn had no place to go back to, and inventing + /// one on the undo would leave it somewhere nobody chose. + #[test] + fn a_zone_that_never_had_a_place_is_not_offered_back() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + create(&mut connection, &sql, None, "Perf", t0()).unwrap(); + note_in(&mut connection, &sql); + + let before = + geometry::arrange(&mut connection, &sql, None, BoardScope::Everything, CARD).unwrap(); + + assert!(before.previous.zones.is_empty()); + assert!(before.previous.cards.is_empty()); + } + + /// The half worth a single click: what goes to pieces is the cards outside the + /// zones, and a zone somebody sized by hand is the only manual work the board holds. + #[test] + fn aligning_the_loose_cards_leaves_every_zone_exactly_where_it_was() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); + let note = note_in(&mut connection, &sql); + place( + &mut connection, + &[zone_at_frame(&perf.id, DRAGGED)], + &[card_at(¬e.id, BoardPoint { x: 640, y: 1200 })], + ); + + let done = + geometry::arrange(&mut connection, &sql, None, BoardScope::LooseCards, CARD).unwrap(); + + assert_eq!(frames(&mut connection, &sql).get(&perf.id), Some(&DRAGGED)); + assert!(done.previous.zones.is_empty()); + assert_eq!(done.moved, 1); + } + + /// The cards flow under the zones **as they stand**, not under where a full + /// reorganisation would have put them. + #[test] + fn the_aligned_cards_clear_the_zones_where_they_actually_are() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); + let note = note_in(&mut connection, &sql); + place(&mut connection, &[zone_at_frame(&perf.id, DRAGGED)], &[]); + + geometry::arrange(&mut connection, &sql, None, BoardScope::LooseCards, CARD).unwrap(); + + let at = *positions(&mut connection, &sql).get(¬e.id).unwrap(); + assert!(at.y > DRAGGED.y + DRAGGED.height); + } + + /// What the undo bar reads. A board nobody disturbed must open no undo window, + /// or the bar offers to put back an arrangement that never changed. + #[test] + fn a_board_already_in_order_reports_nothing_moved() { + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + create(&mut connection, &sql, None, "Perf", t0()).unwrap(); + note_in(&mut connection, &sql); + geometry::arrange(&mut connection, &sql, None, BoardScope::Everything, CARD).unwrap(); + + let again = + geometry::arrange(&mut connection, &sql, None, BoardScope::Everything, CARD).unwrap(); + + assert_eq!(again.moved, 0); + } + + #[test] + fn a_trashed_note_takes_no_room_in_the_zone_it_was_in() { + use engine::notes::store::trash::trash_many; + + let mut connection = open_in_memory().unwrap(); + let sql = space(&mut connection, "SQL"); + let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); + let notes: Vec = (0..4).map(|_| note_in(&mut connection, &sql).id).collect(); + file_many(&mut connection, ¬es, Some(&perf.id), CARD).unwrap(); + trash_many(&mut connection, ¬es[..3], t1()).unwrap(); + + geometry::arrange(&mut connection, &sql, None, BoardScope::Everything, CARD).unwrap(); + + let frame = *frames(&mut connection, &sql).get(&perf.id).unwrap(); + assert_eq!(frame.height, default_zone_height(1, false, CARD)); + } +} diff --git a/crates/engine/tests/folders/main.rs b/crates/engine/tests/folders/main.rs new file mode 100644 index 000000000..b33f744ff --- /dev/null +++ b/crates/engine/tests/folders/main.rs @@ -0,0 +1,67 @@ +//! A space's folders on a temporary library: what the store keeps, moves, files and hands back. + +use engine::db::{Library, open_in_memory}; +use engine::folders::board::{BoardFrame, default_zone_width}; +use engine::folders::store::{create, list}; +use engine::notes::model::{Note, NoteDraft}; +use engine::notes::store::{create as create_note, get}; + +#[path = "../common/mod.rs"] +mod common; +use common::{snippet, space, t0, t1}; + +mod nesting; +mod store; + +// The board's own tests, rewritten in a lot of their own. +mod board; +mod gesture; +mod nested_boards; + +/// The height of a card on these boards. +const CARD: i32 = 140; + +fn note_in(connection: &mut Library, space_id: &str) -> Note { + create_note(connection, snippet(space_id), t0()).unwrap() +} + +fn filed(connection: &mut Library, space_id: &str, folder_id: &str) -> String { + let draft = NoteDraft { + folder_id: Some(folder_id.to_string()), + ..snippet(space_id) + }; + create_note(connection, draft, t0()).unwrap().id +} + +fn folder(connection: &mut Library, space_id: &str, parent_id: Option<&str>, name: &str) -> String { + create(connection, space_id, parent_id, name, t0()) + .unwrap() + .id +} + +fn names(connection: &mut Library, space_id: &str) -> Vec { + let folders = list(connection, Some(space_id)).unwrap(); + folders.into_iter().map(|folder| folder.name).collect() +} + +fn parent_of(connection: &mut Library, folder_id: &str) -> Option { + let folders = list(connection, None).unwrap(); + let found = folders.into_iter().find(|folder| folder.id == folder_id); + found.unwrap().parent_id +} + +/// A live note's space and folder. +fn place_of(connection: &mut Library, note_id: &str) -> (String, Option) { + let note = get(connection, note_id).unwrap(); + (note.space_id, note.folder_id) +} + +/// A zone at the default width, too short for any card. +fn flat_frame() -> BoardFrame { + BoardFrame { + x: 0, + y: 0, + width: default_zone_width(), + height: 10, + } +} diff --git a/crates/engine/tests/folders/nested_boards.rs b/crates/engine/tests/folders/nested_boards.rs new file mode 100644 index 000000000..3fb461e76 --- /dev/null +++ b/crates/engine/tests/folders/nested_boards.rs @@ -0,0 +1,179 @@ +use super::board::{request, titled, view}; +use super::*; + +use engine::folders::board::{BoardFrame, BoardPoint, CardPlacement, ZonePlacement}; +use engine::folders::model::Folder; +use engine::folders::store::board as geometry; +use engine::folders::store::file_many; + +/// `SQL › Perf › Index` and `SQL › Migrations`, and `Angular` beside them. +struct Tree { + space: String, + sql: Folder, + perf: Folder, + index: Folder, + angular: Folder, +} + +fn tree(connection: &mut Library) -> Tree { + // A millisecond apart: folders made in one instant would come back in the order of + // their ids. + let after = |ms: i64| t0() + chrono::TimeDelta::milliseconds(ms); + let space = space(connection, "Découverte"); + let sql = create(connection, &space, None, "SQL", after(0)).unwrap(); + let perf = create(connection, &space, Some(&sql.id), "Perf", after(1)).unwrap(); + let index = create(connection, &space, Some(&perf.id), "Index", after(2)).unwrap(); + create(connection, &space, Some(&sql.id), "Migrations", after(3)).unwrap(); + let angular = create(connection, &space, None, "Angular", after(4)).unwrap(); + Tree { + space, + sql, + perf, + index, + angular, + } +} + +fn filed(connection: &mut Library, tree: &Tree, title: &str, folder: &Folder) -> Note { + let note = titled(connection, &tree.space, title); + file_many( + connection, + std::slice::from_ref(¬e.id), + Some(&folder.id), + CARD, + ) + .unwrap(); + note +} + +fn frame_of(connection: &mut Library, id: &str) -> Option { + connection + .transaction(|connection, _vault| geometry::frame_of(connection, id)) + .unwrap() +} + +/// The space's board shows its top folders; each gathers its whole sub-tree. +#[test] +fn a_zone_gathers_the_notes_of_everything_under_it() { + let mut connection = open_in_memory().unwrap(); + let tree = tree(&mut connection); + filed(&mut connection, &tree, "Requête", &tree.sql); + filed(&mut connection, &tree, "EXPLAIN", &tree.perf); + filed(&mut connection, &tree, "Index partiel", &tree.index); + titled(&mut connection, &tree.space, "Loose"); + + let board = view(&mut connection, &request(&tree.space)); + + let zones: Vec<&str> = board + .zones + .iter() + .map(|zone| zone.folder.name.as_str()) + .collect(); + assert_eq!(zones, ["SQL", "Angular"]); + assert_eq!(board.zones[0].notes.len(), 3); + let children: Vec<(&str, u32)> = board.zones[0] + .children + .iter() + .map(|child| (child.name.as_str(), child.count)) + .collect(); + assert_eq!(children, [("Migrations", 0), ("Perf", 2)]); + assert!(board.zones[1].children.is_empty()); + assert_eq!(board.loose.len(), 1); +} + +/// A folder's board: its sub-folders as zones, what is filed in it free on its ground, and +/// nothing from outside it. +#[test] +fn a_folders_board_draws_its_sub_folders_and_its_own_notes_free() { + let mut connection = open_in_memory().unwrap(); + let tree = tree(&mut connection); + let own = filed(&mut connection, &tree, "Requête", &tree.sql); + filed(&mut connection, &tree, "Index partiel", &tree.index); + filed(&mut connection, &tree, "Composant", &tree.angular); + titled(&mut connection, &tree.space, "Loose"); + let mut inside = request(&tree.space); + inside.root_id = Some(tree.sql.id.clone()); + + let board = view(&mut connection, &inside); + + let zones: Vec<(&str, usize)> = board + .zones + .iter() + .map(|zone| (zone.folder.name.as_str(), zone.notes.len())) + .collect(); + assert_eq!(zones, [("Perf", 1), ("Migrations", 0)]); + assert_eq!(board.loose.len(), 1); + assert_eq!(board.loose[0].note.id, own.id); + assert!(board.loose[0].position.is_some()); + assert_eq!(board.matched, 2); +} + +/// A row of chips under the title is height the cards must not pay for. +#[test] +fn a_zone_with_sub_folders_is_taller_by_their_row() { + let mut connection = open_in_memory().unwrap(); + let tree = tree(&mut connection); + + let board = view(&mut connection, &request(&tree.space)); + + assert_eq!( + board.zones[0].frame.height - board.zones[1].frame.height, + engine::folders::board::ZONE_SUBFOLDERS + ); +} + +/// A card's place is on its own folder's board: saved from another board, it is refused. +#[test] +fn a_place_is_kept_only_on_the_board_of_the_cards_own_folder() { + let mut connection = open_in_memory().unwrap(); + let tree = tree(&mut connection); + let own = filed(&mut connection, &tree, "Requête", &tree.sql); + let deeper = filed(&mut connection, &tree, "EXPLAIN", &tree.perf); + let place = BoardPoint { x: 640, y: 480 }; + let cards = [own.id.clone(), deeper.id.clone()].map(|note_id| CardPlacement { + note_id, + position: place, + }); + + geometry::save_layout(&mut connection, Some(&tree.sql.id), &[], &cards).unwrap(); + + let placed = connection + .transaction(|connection, _vault| geometry::positions(connection, &tree.space)) + .unwrap(); + assert_eq!(placed.get(&own.id), Some(&place)); + assert!(!placed.contains_key(&deeper.id)); +} + +#[test] +fn a_folders_board_is_tidied_on_its_own() { + let mut connection = open_in_memory().unwrap(); + let tree = tree(&mut connection); + let frame = BoardFrame { + x: 2000, + y: 2000, + width: 600, + height: 400, + }; + geometry::save_layout( + &mut connection, + None, + &[ZonePlacement { + folder_id: tree.angular.id.clone(), + frame, + }], + &[], + ) + .unwrap(); + + geometry::arrange( + &mut connection, + &tree.space, + Some(&tree.sql.id), + engine::folders::board::BoardScope::Everything, + CARD, + ) + .unwrap(); + + assert_eq!(frame_of(&mut connection, &tree.angular.id), Some(frame)); + assert!(frame_of(&mut connection, &tree.perf.id).is_some()); +} diff --git a/crates/engine/tests/folders/nesting.rs b/crates/engine/tests/folders/nesting.rs new file mode 100644 index 000000000..e4635254d --- /dev/null +++ b/crates/engine/tests/folders/nesting.rs @@ -0,0 +1,270 @@ +use super::*; + +use engine::error::StorageError; +use engine::folders::model::{FolderMove, MAX_DEPTH}; +use engine::folders::store::board::{frame_of, set_frame}; +use engine::folders::store::{delete, move_back, move_to}; +use engine::notes::store::trash::{list_trashed, trash}; + +/// f1 ─ f2 ─ … under the top of `space_id`, `levels` deep; the deepest is answered. +fn chain(connection: &mut Library, space_id: &str, levels: usize) -> String { + let mut parent: Option = None; + for level in 1..=levels { + let name = format!("f{level}"); + parent = Some(folder(connection, space_id, parent.as_deref(), &name)); + } + parent.unwrap() +} + +fn refused_as_parent(answer: Result) -> bool { + matches!(answer, Err(StorageError::Invalid(refused)) if refused.field == "parentId") +} + +#[test] +fn a_folder_moved_under_another_takes_what_it_holds_and_lets_go_of_its_frame() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let infra = folder(&mut connection, &work, None, "Infra"); + let perf = folder(&mut connection, &work, Some(&infra), "Perf"); + let docs = folder(&mut connection, &work, None, "Docs"); + set_frame(connection.db(), &infra, flat_frame()).unwrap(); + let held = filed(&mut connection, &work, &infra); + + let was = move_to(&mut connection, &infra, (&work, Some(&docs))).unwrap(); + + assert_eq!( + was, + FolderMove { + folder_id: infra.clone(), + space_id: work.clone(), + parent_id: None, + frame: Some(flat_frame()), + notes: Vec::new(), + } + ); + assert_eq!(parent_of(&mut connection, &infra), Some(docs)); + assert_eq!(parent_of(&mut connection, &perf), Some(infra.clone())); + assert_eq!(frame_of(connection.db(), &infra).unwrap(), None); + assert_eq!(place_of(&mut connection, &held), (work, Some(infra))); +} + +#[test] +fn a_folder_moved_where_it_already_is_keeps_its_frame() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let infra = folder(&mut connection, &work, None, "Infra"); + set_frame(connection.db(), &infra, flat_frame()).unwrap(); + + let was = move_to(&mut connection, &infra, (&work, None)).unwrap(); + + assert_eq!(was.frame, Some(flat_frame())); + assert_eq!( + frame_of(connection.db(), &infra).unwrap(), + Some(flat_frame()) + ); +} + +#[test] +fn a_folder_never_moves_into_itself_what_it_holds_or_a_folder_of_another_space() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let home = space(&mut connection, "Home"); + let infra = folder(&mut connection, &work, None, "Infra"); + let perf = folder(&mut connection, &work, Some(&infra), "Perf"); + let garden = folder(&mut connection, &home, None, "Garden"); + + for into in [&infra, &perf, &garden] { + assert!(refused_as_parent(move_to( + &mut connection, + &infra, + (&work, Some(into)) + ))); + } + assert_eq!(parent_of(&mut connection, &infra), None); +} + +#[test] +fn a_folder_moves_only_where_its_name_is_free_among_its_new_siblings() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let docs = folder(&mut connection, &work, None, "Docs"); + folder(&mut connection, &work, Some(&docs), "Perf"); + let perf = folder(&mut connection, &work, None, "PERF"); + + assert!(matches!( + move_to(&mut connection, &perf, (&work, Some(&docs))), + Err(StorageError::DuplicateFolderName(_)) + )); + assert_eq!(parent_of(&mut connection, &perf), None); +} + +/// What it holds moves with it, and counts. +#[test] +fn a_folder_moves_only_where_its_deepest_sub_folder_stays_within_the_limit() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let deepest = chain(&mut connection, &work, MAX_DEPTH - 1); + let moving = folder(&mut connection, &work, None, "Moving"); + folder(&mut connection, &work, Some(&moving), "Below"); + + assert!(refused_as_parent(move_to( + &mut connection, + &moving, + (&work, Some(&deepest)) + ))); + let above = parent_of(&mut connection, &deepest).unwrap(); + assert!(move_to(&mut connection, &moving, (&work, Some(&above))).is_ok()); +} + +/// Trashed notes go too: a restore must not bring one back into a space its folder left. +#[test] +fn a_folder_moved_to_another_space_takes_its_sub_folders_and_every_note_filed_in_them() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let home = space(&mut connection, "Home"); + let infra = folder(&mut connection, &work, None, "Infra"); + let perf = folder(&mut connection, &work, Some(&infra), "Perf"); + let in_infra = filed(&mut connection, &work, &infra); + let in_perf = filed(&mut connection, &work, &perf); + let trashed = filed(&mut connection, &work, &perf); + trash(&mut connection, &trashed, t1()).unwrap(); + let loose = note_in(&mut connection, &work).id; + + let was = move_to(&mut connection, &infra, (&home, None)).unwrap(); + + let mut went = was.notes; + went.sort(); + let mut expected = vec![in_infra.clone(), in_perf.clone(), trashed]; + expected.sort(); + assert_eq!(went, expected); + let mut moved = names(&mut connection, &home); + moved.sort(); + assert_eq!(moved, ["Infra", "Perf"]); + assert_eq!( + place_of(&mut connection, &in_perf), + (home.clone(), Some(perf)) + ); + assert_eq!(list_trashed(&mut connection).unwrap()[0].0.space_id, home); + assert_eq!(place_of(&mut connection, &loose), (work, None)); + assert_eq!(get(&mut connection, &in_infra).unwrap().updated_at, t0()); +} + +#[test] +fn a_folder_lands_in_another_space_only_under_its_folders_with_room_for_its_levels() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let home = space(&mut connection, "Home"); + let infra = folder(&mut connection, &work, None, "Infra"); + folder(&mut connection, &work, Some(&infra), "Perf"); + let docs = folder(&mut connection, &work, None, "Docs"); + let deepest = chain(&mut connection, &home, MAX_DEPTH - 1); + + assert!(refused_as_parent(move_to( + &mut connection, + &infra, + (&home, Some(&docs)) + ))); + assert!(refused_as_parent(move_to( + &mut connection, + &infra, + (&home, Some(&deepest)) + ))); + assert_eq!(names(&mut connection, &work).len(), 3); +} + +#[test] +fn a_move_undone_puts_the_folder_back_under_its_parent_in_its_frame() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let docs = folder(&mut connection, &work, None, "Docs"); + let infra = folder(&mut connection, &work, Some(&docs), "Infra"); + set_frame(connection.db(), &infra, flat_frame()).unwrap(); + let was = move_to(&mut connection, &infra, (&work, None)).unwrap(); + + let went = move_back(&mut connection, &was).unwrap(); + + assert_eq!(went, Some(Vec::new())); + assert_eq!(parent_of(&mut connection, &infra), Some(docs)); + assert_eq!( + frame_of(connection.db(), &infra).unwrap(), + Some(flat_frame()) + ); +} + +#[test] +fn a_move_to_another_space_undone_brings_the_folder_s_notes_back() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let home = space(&mut connection, "Home"); + let infra = folder(&mut connection, &work, None, "Infra"); + let id = filed(&mut connection, &work, &infra); + let was = move_to(&mut connection, &infra, (&home, None)).unwrap(); + + let went = move_back(&mut connection, &was).unwrap(); + + assert_eq!(went, Some(vec![id.clone()])); + assert_eq!(names(&mut connection, &work), ["Infra"]); + assert_eq!(place_of(&mut connection, &id), (work, Some(infra))); +} + +/// The undo answers `None` and moves nothing when the place it left cannot take it back. +#[test] +fn a_move_is_not_undone_into_a_parent_gone_since() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let docs = folder(&mut connection, &work, None, "Docs"); + let infra = folder(&mut connection, &work, Some(&docs), "Infra"); + let was = move_to(&mut connection, &infra, (&work, None)).unwrap(); + delete(&mut connection, &docs, CARD, None).unwrap(); + + assert_eq!(move_back(&mut connection, &was).unwrap(), None); + assert_eq!(parent_of(&mut connection, &infra), None); +} + +#[test] +fn a_move_is_not_undone_into_a_parent_that_now_lies_under_the_folder() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let docs = folder(&mut connection, &work, None, "Docs"); + let infra = folder(&mut connection, &work, Some(&docs), "Infra"); + let was = move_to(&mut connection, &infra, (&work, None)).unwrap(); + move_to(&mut connection, &docs, (&work, Some(&infra))).unwrap(); + + assert_eq!(move_back(&mut connection, &was).unwrap(), None); + assert_eq!(parent_of(&mut connection, &infra), None); +} + +#[test] +fn a_move_is_not_undone_where_its_name_is_now_taken() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let docs = folder(&mut connection, &work, None, "Docs"); + let infra = folder(&mut connection, &work, None, "Infra"); + let was = move_to(&mut connection, &infra, (&work, Some(&docs))).unwrap(); + folder(&mut connection, &work, None, "infra"); + + assert_eq!(move_back(&mut connection, &was).unwrap(), None); + assert_eq!(parent_of(&mut connection, &infra), Some(docs)); +} + +#[test] +fn moving_or_putting_back_a_folder_that_is_not_there_fails_by_name() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let gone = FolderMove { + folder_id: "missing".to_string(), + space_id: work.clone(), + parent_id: None, + frame: None, + notes: Vec::new(), + }; + + assert!(matches!( + move_to(&mut connection, "missing", (&work, None)), + Err(StorageError::FolderNotFound(id)) if id == "missing" + )); + assert!(matches!( + move_back(&mut connection, &gone), + Err(StorageError::FolderNotFound(_)) + )); +} diff --git a/crates/engine/tests/folders/store.rs b/crates/engine/tests/folders/store.rs new file mode 100644 index 000000000..84397da44 --- /dev/null +++ b/crates/engine/tests/folders/store.rs @@ -0,0 +1,662 @@ +use super::*; + +use diesel::prelude::*; +use engine::db::schema::folders; +use engine::error::StorageError; +use engine::folders::board::{BoardPoint, columns_in, zone_height}; +use engine::folders::model::{FolderColour, FolderContents, NoteFiling}; +use engine::folders::store::board::{frame_of, positions, set_frame, set_position}; +use engine::folders::store::{ + belongs_to, by_id, contents, delete, exists, file_many, lineage, move_into, recolour, rename, + restore_filings, subtree, +}; +use engine::notes::store::trash::{list_trashed, trash}; + +fn sorted(mut filings: Vec) -> Vec { + filings.sort_by(|left, right| left.note_id.cmp(&right.note_id)); + filings +} + +fn filing(note_id: &str, folder_id: Option<&str>) -> NoteFiling { + NoteFiling { + note_id: note_id.to_string(), + folder_id: folder_id.map(str::to_string), + } +} + +fn tall_enough(notes: usize, nested: bool) -> i32 { + zone_height(notes, columns_in(default_zone_width()), nested, CARD) +} + +fn height_of(connection: &mut Library, folder_id: &str) -> i32 { + frame_of(connection.db(), folder_id) + .unwrap() + .unwrap() + .height +} + +/// The order the board lays its zones out in: a rename does not reshuffle it. +#[test] +fn folders_are_listed_in_the_order_they_were_made_one_space_or_every_one() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let home = space(&mut connection, "Home"); + let zeta = create(&mut connection, &work, None, "Zeta", t1()) + .unwrap() + .id; + create(&mut connection, &work, None, "Alpha", t0()).unwrap(); + create(&mut connection, &home, None, "Garden", t0()).unwrap(); + rename(&mut connection, &zeta, "Aardvark").unwrap(); + + let mut every: Vec = list(&mut connection, None) + .unwrap() + .into_iter() + .map(|folder| folder.name) + .collect(); + every.sort(); + + assert_eq!(names(&mut connection, &work), ["Alpha", "Aardvark"]); + assert_eq!(every, ["Aardvark", "Alpha", "Garden"]); +} + +#[test] +fn a_folder_s_name_is_sealed_in_its_column() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + folder(&mut connection, &work, None, "Secret plans"); + + let stored: String = folders::table + .select(folders::name) + .first(connection.db()) + .unwrap(); + + assert!(!stored.contains("Secret")); +} + +/// A folder is worth more than its swatch. +#[test] +fn a_colour_the_column_does_not_name_reads_as_blue() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + folder(&mut connection, &work, None, "First"); + let second = folder(&mut connection, &work, None, "Second"); + diesel::update(folders::table.find(&second)) + .set(folders::colour.eq("teal")) + .execute(connection.db()) + .unwrap(); + + let read = list(&mut connection, Some(&work)).unwrap(); + + assert_eq!(read[1].colour, FolderColour::Blue); +} + +#[test] +fn an_unreadable_creation_instant_is_answered_as_a_corrupt_row() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let id = folder(&mut connection, &work, None, "Perf"); + diesel::update(folders::table.find(&id)) + .set(folders::created_at.eq("yesterday")) + .execute(connection.db()) + .unwrap(); + + assert!(matches!( + list(&mut connection, Some(&work)), + Err(StorageError::CorruptRow { id: row, field: "createdAt" }) if row == id + )); +} + +/// Counted inside the space, sub-folders included. +#[test] +fn a_new_folder_takes_the_next_colour_of_its_space() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let home = space(&mut connection, "Home"); + let mut colour = |space_id: &str, parent: Option<&str>, name: &str| { + create(&mut connection, space_id, parent, name, t0()).unwrap() + }; + + let first = colour(&work, None, "A"); + let second = colour(&work, None, "B"); + let nested = colour(&work, Some(&first.id), "C"); + let elsewhere = colour(&home, None, "A"); + + assert_eq!( + [first.colour, second.colour, nested.colour, elsewhere.colour], + [ + FolderColour::Blue, + FolderColour::Amber, + FolderColour::Purple, + FolderColour::Blue + ] + ); +} + +#[test] +fn a_folder_is_made_only_in_a_space_that_exists() { + let mut connection = open_in_memory().unwrap(); + + assert!(matches!( + create(&mut connection, "missing", None, "Perf", t0()), + Err(StorageError::SpaceNotFound(id)) if id == "missing" + )); +} + +#[test] +fn a_folder_is_made_only_under_a_folder_of_its_own_space() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let home = space(&mut connection, "Home"); + let garden = folder(&mut connection, &home, None, "Garden"); + + for parent in [garden.as_str(), "missing"] { + assert!(matches!( + create(&mut connection, &work, Some(parent), "Perf", t0()), + Err(StorageError::Invalid(refused)) if refused.field == "parentId" + )); + } + assert!(names(&mut connection, &work).is_empty()); +} + +/// Two folders may each hold a "Perf", as two spaces may. +#[test] +fn a_name_is_unique_among_its_siblings_whatever_its_case() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let home = space(&mut connection, "Home"); + let perf = folder(&mut connection, &work, None, "Perf"); + + assert!(matches!( + create(&mut connection, &work, None, "PERF", t0()), + Err(StorageError::DuplicateFolderName(name)) if name == "PERF" + )); + assert!(create(&mut connection, &work, Some(&perf), "perf", t0()).is_ok()); + assert!(create(&mut connection, &home, None, "Perf", t0()).is_ok()); +} + +#[test] +fn a_folder_renamed_keeps_the_rest_and_may_correct_its_own_case() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let parent = folder(&mut connection, &work, None, "Parent"); + let made = create(&mut connection, &work, Some(&parent), "perf", t1()).unwrap(); + + let renamed = rename(&mut connection, &made.id, "Perf").unwrap(); + + assert_eq!(renamed.name, "Perf"); + assert_eq!( + (renamed.colour, renamed.parent_id, renamed.created_at), + (made.colour, made.parent_id, made.created_at) + ); + assert_eq!(names(&mut connection, &work), ["Parent", "Perf"]); +} + +#[test] +fn a_folder_is_not_renamed_after_a_sibling_nor_when_it_is_gone() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + folder(&mut connection, &work, None, "Perf"); + let other = folder(&mut connection, &work, None, "Other"); + + assert!(matches!( + rename(&mut connection, &other, "perf"), + Err(StorageError::DuplicateFolderName(_)) + )); + assert!(matches!( + rename(&mut connection, "missing", "x"), + Err(StorageError::FolderNotFound(id)) if id == "missing" + )); +} + +#[test] +fn a_folder_recoloured_answers_its_new_colour() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let id = folder(&mut connection, &work, None, "Perf"); + + let recoloured = recolour(&mut connection, &id, FolderColour::Red).unwrap(); + + assert_eq!(recoloured.colour, FolderColour::Red); + assert_eq!( + list(&mut connection, None).unwrap()[0].colour, + FolderColour::Red + ); + assert!(matches!( + recolour(&mut connection, "missing", FolderColour::Red), + Err(StorageError::FolderNotFound(_)) + )); +} + +#[test] +fn a_folder_exists_and_belongs_only_to_its_own_space() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let home = space(&mut connection, "Home"); + let id = folder(&mut connection, &work, None, "Perf"); + let db = connection.db(); + + assert!(exists(db, &id).unwrap()); + assert!(!exists(db, "missing").unwrap()); + assert!(belongs_to(db, &id, &work).unwrap()); + assert!(!belongs_to(db, &id, &home).unwrap()); +} + +/// What a card's chip shows, its path said on hover. +#[test] +fn each_folder_is_named_with_its_colour_and_its_path_from_the_top() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let home = space(&mut connection, "Home"); + let infra = folder(&mut connection, &work, None, "Infra"); + let perf = folder(&mut connection, &work, Some(&infra), "Perf"); + folder(&mut connection, &home, None, "Garden"); + + let chips = by_id(&mut connection, Some(&work)).unwrap(); + + assert_eq!(chips.len(), 2); + let chip = &chips[&perf]; + assert_eq!( + (chip.name.as_str(), chip.colour), + ("Perf", FolderColour::Amber) + ); + assert_eq!(chip.path, ["Infra", "Perf"]); + assert_eq!(chips[&infra].path, ["Infra"]); +} + +#[test] +fn a_space_s_tree_and_a_folder_s_subtree_are_read_from_the_store() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let infra = folder(&mut connection, &work, None, "Infra"); + let perf = folder(&mut connection, &work, Some(&infra), "Perf"); + let docs = create(&mut connection, &work, None, "Docs", t1()) + .unwrap() + .id; + + let tree = lineage(connection.db(), &work).unwrap(); + + assert_eq!(tree.children(None), [infra.clone(), docs]); + assert_eq!(subtree(connection.db(), &infra).unwrap(), [infra, perf]); + assert!(matches!( + subtree(connection.db(), "missing"), + Err(StorageError::FolderNotFound(_)) + )); +} + +#[test] +fn a_folder_s_contents_are_the_live_notes_under_it_and_its_sub_folders() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let infra = folder(&mut connection, &work, None, "Infra"); + let perf = folder(&mut connection, &work, Some(&infra), "Perf"); + filed(&mut connection, &work, &infra); + filed(&mut connection, &work, &perf); + let trashed = filed(&mut connection, &work, &perf); + trash(&mut connection, &trashed, t1()).unwrap(); + note_in(&mut connection, &work); + + assert_eq!( + contents(&mut connection, &infra).unwrap(), + FolderContents { + notes: 2, + folders: 1 + } + ); + assert!(matches!( + contents(&mut connection, "missing"), + Err(StorageError::FolderNotFound(_)) + )); +} + +/// Its sub-folders keep what they hold, and let go of their place on its board. +#[test] +fn a_folder_deleted_hands_its_notes_and_its_sub_folders_to_its_parent() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let infra = folder(&mut connection, &work, None, "Infra"); + let perf = folder(&mut connection, &work, Some(&infra), "Perf"); + let deep = folder(&mut connection, &work, Some(&perf), "Deep"); + set_frame(connection.db(), &deep, flat_frame()).unwrap(); + let held = filed(&mut connection, &work, &perf); + let deeper = filed(&mut connection, &work, &deep); + + let counted = delete(&mut connection, &perf, CARD, None).unwrap(); + + assert_eq!(counted, 2); + let mut left = names(&mut connection, &work); + left.sort(); + assert_eq!(left, ["Deep", "Infra"]); + assert_eq!(parent_of(&mut connection, &deep), Some(infra.clone())); + assert_eq!(frame_of(connection.db(), &deep).unwrap(), None); + assert_eq!( + place_of(&mut connection, &held), + (work.clone(), Some(infra)) + ); + assert_eq!(place_of(&mut connection, &deeper), (work, Some(deep))); +} + +/// The user aimed at the folder, not at its notes. +#[test] +fn a_folder_deleted_at_the_top_leaves_its_notes_loose_undated_and_its_sub_folders_at_the_top() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let perf = folder(&mut connection, &work, None, "Perf"); + let below = folder(&mut connection, &work, Some(&perf), "Below"); + let id = filed(&mut connection, &work, &perf); + + delete(&mut connection, &perf, CARD, None).unwrap(); + + let note = get(&mut connection, &id).unwrap(); + assert_eq!((note.folder_id, note.updated_at), (None, t0())); + assert_eq!(parent_of(&mut connection, &below), None); +} + +/// A place on the deleted folder's board means nothing on its parent's. +#[test] +fn a_folder_deleted_forgets_where_its_notes_sat() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let perf = folder(&mut connection, &work, None, "Perf"); + let id = filed(&mut connection, &work, &perf); + set_position(connection.db(), &id, BoardPoint { x: 40, y: 40 }).unwrap(); + + delete(&mut connection, &perf, CARD, None).unwrap(); + + assert!(!positions(connection.db(), &work).unwrap().contains_key(&id)); +} + +/// They come back loose: the folder they were in is gone. +#[test] +fn a_folder_deleted_with_its_notes_trashes_everything_under_it() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let infra = folder(&mut connection, &work, None, "Infra"); + let perf = folder(&mut connection, &work, Some(&infra), "Perf"); + filed(&mut connection, &work, &infra); + filed(&mut connection, &work, &perf); + let loose = note_in(&mut connection, &work).id; + + let counted = delete(&mut connection, &infra, CARD, Some(t1())).unwrap(); + + assert_eq!(counted, 2); + assert!(names(&mut connection, &work).is_empty()); + let trashed = list_trashed(&mut connection).unwrap(); + assert_eq!(trashed.len(), 2); + assert!( + trashed + .iter() + .all(|(note, at)| note.folder_id.is_none() && *at == t1()) + ); + assert!(get(&mut connection, &loose).is_ok()); +} + +#[test] +fn a_note_already_in_the_trash_keeps_its_date_when_its_folder_goes() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let perf = folder(&mut connection, &work, None, "Perf"); + let earlier = filed(&mut connection, &work, &perf); + trash(&mut connection, &earlier, t0()).unwrap(); + + let counted = delete(&mut connection, &perf, CARD, Some(t1())).unwrap(); + + assert_eq!(counted, 0); + assert_eq!(list_trashed(&mut connection).unwrap()[0].1, t0()); +} + +#[test] +fn deleting_a_folder_that_is_not_there_fails_by_name() { + let mut connection = open_in_memory().unwrap(); + + assert!(matches!( + delete(&mut connection, "missing", CARD, None), + Err(StorageError::FolderNotFound(id)) if id == "missing" + )); +} + +/// The parent now shows the notes, and so does every zone above it. +#[test] +fn a_deletion_opens_the_zones_that_now_show_its_notes_tall_enough() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let top = folder(&mut connection, &work, None, "Top"); + let middle = folder(&mut connection, &work, Some(&top), "Middle"); + let doomed = folder(&mut connection, &work, Some(&middle), "Doomed"); + for zone in [&top, &middle] { + set_frame(connection.db(), zone, flat_frame()).unwrap(); + } + for _ in 0..3 { + filed(&mut connection, &work, &doomed); + } + + delete(&mut connection, &doomed, CARD, None).unwrap(); + + assert_eq!(height_of(&mut connection, &top), tall_enough(3, true)); + assert_eq!(height_of(&mut connection, &middle), tall_enough(3, false)); +} + +#[test] +fn filing_answers_where_each_note_was_and_leaves_out_one_already_there() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let infra = folder(&mut connection, &work, None, "Infra"); + let docs = folder(&mut connection, &work, None, "Docs"); + let loose = note_in(&mut connection, &work).id; + let in_docs = filed(&mut connection, &work, &docs); + let there = filed(&mut connection, &work, &infra); + let ids = [loose.clone(), in_docs.clone(), there.clone()]; + + let filings = file_many(&mut connection, &ids, Some(&infra), CARD).unwrap(); + + assert_eq!( + sorted(filings), + sorted(vec![filing(&loose, None), filing(&in_docs, Some(&docs))]) + ); + for id in &ids { + assert_eq!( + place_of(&mut connection, id).1.as_deref(), + Some(infra.as_str()) + ); + } +} + +#[test] +fn filing_into_no_folder_takes_notes_out_of_theirs() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let infra = folder(&mut connection, &work, None, "Infra"); + let id = filed(&mut connection, &work, &infra); + + let filings = file_many(&mut connection, std::slice::from_ref(&id), None, CARD).unwrap(); + + assert_eq!(filings, [filing(&id, Some(&infra))]); + assert_eq!(place_of(&mut connection, &id).1, None); +} + +/// A chip of another space would point where the switcher cannot reach. +#[test] +fn only_live_notes_of_the_folder_s_own_space_are_filed() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let home = space(&mut connection, "Home"); + let infra = folder(&mut connection, &work, None, "Infra"); + let elsewhere = note_in(&mut connection, &home).id; + let trashed = note_in(&mut connection, &work).id; + trash(&mut connection, &trashed, t1()).unwrap(); + + let ids = [elsewhere.clone(), trashed]; + let filings = file_many(&mut connection, &ids, Some(&infra), CARD).unwrap(); + + assert!(filings.is_empty()); + assert_eq!(place_of(&mut connection, &elsewhere), (home, None)); + assert_eq!(list_trashed(&mut connection).unwrap()[0].0.folder_id, None); +} + +#[test] +fn filing_into_a_folder_that_is_not_there_fails_by_name_unless_nothing_is_filed() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let id = note_in(&mut connection, &work).id; + + assert!(matches!( + file_many(&mut connection, &[id], Some("missing"), CARD), + Err(StorageError::FolderNotFound(_)) + )); + assert_eq!( + file_many(&mut connection, &[], Some("missing"), CARD).unwrap(), + [] + ); +} + +/// A filed card flows in its zone: the place it had loose is let go. +#[test] +fn filing_forgets_where_a_note_sat_and_leaves_its_instant_alone() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let infra = folder(&mut connection, &work, None, "Infra"); + let id = note_in(&mut connection, &work).id; + set_position(connection.db(), &id, BoardPoint { x: 40, y: 40 }).unwrap(); + + file_many( + &mut connection, + std::slice::from_ref(&id), + Some(&infra), + CARD, + ) + .unwrap(); + + assert!(!positions(connection.db(), &work).unwrap().contains_key(&id)); + assert_eq!(get(&mut connection, &id).unwrap().updated_at, t0()); +} + +/// The gesture that filled the zone is the one that makes room in it. +#[test] +fn filing_opens_the_folder_s_zone_and_its_ancestors_tall_enough() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let infra = folder(&mut connection, &work, None, "Infra"); + let perf = folder(&mut connection, &work, Some(&infra), "Perf"); + for zone in [&infra, &perf] { + set_frame(connection.db(), zone, flat_frame()).unwrap(); + } + let ids: Vec = (0..3).map(|_| note_in(&mut connection, &work).id).collect(); + + file_many(&mut connection, &ids, Some(&perf), CARD).unwrap(); + + assert_eq!(height_of(&mut connection, &perf), tall_enough(3, false)); + assert_eq!(height_of(&mut connection, &infra), tall_enough(3, true)); +} + +/// From any space: a move is not a filing. +#[test] +fn notes_moved_into_a_folder_join_its_space_and_answer_where_they_were() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let home = space(&mut connection, "Home"); + let garden = folder(&mut connection, &home, None, "Garden"); + let infra = folder(&mut connection, &work, None, "Infra"); + let loose = note_in(&mut connection, &work).id; + let in_infra = filed(&mut connection, &work, &infra); + let there = filed(&mut connection, &home, &garden); + let trashed = note_in(&mut connection, &work).id; + trash(&mut connection, &trashed, t1()).unwrap(); + let ids = [loose.clone(), in_infra.clone(), there, trashed]; + + let mut moved = move_into(&mut connection, &ids, &garden, CARD).unwrap(); + moved.sort_by(|left, right| left.note_id.cmp(&right.note_id)); + + let was: Vec<(&str, &str, Option<&str>)> = moved + .iter() + .map(|one| { + ( + one.note_id.as_str(), + one.space_id.as_str(), + one.folder_id.as_deref(), + ) + }) + .collect(); + let mut expected = vec![ + (loose.as_str(), work.as_str(), None), + (in_infra.as_str(), work.as_str(), Some(infra.as_str())), + ]; + expected.sort_unstable(); + assert_eq!(was, expected); + for id in [&loose, &in_infra] { + assert_eq!( + place_of(&mut connection, id), + (home.clone(), Some(garden.clone())) + ); + } + assert_eq!(list_trashed(&mut connection).unwrap()[0].0.space_id, work); +} + +#[test] +fn moving_into_a_folder_that_is_not_there_fails_by_name_unless_nothing_moves() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let id = note_in(&mut connection, &work).id; + + assert!(matches!( + move_into(&mut connection, &[id], "missing", CARD), + Err(StorageError::FolderNotFound(_)) + )); + assert!( + move_into(&mut connection, &[], "missing", CARD) + .unwrap() + .is_empty() + ); +} + +/// Undoing is not editing: the instant stays. +#[test] +fn a_filing_undone_puts_each_note_back_where_it_was() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let infra = folder(&mut connection, &work, None, "Infra"); + let docs = folder(&mut connection, &work, None, "Docs"); + let loose = note_in(&mut connection, &work).id; + let in_docs = filed(&mut connection, &work, &docs); + let ids = [loose.clone(), in_docs.clone()]; + let filings = file_many(&mut connection, &ids, Some(&infra), CARD).unwrap(); + + let restored = restore_filings(&mut connection, &filings, CARD).unwrap(); + + assert_eq!(restored, 2); + assert_eq!(place_of(&mut connection, &loose).1, None); + assert_eq!(place_of(&mut connection, &in_docs).1, Some(docs)); + assert_eq!(get(&mut connection, &in_docs).unwrap().updated_at, t0()); +} + +/// A note trashed since is left in the trash, out of any folder. +#[test] +fn an_undo_leaves_a_note_trashed_since_where_it_is() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let infra = folder(&mut connection, &work, None, "Infra"); + let trashed = note_in(&mut connection, &work).id; + trash(&mut connection, &trashed, t1()).unwrap(); + + let filings = [filing(&trashed, Some(&infra))]; + let restored = restore_filings(&mut connection, &filings, CARD).unwrap(); + + assert_eq!(restored, 0); + assert_eq!(list_trashed(&mut connection).unwrap()[0].0.folder_id, None); + assert_eq!(restore_filings(&mut connection, &[], CARD).unwrap(), 0); +} + +/// Putting notes back may fill a zone past its height. +#[test] +fn an_undo_opens_the_zones_it_files_back_into_tall_enough() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let infra = folder(&mut connection, &work, None, "Infra"); + let ids: Vec = (0..3) + .map(|_| filed(&mut connection, &work, &infra)) + .collect(); + let filings = file_many(&mut connection, &ids, None, CARD).unwrap(); + set_frame(connection.db(), &infra, flat_frame()).unwrap(); + + restore_filings(&mut connection, &filings, CARD).unwrap(); + + assert_eq!(height_of(&mut connection, &infra), tall_enough(3, false)); +} From c53afe5c5f4937fbc861f79d7cfdfd58993c1520 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 07:23:07 +0100 Subject: [PATCH 21/95] Folders: undoing a filing skips a folder deleted since (#1743) Co-authored-by: Claude Opus 5.5 --- crates/engine/src/folders/store.rs | 6 +++++- crates/engine/tests/folders/store.rs | 21 +++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/folders/store.rs b/crates/engine/src/folders/store.rs index d3781c8a3..d86e3e0ec 100644 --- a/crates/engine/src/folders/store.rs +++ b/crates/engine/src/folders/store.rs @@ -663,12 +663,16 @@ pub fn restore_filings( .execute(connection)?; } - // Undoing puts notes back into zones that may no longer be tall enough for them. + // Undoing puts notes back into zones that may no longer be tall enough for them; a + // folder gone since has no zone left to grow. for folder_id in filings .iter() .filter_map(|filing| filing.folder_id.as_deref()) .collect::>() { + if !exists(connection, folder_id)? { + continue; + } let lineage = lineage_of(connection, folder_id)?; grow_with_ancestors(connection, &lineage, folder_id, card)?; } diff --git a/crates/engine/tests/folders/store.rs b/crates/engine/tests/folders/store.rs index 84397da44..0eb69fdaf 100644 --- a/crates/engine/tests/folders/store.rs +++ b/crates/engine/tests/folders/store.rs @@ -627,6 +627,27 @@ fn a_filing_undone_puts_each_note_back_where_it_was() { assert_eq!(get(&mut connection, &in_docs).unwrap().updated_at, t0()); } +/// A folder deleted since is not an error: the other notes go back, that one stays where it is. +#[test] +fn an_undo_leaves_a_note_whose_folder_went_since_where_it_is() { + let mut connection = open_in_memory().unwrap(); + let work = space(&mut connection, "Work"); + let infra = folder(&mut connection, &work, None, "Infra"); + let gone = folder(&mut connection, &work, None, "Gone"); + let docs = folder(&mut connection, &work, None, "Docs"); + let from_gone = filed(&mut connection, &work, &gone); + let from_docs = filed(&mut connection, &work, &docs); + let ids = [from_gone.clone(), from_docs.clone()]; + let filings = file_many(&mut connection, &ids, Some(&infra), CARD).unwrap(); + delete(&mut connection, &gone, CARD, None).unwrap(); + + let restored = restore_filings(&mut connection, &filings, CARD).unwrap(); + + assert_eq!(restored, 1); + assert_eq!(place_of(&mut connection, &from_gone).1, Some(infra)); + assert_eq!(place_of(&mut connection, &from_docs).1, Some(docs)); +} + /// A note trashed since is left in the trash, out of any folder. #[test] fn an_undo_leaves_a_note_trashed_since_where_it_is() { From 997fdf7ddc8a6cbd1fe3227396301fc34e011ea8 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 07:29:01 +0100 Subject: [PATCH 22/95] Folders: unit tests rewritten for the board and its geometry (#1744) * Rewrite the tests of the folders' board and its geometry around their rules Co-Authored-By: Claude Opus 5.5 * Trash enough notes for their room to show Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/folders/board.rs | 830 ++++++++++------- crates/engine/tests/folders/board.rs | 922 +++++++------------ crates/engine/tests/folders/gesture.rs | 458 --------- crates/engine/tests/folders/main.rs | 6 +- crates/engine/tests/folders/nested_boards.rs | 179 ---- 5 files changed, 809 insertions(+), 1586 deletions(-) delete mode 100644 crates/engine/tests/folders/gesture.rs delete mode 100644 crates/engine/tests/folders/nested_boards.rs diff --git a/crates/engine/src/folders/board.rs b/crates/engine/src/folders/board.rs index 496611ab9..17895f9b2 100644 --- a/crates/engine/src/folders/board.rs +++ b/crates/engine/src/folders/board.rs @@ -730,322 +730,308 @@ fn flowed(loose_ids: &[String], top: i32, card: i32) -> Vec { #[cfg(test)] mod tests { use super::*; + use crate::folders::model::NoteFolder; use crate::notes::fixtures::{NOW, at, note}; + use crate::notes::view::FacetCount; - /// The default card, four lines. const CARD: i32 = 140; - fn notes(count: usize) -> ZoneContents { - ZoneContents { - notes: count, - nested: false, + fn folder(id: &str, parent: Option<&str>, name: &str) -> Folder { + Folder { + id: id.to_string(), + space_id: "s-1".to_string(), + name: name.to_string(), + colour: FolderColour::Blue, + created_at: at(NOW), + parent_id: parent.map(str::to_string), } } - fn holding(counts: &[usize]) -> Vec { - counts.iter().copied().map(notes).collect() + fn filed(id: &str, folder_id: Option<&str>) -> Note { + Note { + id: id.to_string(), + folder_id: folder_id.map(str::to_string), + ..note() + } } - /// Everything but the space and the instant is neutral: the board dims, it never narrows. - #[test] - fn the_board_reads_the_whole_space_whatever_it_is_asked() { - let request = BoardQuery { + fn request(root: Option<&str>) -> BoardQuery { + BoardQuery { space_id: "s-1".to_string(), - root_id: Some("f-1".to_string()), - search: "deploy".to_string(), - filter: NoteFilter::Pinned, - tags: vec!["ops".to_string()], - languages: vec![Language::Sql], - kinds: vec![NoteKind::Note], + root_id: root.map(str::to_string), + search: String::new(), + filter: NoteFilter::All, + tags: Vec::new(), + languages: Vec::new(), + kinds: Vec::new(), priorities: Vec::new(), now: at(NOW), tz_offset_minutes: 0, - preview_lines: PreviewLines::default(), - }; - - let wide = request.whole_space(); - - assert_eq!(wide.space_id.as_deref(), Some("s-1")); - assert!(wide.search.is_empty() && wide.tags.is_empty() && wide.languages.is_empty()); - assert!(wide.kinds.is_empty() && wide.priorities.is_empty()); - assert_eq!(wide.filter, NoteFilter::All); - assert_eq!(wide.now, at(NOW)); + preview_lines: PreviewLines::Four, + } } - #[test] - fn every_card_of_a_board_is_reached_once_zones_first() { - let card = |id: &str| BoardNote { - note: model::decorate( - Note { - id: id.to_string(), - ..note() - }, - at(NOW), - ), - matches: true, - position: None, - }; - let mut view = BoardView { - zones: vec![BoardZone { - folder: Folder { - id: "f-1".to_string(), - space_id: "s-1".to_string(), - name: "Ops".to_string(), - colour: super::super::model::FolderColour::nth(0), - created_at: at(NOW), - parent_id: None, - }, - frame: BoardFrame { - x: 0, - y: 0, - width: 400, - height: 300, - }, - notes: vec![card("filed")], - children: Vec::new(), - }], - loose: vec![card("loose")], - available_tags: Vec::new(), - available_languages: Vec::new(), - is_filtering: false, - matched: 2, - width: 0, - height: 0, - }; - - let ids: Vec = view.notes_mut().map(|note| note.id.clone()).collect(); - - assert_eq!(ids, ["filed", "loose"]); + /// Infra ─ Perf, and Docs beside it. + fn folders() -> Vec { + vec![ + folder("infra", None, "Infra"), + folder("perf", Some("infra"), "Perf"), + folder("docs", None, "Docs"), + ] } - #[test] - fn the_occupancy_counts_each_folder_and_lists_the_loose_notes() { - let filed = |id: &str, folder: Option<&str>| Note { - id: id.to_string(), - folder_id: folder.map(str::to_string), - ..note() - }; - - let notes = [ - filed("a", Some("f-1")), - filed("b", Some("f-1")), - filed("c", None), - filed("d", Some("f-2")), - filed("e", Some("f-1a")), - ]; - let lineage = Lineage::new([ - ("f-1".to_string(), None), - ("f-2".to_string(), None), - ("f-1a".to_string(), Some("f-1".to_string())), - ]); - - let space = Occupancy::on(¬es, &lineage, None); - assert_eq!(space.per_folder.get("f-1"), Some(&3)); - assert_eq!(space.per_folder.get("f-2"), Some(&1)); - assert_eq!(space.loose, ["c"]); - - let inside = Occupancy::on(¬es, &lineage, Some("f-1")); - assert_eq!(inside.per_folder.get("f-1a"), Some(&1)); - assert_eq!(inside.loose, ["a", "b"]); - assert!(!inside.per_folder.contains_key("f-2")); + fn board( + notes: Vec, + positions: &HashMap, + query: &BoardQuery, + ) -> BoardView { + build( + notes, + &folders(), + &HashMap::new(), + positions, + &Facets::default(), + query, + ) } - /// Two cards and room for the scrollbar: at exactly the inner width the second card wraps. - #[test] - fn a_zone_is_two_cards_wide_with_room_for_the_scrollbar() { - assert_eq!(default_zone_width(), 12 + 240 + 12 + 240 + 12 + SCROLLBAR); - assert!(default_zone_width() - ZONE_PADDING * 2 > ZONE_COLUMNS * CARD_WIDTH + GAP); + fn ids(notes: &[BoardNote]) -> Vec<&str> { + notes.iter().map(|entry| entry.note.id.as_str()).collect() } - #[test] - fn a_zone_grows_a_row_at_a_time() { - let one_row = default_zone_height(2, false, CARD); - let two_rows = default_zone_height(3, false, CARD); - - assert_eq!(two_rows - one_row, CARD + GAP); - assert_eq!(default_zone_height(4, false, CARD), two_rows); + fn frame(x: i32, y: i32, width: i32, height: i32) -> BoardFrame { + BoardFrame { + x, + y, + width, + height, + } } - /// One pixel short of two rows brings a vertical scrollbar that wraps the second card. - #[test] - fn a_zone_is_tall_enough_for_its_rows_once_its_own_hairlines_are_paid_for() { - let body = zone_height(3, 2, false, CARD) - ZONE_BORDER * 2 - ZONE_HEADER; - - assert!( - body >= ZONE_PADDING * 2 + CARD * 2 + GAP, - "{body}px of body for two rows that need {}", - ZONE_PADDING * 2 + CARD * 2 + GAP - ); + fn point(x: i32, y: i32) -> BoardPoint { + BoardPoint { x, y } } - /// `border-box`, and no scrollbar once the zone is tall enough: two cards still flow across. #[test] - fn a_zone_shaved_narrower_than_nominal_still_fits_two_across() { - let shaved = default_zone_width() - 14; + fn a_card_is_as_tall_as_the_lines_it_shows() { + let cases = [ + (PreviewLines::Three, 3, 120), + (PreviewLines::Four, 4, 140), + (PreviewLines::Five, 5, 160), + ]; - assert_eq!(columns_in(shaved), 2); - assert_eq!( - zone_height(3, columns_in(shaved), false, CARD), - zone_height(3, ZONE_COLUMNS, false, CARD) - ); + for (lines, count, height) in cases { + assert_eq!((lines.count(), lines.card_height()), (count, height)); + } + assert_eq!(PreviewLines::default(), PreviewLines::Four); } - /// The narrowest width that still flows two, and the widest that does not. + /// The board dims rather than narrows: what it reads is the whole space. #[test] - fn the_count_turns_over_where_the_flow_does() { - let two = ZONE_BORDER * 2 + ZONE_PADDING * 2 + CARD_WIDTH * 2 + GAP; + fn a_board_reads_its_whole_space_whatever_it_is_asked_to_dim() { + let query = BoardQuery { + search: "pg".to_string(), + filter: NoteFilter::Pinned, + tags: vec!["sql".to_string()], + tz_offset_minutes: -120, + ..request(Some("infra")) + }; + + let read = query.whole_space(); - assert_eq!(columns_in(two), 2); - assert_eq!(columns_in(two - 1), 1); + assert_eq!(read.space_id.as_deref(), Some("s-1")); + assert_eq!((read.folder_id, read.search.as_str()), (None, "")); + assert_eq!(read.filter, NoteFilter::All); + assert!(read.tags.is_empty()); + assert_eq!((read.now, read.tz_offset_minutes), (at(NOW), -120)); } - /// A zone widened by hand fits more across, and needs fewer rows. #[test] - fn a_wider_zone_needs_fewer_rows_for_the_same_notes() { - let nominal = default_zone_width(); - let wider = nominal + CARD_WIDTH + GAP; + fn a_board_counts_each_zone_s_notes_and_lists_the_free_ones() { + let lineage = Lineage::of(&folders()); + let notes = [ + filed("in-infra", Some("infra")), + filed("in-perf", Some("perf")), + filed("in-docs", Some("docs")), + filed("loose", None), + ]; - assert_eq!(columns_in(nominal), ZONE_COLUMNS); - assert_eq!(columns_in(wider), ZONE_COLUMNS + 1); - assert!( - zone_height(6, columns_in(wider), false, CARD) - < zone_height(6, columns_in(nominal), false, CARD) + let space = Occupancy::on(¬es, &lineage, None); + let infra = Occupancy::on(¬es, &lineage, Some("infra")); + + assert_eq!( + space.per_folder, + HashMap::from([("infra".to_string(), 2), ("docs".to_string(), 1)]) ); + assert_eq!(space.loose, ["loose"]); + assert_eq!(infra.per_folder, HashMap::from([("perf".to_string(), 1)])); + assert_eq!(infra.loose, ["in-infra"]); } - /// Below one card across, the flow still has to have a column. + /// Clamped rather than refused: an error mid-gesture would leave the screen holding a frame + /// the library refused. #[test] - fn a_zone_squashed_narrow_still_counts_one_column() { - assert_eq!(columns_in(0), 1); - assert_eq!(columns_in(MIN_ZONE_WIDTH), 1); - } + fn a_frame_is_kept_on_the_board_and_big_enough_to_drop_a_card_into() { + let cases = [ + ( + frame(-5, -1, 10, 10), + frame(0, 0, MIN_ZONE_WIDTH, MIN_ZONE_HEIGHT), + ), + (frame(40, 60, 600, 400), frame(40, 60, 600, 400)), + ( + frame(0, 0, i32::MAX, i32::MAX), + frame(0, 0, MAX_SIDE, MAX_SIDE), + ), + ]; - /// A zone with nothing in it is still a target to drop a card into. - #[test] - fn an_empty_zone_is_still_a_row_tall() { - assert_eq!( - default_zone_height(0, false, CARD), - default_zone_height(1, false, CARD) - ); + for (asked, kept) in cases { + assert_eq!(clamp(asked), kept, "{asked:?}"); + } + assert_eq!(clamp_point(point(-3, i32::MAX)), point(0, MAX_SIDE)); } + /// A zone drawn on top of another wins the point they share; the right and bottom edges + /// belong to the ground. #[test] - fn zones_are_laid_out_in_reading_order() { - let frames = arrange_zones(&holding(&[1, 1, 1]), CARD); + fn a_point_falls_in_the_topmost_zone_that_holds_it() { + let frames = [ + ("under".to_string(), frame(0, 0, 100, 100)), + ("over".to_string(), frame(50, 50, 100, 100)), + ]; + let cases = [ + (point(10, 10), Some("under")), + (point(60, 60), Some("over")), + (point(0, 0), Some("under")), + (point(150, 60), None), + (point(10, 100), None), + ]; - assert_eq!(frames[0].y, frames[1].y); - assert!(frames[0].x < frames[1].x); - assert!(frames[1].x < frames[2].x); + for (at, zone) in cases { + assert_eq!(zone_at(&frames, at).as_deref(), zone, "{at:?}"); + } } + /// Counted the way the zone's body lays them: hairlines and padding off, the scrollbar's + /// allowance kept, so the count turns over exactly where the flow does. #[test] - fn the_layout_wraps_after_three_zones() { - let frames = arrange_zones(&holding(&[1, 1, 1, 1]), CARD); + fn a_first_zone_holds_two_cards_across_and_a_narrow_one_at_least_one() { + let two = ZONE_BORDER * 2 + ZONE_PADDING * 2 + CARD_WIDTH * 2 + GAP; - assert_eq!(frames[3].x, frames[0].x); - assert!(frames[3].y > frames[0].y); + assert_eq!(columns_in(default_zone_width()), ZONE_COLUMNS); + assert_eq!((columns_in(two), columns_in(two - 1)), (2, 1)); + assert_eq!(columns_in(MIN_ZONE_WIDTH), 1); + assert_eq!(columns_in(0), 1); } - /// A row advances by its tallest zone, or the next row lands on top of it. + /// One pixel short, the body shows a scrollbar that wraps the second card. #[test] - fn a_wrapped_row_clears_the_tallest_zone_above_it() { - let frames = arrange_zones(&holding(&[1, 9, 1, 1]), CARD); + fn a_zone_s_body_is_its_rows_once_its_hairlines_and_header_are_paid_for() { + let body = zone_height(3, 2, false, CARD) - ZONE_BORDER * 2 - ZONE_HEADER; - let tallest = frames[..3].iter().map(|f| f.y + f.height).max().unwrap(); - assert!(frames[3].y >= tallest); + assert_eq!(body, ZONE_PADDING * 2 + CARD * 2 + GAP); } #[test] - fn the_layout_is_the_same_every_time() { + fn a_zone_is_tall_enough_for_its_rows_of_cards_and_never_less_than_one() { + let height = + |notes: usize, columns: i32, nested: bool| zone_height(notes, columns, nested, CARD); + + assert_eq!(height(0, 2, false), height(1, 2, false)); + assert_eq!(height(2, 2, false), height(1, 2, false)); + assert_eq!(height(3, 2, false) - height(2, 2, false), CARD + GAP); + assert_eq!(height(2, 0, false), height(2, 1, false)); + assert_eq!(height(1, 2, true) - height(1, 2, false), ZONE_SUBFOLDERS); + assert_eq!(zone_height(1, 1, false, MIN_CARD_HEIGHT), MIN_ZONE_HEIGHT); assert_eq!( - arrange_zones(&holding(&[3, 1, 7]), CARD), - arrange_zones(&holding(&[3, 1, 7]), CARD) + default_zone_height(3, true, CARD), + height(3, ZONE_COLUMNS, true) ); } + /// Three across in the order handed over; a row starts under the tallest of the one above. #[test] - fn loose_cards_flow_under_the_zones_with_room_for_their_label() { - let frames = arrange_zones(&holding(&[1]), CARD); - let top = loose_top(&frames); + fn zones_are_laid_out_in_reading_order_three_across() { + let contents = [5, 0, 0, 0].map(|notes| ZoneContents { + notes, + nested: false, + }); + let width = default_zone_width(); - assert!(top > frames[0].y + frames[0].height); + let frames = arrange_zones(&contents, CARD); - let points = arrange_loose(5, top, CARD); + let corners: Vec<(i32, i32)> = frames.iter().map(|frame| (frame.x, frame.y)).collect(); + let second_row = BOARD_MARGIN + default_zone_height(5, false, CARD) + GAP; assert_eq!( - points[0], - BoardPoint { - x: BOARD_MARGIN, - y: top - } + corners, + [ + (BOARD_MARGIN, BOARD_MARGIN), + (BOARD_MARGIN + width + GAP, BOARD_MARGIN), + (BOARD_MARGIN + 2 * (width + GAP), BOARD_MARGIN), + (BOARD_MARGIN, second_row), + ] ); - assert_eq!(points[3].y, top); - assert_eq!(points[4].x, BOARD_MARGIN); - assert_eq!(points[4].y, top + CARD + GAP); + assert!(frames.iter().all(|frame| frame.width == width)); + assert_eq!(frames[1].height, default_zone_height(0, false, CARD)); } #[test] - fn an_empty_board_still_puts_its_loose_cards_somewhere() { + fn loose_cards_flow_four_across_clear_of_the_lowest_zone() { assert_eq!(loose_top(&[]), BOARD_MARGIN); - } + let top = loose_top(&[frame(0, 0, 10, 300), frame(0, 100, 10, 50)]); + assert_eq!(top, 300 + 2 * GAP); - /// A new note must not land under a card that is already there. - #[test] - fn a_card_with_no_place_never_takes_one_that_is_occupied() { - let top = loose_top(&[]); - let first = slot(0, top, CARD); + let seats = arrange_loose(5, top, CARD); - assert_eq!(free_slot(top, &[], &[], CARD), first); - assert_eq!(free_slot(top, &[first], &[], CARD), slot(1, top, CARD)); + assert_eq!(seats[0], point(BOARD_MARGIN, top)); + assert_eq!(seats[3], point(BOARD_MARGIN + 3 * (CARD_WIDTH + GAP), top)); + assert_eq!(seats[4], point(BOARD_MARGIN, top + CARD + GAP)); } - /// A card dragged by hand hides the seats it straddles. + /// Not the seat of its index: a new note would land on whichever card sits on seat 0. #[test] - fn a_seat_half_covered_is_a_seat_taken() { - let top = loose_top(&[]); - let nudged = BoardPoint { - x: BOARD_MARGIN + 20, - y: top + 20, - }; - - let at = free_slot(top, &[nudged], &[], CARD); + fn a_card_never_placed_takes_the_first_seat_nothing_stands_on() { + let seats = arrange_loose(4, 100, CARD); + let half_way = point(seats[1].x + CARD_WIDTH / 2, seats[1].y); + let cases = [ + (vec![], vec![], seats[0]), + (vec![seats[0]], vec![], seats[1]), + (vec![half_way], vec![], seats[0]), + (vec![seats[0], half_way], vec![], seats[3]), + (vec![seats[0], seats[2]], vec![], seats[1]), + (vec![], vec![frame(0, 100, 2 * CARD_WIDTH, CARD)], seats[2]), + ]; - assert!(!overlaps(at, CARD, card_frame(nudged, CARD))); - assert_eq!(at, slot(2, top, CARD)); + for (taken, zones, seat) in cases { + assert_eq!( + free_slot(100, &taken, &zones, CARD), + seat, + "{taken:?} {zones:?}" + ); + } } #[test] - fn a_zone_standing_on_a_seat_takes_it_too() { - let top = loose_top(&[]); - let over = BoardFrame { - x: BOARD_MARGIN, - y: top, - width: CARD_WIDTH, - height: CARD, - }; + fn a_card_with_no_seat_left_goes_under_everything() { + let zone = frame(0, 0, 10_000, 5_000); assert_eq!( - free_slot(top, &[], std::slice::from_ref(&over), CARD), - slot(1, top, CARD) + free_slot(100, &[], &[zone], CARD), + point(BOARD_MARGIN, 5_000 + GAP) ); } + /// The run starts each search where the last stopped, and gives the seats one by one would. #[test] fn seats_given_in_a_run_are_the_ones_given_one_by_one() { - let top = 100; - let wall = BoardFrame { - x: slot(2, top, CARD).x, - y: slot(2, top, CARD).y, - width: CARD_WIDTH, - height: CARD, - }; - let zones = [wall]; - let mut one_by_one = vec![slot(5, top, CARD)]; + let seats = arrange_loose(6, 100, CARD); + let wall = [frame(seats[2].x, seats[2].y, CARD_WIDTH, CARD)]; + let mut one_by_one = vec![seats[5]]; let mut run = one_by_one.clone(); let mut seat = 0; for _ in 0..40 { - one_by_one.push(free_slot(top, &one_by_one, &zones, CARD)); - let (reached, at) = free_slot_from(seat, top, (&run, &zones), CARD); + one_by_one.push(free_slot(100, &one_by_one, &wall, CARD)); + let (reached, at) = free_slot_from(seat, 100, (&run, &wall), CARD); seat = reached; run.push(at); } @@ -1054,153 +1040,333 @@ mod tests { } #[test] - fn a_seat_freed_in_the_middle_is_the_next_one_given() { - let top = loose_top(&[]); - let taken = [slot(0, top, CARD), slot(2, top, CARD)]; + fn the_surface_reaches_past_the_furthest_zone_or_card_and_is_never_less_than_a_screen() { + let zone = BoardZone { + folder: folder("infra", None, "Infra"), + frame: frame(1_000, 0, 500, 100), + notes: Vec::new(), + children: Vec::new(), + }; + let card = BoardNote { + note: model::decorate(note(), at(NOW)), + matches: true, + position: Some(point(0, 600)), + }; - assert_eq!(free_slot(top, &taken, &[], CARD), slot(1, top, CARD)); + assert_eq!( + surface(&[], &[], CARD), + (960 + BOARD_MARGIN, 540 + BOARD_MARGIN) + ); + assert_eq!( + surface(&[zone], &[card], CARD), + (1_500 + BOARD_MARGIN, 600 + CARD + BOARD_MARGIN) + ); } #[test] - fn a_card_with_nowhere_to_sit_goes_below_everything() { - let top = loose_top(&[]); - let wall = BoardFrame { - x: 0, - y: top, - width: MAX_SIDE, - height: MAX_SIDE, - }; + fn the_space_s_board_draws_its_top_folders_each_gathering_what_is_under_it() { + let notes = vec![ + filed("in-infra", Some("infra")), + filed("in-perf", Some("perf")), + filed("loose", None), + ]; - let at = free_slot(top, &[], std::slice::from_ref(&wall), CARD); + let view = board(notes, &HashMap::new(), &request(None)); - assert_eq!(at.x, BOARD_MARGIN); - assert!(at.y >= wall.y + wall.height); + let zones: Vec<(&str, Vec<&str>)> = view + .zones + .iter() + .map(|zone| (zone.folder.id.as_str(), ids(&zone.notes))) + .collect(); + assert_eq!( + zones, + [("infra", vec!["in-infra", "in-perf"]), ("docs", vec![])] + ); + assert_eq!(ids(&view.loose), ["loose"]); + assert!( + view.zones[0] + .notes + .iter() + .all(|entry| entry.position.is_none()) + ); } + /// Nothing from outside it: a note of a sibling folder, or loose in the space, is not drawn. #[test] - fn the_surface_covers_the_furthest_zone() { - let zone = BoardZone { - folder: crate::folders::model::Folder { - id: "f-1".to_string(), - space_id: "s-1".to_string(), - name: "Perf".to_string(), - colour: crate::folders::model::FolderColour::Blue, - created_at: Utc::now(), - parent_id: None, - }, - frame: BoardFrame { - x: 2000, - y: 1500, - width: 300, - height: 200, - }, - notes: Vec::new(), - children: Vec::new(), - }; + fn a_folder_s_board_draws_its_sub_folders_and_its_own_notes_free_on_its_ground() { + let notes = vec![ + filed("in-infra", Some("infra")), + filed("in-perf", Some("perf")), + filed("in-docs", Some("docs")), + filed("loose", None), + ]; - let (width, height) = surface(std::slice::from_ref(&zone), &[], CARD); + let view = board(notes, &HashMap::new(), &request(Some("infra"))); - assert_eq!(width, 2300 + BOARD_MARGIN); - assert_eq!(height, 1700 + BOARD_MARGIN); + assert_eq!(view.zones.len(), 1); + assert_eq!(ids(&view.zones[0].notes), ["in-perf"]); + assert_eq!(ids(&view.loose), ["in-infra"]); + assert_eq!(view.matched, 2); } #[test] - fn the_surface_is_never_smaller_than_a_screen() { - let (width, height) = surface(&[], &[], CARD); + fn a_zone_names_its_sub_folders_by_name_with_what_each_one_holds_below() { + let folders = [ + folder("infra", None, "Infra"), + folder("zeta", Some("infra"), "zeta"), + folder("alpha", Some("infra"), "Alpha"), + folder("deep", Some("zeta"), "Deep"), + ]; + let notes = vec![ + filed("a", Some("zeta")), + filed("b", Some("deep")), + filed("c", Some("infra")), + ]; + + let view = build( + notes, + &folders, + &HashMap::new(), + &HashMap::new(), + &Facets::default(), + &request(None), + ); - assert!(width >= 960); - assert!(height >= 540); + let children: Vec<(&str, u32)> = view.zones[0] + .children + .iter() + .map(|child| (child.name.as_str(), child.count)) + .collect(); + assert_eq!(children, [("Alpha", 0), ("zeta", 2)]); } + /// A zone with sub-folders is taller by their row; a stored frame is kept as it is. #[test] - fn tidying_up_puts_every_zone_back_in_reading_order() { - let counts = vec![ - ("a".into(), notes(1)), - ("b".into(), notes(2)), - ("c".into(), notes(3)), + fn a_zone_never_laid_out_is_sized_for_its_notes_and_its_sub_folders() { + let stored = frame(300, 300, 600, 600); + let frames = HashMap::from([("docs".to_string(), stored)]); + let notes = vec![ + filed("a", Some("infra")), + filed("b", Some("infra")), + filed("c", Some("infra")), ]; - let layout = arrange_everything(&counts, &[], CARD); + let view = build( + notes, + &folders(), + &frames, + &HashMap::new(), + &Facets::default(), + &request(None), + ); - let xs: Vec = layout.zones.iter().map(|zone| zone.frame.x).collect(); - assert_eq!(xs[0], BOARD_MARGIN); - assert!(xs[1] > xs[0] && xs[2] > xs[1]); - assert!(layout.zones.iter().all(|zone| zone.frame.y == BOARD_MARGIN)); + assert_eq!( + view.zones[0].frame, + frame( + BOARD_MARGIN, + BOARD_MARGIN, + default_zone_width(), + default_zone_height(3, true, CARD) + ) + ); + assert_eq!(view.zones[1].frame, stored); } - /// A zone stretched or squashed by hand comes back at the height its contents need. #[test] - fn tidying_up_resizes_a_zone_to_what_it_holds() { - let layout = arrange_everything(&[("a".into(), notes(5))], &[], CARD); + fn a_free_card_keeps_its_place_and_one_without_takes_a_free_seat_under_the_zones() { + let placed = point(BOARD_MARGIN, 2_000); + let positions = HashMap::from([("placed".to_string(), placed)]); + let notes = vec![filed("new", None), filed("placed", None)]; + + let view = board(notes, &positions, &request(None)); + let at: HashMap<&str, BoardPoint> = view + .loose + .iter() + .map(|entry| (entry.note.id.as_str(), entry.position.unwrap())) + .collect(); + assert_eq!(at["placed"], placed); + let zones: Vec = view.zones.iter().map(|zone| zone.frame).collect(); assert_eq!( - layout.zones[0].frame.height, - default_zone_height(5, false, CARD) + at["new"], + free_slot(loose_top(&zones), &[placed], &zones, CARD) ); - assert_eq!(layout.zones[0].frame.width, default_zone_width()); } + /// Spatial memory is what the board has that the list does not: a card is dimmed in place. #[test] - fn tidied_loose_cards_flow_under_the_zones() { - let layout = - arrange_everything(&[("a".into(), notes(2))], &["n1".into(), "n2".into()], CARD); + fn a_card_that_does_not_match_is_dimmed_not_dropped() { + let notes = vec![ + Note { + title: "Postgres".to_string(), + ..filed("hit", Some("infra")) + }, + filed("miss", None), + ]; + let query = BoardQuery { + search: "postgres".to_string(), + ..request(None) + }; - let zone = layout.zones[0].frame; - assert!( - layout - .cards - .iter() - .all(|card| card.position.y > zone.y + zone.height) - ); - assert_eq!(layout.cards[0].position.x, BOARD_MARGIN); - assert!(layout.cards[1].position.x > layout.cards[0].position.x); + let view = board(notes, &HashMap::new(), &query); + + assert_eq!(view.matched, 1); + assert!(view.is_filtering); + assert!(view.zones[0].notes[0].matches); + assert!(!view.loose[0].matches); } #[test] - fn the_same_board_tidied_twice_is_the_same_board() { - let counts = vec![("a".into(), notes(4)), ("b".into(), notes(1))]; - let loose = vec!["n1".to_string(), "n2".to_string()]; + fn the_quick_filter_alone_counts_as_filtering() { + let cases = [ + (NoteFilter::All, false), + (NoteFilter::Pinned, true), + (NoteFilter::Untriaged, true), + ]; - assert_eq!( - arrange_everything(&counts, &loose, CARD), - arrange_everything(&counts, &loose, CARD) + for (filter, filtering) in cases { + let query = BoardQuery { + filter, + ..request(None) + }; + assert_eq!( + board(Vec::new(), &HashMap::new(), &query).is_filtering, + filtering, + "{filter:?}" + ); + } + } + + #[test] + fn a_pinned_card_comes_first_in_its_zone() { + let notes = vec![ + filed("first", Some("infra")), + Note { + pinned: true, + ..filed("pinned", Some("infra")) + }, + filed("second", Some("infra")), + ]; + + let view = board(notes, &HashMap::new(), &request(None)); + + assert_eq!(ids(&view.zones[0].notes), ["pinned", "first", "second"]); + } + + /// Drawn from the space, so the first choice on a rail does not empty it. + #[test] + fn the_rails_offer_the_space_s_tags_and_languages() { + let facets = Facets { + tags: vec![FacetCount { + value: "sql".to_string(), + count: 2, + }], + languages: vec![FacetCount { + value: Language::Sql, + count: 2, + }], + ..Facets::default() + }; + + let view = build( + Vec::new(), + &folders(), + &HashMap::new(), + &HashMap::new(), + &facets, + &request(None), ); + + assert_eq!(view.available_tags, ["sql"]); + assert_eq!(view.available_languages, [Language::Sql]); } + /// A card shows a preview; opening the note reads it whole. #[test] - fn tidying_an_empty_space_writes_nothing() { - let layout = arrange_everything(&[], &[], CARD); + fn a_card_carries_only_its_preview() { + let long = Note { + content: (1..=20) + .map(|line| format!("line {line}")) + .collect::>() + .join("\n"), + ..filed("long", None) + }; + + let view = board(vec![long], &HashMap::new(), &request(None)); - assert!(layout.zones.is_empty() && layout.cards.is_empty()); + assert!(view.loose[0].note.content.lines().count() <= model::PREVIEW_LINES); } - /// 3, 4 or 5 lines: a zone's rows and the loose grid's pitch follow the card, on the grid. + /// The zone says where a card is, unless it comes from below it; the ground needs no chip. #[test] - fn the_first_layout_follows_the_libraries_preview_lines() { - for (lines, card) in [ - (PreviewLines::Three, 120), - (PreviewLines::Four, 140), - (PreviewLines::Five, 160), - ] { - assert_eq!(lines.card_height(), card); - assert_eq!(card % 20, 0, "{lines}: off the board's grid"); - let layout = arrange_everything( - &[("a".into(), notes(3))], - &[ - "n1".into(), - "n2".into(), - "n3".into(), - "n4".into(), - "n5".into(), - ], - lines.card_height(), - ); - let zone = layout.zones[0].frame; - let body = zone.height - ZONE_BORDER * 2 - ZONE_HEADER - ZONE_PADDING * 2; - assert_eq!(body, card * 2 + GAP, "{lines}: two rows of cards"); - let cards = &layout.cards; - assert_eq!(cards[4].position.y - cards[0].position.y, card + GAP); - assert!(cards[0].position.y >= zone.y + zone.height); + fn a_card_names_its_folder_only_when_it_comes_from_below_its_zone() { + let chip = |id: &str| NoteFolder { + id: id.to_string(), + name: id.to_string(), + colour: FolderColour::Blue, + path: vec![id.to_string()], + }; + let mut view = board( + vec![ + filed("own", Some("infra")), + filed("below", Some("perf")), + filed("loose", None), + ], + &HashMap::new(), + &request(None), + ); + for entry in view.notes_mut() { + entry.folder = Some(chip(entry.note.folder_id.as_deref().unwrap_or("none"))); } + + view.keep_chips_from_below(); + + let chips: Vec<(String, bool)> = view + .notes_mut() + .map(|entry| (entry.note.id.clone(), entry.folder.is_some())) + .collect(); + let expected = [("own", false), ("below", true), ("loose", false)]; + assert_eq!(chips, expected.map(|(id, chip)| (id.to_string(), chip))); + } + + /// The same board tidied twice is the same board. + #[test] + fn tidying_everything_lays_the_zones_out_again_and_flows_the_loose_cards_under_them() { + let counts = [ + ( + "infra".to_string(), + ZoneContents { + notes: 3, + nested: true, + }, + ), + ("docs".to_string(), ZoneContents::default()), + ]; + let loose = ["a".to_string(), "b".to_string()]; + + let layout = arrange_everything(&counts, &loose, CARD); + + let frames = arrange_zones(&[counts[0].1, counts[1].1], CARD); + let placed: Vec<(&str, BoardFrame)> = layout + .zones + .iter() + .map(|zone| (zone.folder_id.as_str(), zone.frame)) + .collect(); + assert_eq!(placed, [("infra", frames[0]), ("docs", frames[1])]); + let seats = arrange_loose(2, loose_top(&frames), CARD); + let cards: Vec = layout.cards.iter().map(|card| card.position).collect(); + assert_eq!(cards, seats); + assert_eq!(arrange_everything(&counts, &loose, CARD), layout); + } + + /// A zone placed and sized by hand is the only manual work the board holds. + #[test] + fn tidying_the_loose_cards_leaves_every_zone_where_it_stands() { + let standing = [frame(0, 0, 600, 900)]; + + let layout = arrange_loose_cards(&standing, &["a".to_string()], CARD); + + assert!(layout.zones.is_empty()); + assert_eq!(layout.cards[0].position, point(BOARD_MARGIN, 900 + 2 * GAP)); } } diff --git a/crates/engine/tests/folders/board.rs b/crates/engine/tests/folders/board.rs index 61c97cc60..4425293a7 100644 --- a/crates/engine/tests/folders/board.rs +++ b/crates/engine/tests/folders/board.rs @@ -1,722 +1,420 @@ use super::*; -// Read with the board's, to be rewritten with it. -use common::snippet as draft; -use engine::folders::model::Lineage; -use engine::folders::store::{file_many, restore_filings}; -use engine::notes::kind::NoteKind; -use engine::notes::language::Language; -use engine::notes::priority::Priority; - -use engine::folders::board::{self, BoardFrame, BoardPoint, BoardQuery, BoardView, PreviewLines}; -use engine::folders::store::board as geometry; -use engine::notes::store::fetch; -use engine::notes::view::{Grouping, NoteFilter, NoteOrder, NotesQuery}; - -pub(super) fn request(space_id: &str) -> BoardQuery { - BoardQuery { - space_id: space_id.to_string(), - root_id: None, - search: String::new(), - filter: NoteFilter::All, - tags: Vec::new(), - languages: Vec::new(), - kinds: Vec::new(), - priorities: Vec::new(), - now: t1(), - tz_offset_minutes: 0, - preview_lines: PreviewLines::default(), +use std::collections::HashMap; + +use engine::error::StorageError; +use engine::folders::board::{ + BoardPoint, BoardScope, CARD_WIDTH, CardPlacement, MAX_SIDE, MIN_ZONE_HEIGHT, MIN_ZONE_WIDTH, + Occupancy, ZoneContents, ZonePlacement, arrange_everything, arrange_loose, arrange_zones, + columns_in, free_slot, loose_top, zone_height, +}; +use engine::folders::store::board::{ + arrange, forget_positions, frame_of, frames, geometry, grow_to_fit, positions, save_layout, + set_frame, set_position, +}; +use engine::notes::store::trash::trash; + +fn frame(x: i32, y: i32, width: i32, height: i32) -> BoardFrame { + BoardFrame { + x, + y, + width, + height, } } -/// What `board_view` does, minus the decoration passes that need a connection. -pub(super) fn view(connection: &mut Library, query: &BoardQuery) -> BoardView { - let folders = list(connection, Some(&query.space_id)).unwrap(); - let (notes, facets) = fetch( - connection, - &NotesQuery { - space_id: Some(query.space_id.clone()), - folder_id: None, - search: String::new(), - filter: NoteFilter::All, - tags: Vec::new(), - languages: Vec::new(), - kinds: Vec::new(), - priorities: Vec::new(), - order: NoteOrder::default(), - grouping: Grouping::default(), - ranked: false, - now: query.now, - tz_offset_minutes: 0, - pinned_first: true, - }, - ) - .unwrap(); - - let lineage = Lineage::of(&folders); - let root = query.root_id.as_deref(); - let zones: Vec<(String, bool)> = lineage - .children(root) - .iter() - .map(|id| (id.clone(), !lineage.children(Some(id)).is_empty())) - .collect(); - let (frames, positions) = geometry::geometry( - connection, - &query.space_id, - &zones, - &board::Occupancy::on(¬es, &lineage, root), - CARD, - ) - .unwrap(); - - board::build(notes, &folders, &frames, &positions, &facets, query) +fn point(x: i32, y: i32) -> BoardPoint { + BoardPoint { x, y } } -pub(super) fn titled(connection: &mut Library, space_id: &str, title: &str) -> Note { - create_note( - connection, - NoteDraft { - title: title.to_string(), - ..draft(space_id) - }, - t0(), - ) - .unwrap() +fn zone(folder_id: &str, frame: BoardFrame) -> ZonePlacement { + ZonePlacement { + folder_id: folder_id.to_string(), + frame, + } } -#[test] -fn a_board_draws_every_folder_as_a_zone_holding_its_notes() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - // Distinct instants: `list` orders by `(created_at, id)`, so two folders made - // in the same millisecond fall back to their UUIDs — stable across launches, which - // is what the board needs, but not something a test can name. - let migrations = create(&mut connection, &sql, None, "Migrations", t0()).unwrap(); - create(&mut connection, &sql, None, "Perf", t1()).unwrap(); - let filed = note_in(&mut connection, &sql); - note_in(&mut connection, &sql); - file_many( - &mut connection, - std::slice::from_ref(&filed.id), - Some(&migrations.id), - CARD, - ) - .unwrap(); - - let board = view(&mut connection, &request(&sql)); +fn card(note_id: &str, position: BoardPoint) -> CardPlacement { + CardPlacement { + note_id: note_id.to_string(), + position, + } +} - assert_eq!(board.zones.len(), 2); - assert_eq!(board.zones[0].folder.name, "Migrations"); - assert_eq!(board.zones[0].notes.len(), 1); - assert!(board.zones[1].notes.is_empty()); - assert_eq!(board.loose.len(), 1); +/// Work: Infra ─ Perf, and Docs beside it, a millisecond apart so the order is theirs. +struct Space { + id: String, + infra: String, + perf: String, + docs: String, } -/// A board is a list like the canvas: filed or loose, a card carries a preview. -#[test] -fn a_board_card_carries_the_head_of_a_long_body() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - // A snippet: a Note's preview is its words, not its lines. - let long = || NoteDraft { - language: Language::Sh, - content: "1\n2\n3\n4\n5\n6\n7".to_string(), - ..draft(&sql) - }; - let filed = create_note(&mut connection, long(), t0()).unwrap(); - create_note(&mut connection, long(), t0()).unwrap(); - file_many( - &mut connection, - std::slice::from_ref(&filed.id), - Some(&perf.id), - CARD, - ) - .unwrap(); +fn space_with_folders(connection: &mut Library) -> Space { + let id = space(connection, "Work"); + let after = |ms: i64| t0() + chrono::TimeDelta::milliseconds(ms); + let infra = create(connection, &id, None, "Infra", after(0)).unwrap().id; + let perf = create(connection, &id, Some(&infra), "Perf", after(1)) + .unwrap() + .id; + let docs = create(connection, &id, None, "Docs", after(2)).unwrap().id; + Space { + id, + infra, + perf, + docs, + } +} - let mut board = view(&mut connection, &request(&sql)); +fn frame_now(connection: &mut Library, folder_id: &str) -> Option { + frame_of(connection.db(), folder_id).unwrap() +} - assert_eq!(board.notes_mut().count(), 2); - assert!( - board - .notes_mut() - .all(|note| note.truncated && note.content == "1\n2\n3\n4\n5") - ); +fn places(connection: &mut Library, space_id: &str) -> HashMap { + positions(connection.db(), space_id).unwrap() } -/// A filed card flows inside its zone; only a loose one carries a place of its own. #[test] -fn a_filed_card_has_no_position_and_a_loose_one_does() { +fn a_frame_is_stored_whole_and_a_folder_never_laid_out_has_none() { let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let filed = note_in(&mut connection, &sql); - note_in(&mut connection, &sql); - file_many( - &mut connection, - std::slice::from_ref(&filed.id), - Some(&perf.id), - CARD, - ) - .unwrap(); - - let board = view(&mut connection, &request(&sql)); - - assert!(board.zones[0].notes[0].position.is_none()); - assert!(board.loose[0].position.is_some()); + let work = space_with_folders(&mut connection); + let home = space(&mut connection, "Home"); + let garden = folder(&mut connection, &home, None, "Garden"); + let laid = frame(40, 60, 600, 400); + set_frame(connection.db(), &work.infra, laid).unwrap(); + set_frame(connection.db(), &garden, laid).unwrap(); + + assert_eq!(frame_now(&mut connection, &work.infra), Some(laid)); + assert_eq!(frame_now(&mut connection, &work.docs), None); + assert_eq!(frame_now(&mut connection, "missing"), None); + let stored = frames(connection.db(), &work.id).unwrap(); + assert_eq!(stored, HashMap::from([(work.infra, laid)])); } -/// The board would look shuffled at every launch otherwise. +/// Shrinking would move the board under the pointer; a zone made too small is reopened. #[test] -fn the_first_layout_is_written_down_and_read_back_unchanged() { +fn a_zone_grows_to_fit_its_notes_at_its_own_width_and_never_shrinks() { let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - create(&mut connection, &sql, None, "Migrations", t0()).unwrap(); - create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - note_in(&mut connection, &sql); + let work = space_with_folders(&mut connection); + let wide = default_zone_width() + CARD_WIDTH + 12; + set_frame(connection.db(), &work.infra, frame(0, 0, wide, 10)).unwrap(); + set_frame(connection.db(), &work.perf, frame(0, 0, wide, 5_000)).unwrap(); - let first = view(&mut connection, &request(&sql)); - let second = view(&mut connection, &request(&sql)); + for folder_id in [&work.infra, &work.perf, &work.docs] { + grow_to_fit(connection.db(), folder_id, (6, true), CARD).unwrap(); + } + assert_eq!(columns_in(wide), 3); + let needed = zone_height(6, 3, true, CARD); assert_eq!( - first - .zones - .iter() - .map(|zone| zone.frame) - .collect::>(), - second - .zones - .iter() - .map(|zone| zone.frame) - .collect::>(), + frame_now(&mut connection, &work.infra).unwrap().height, + needed ); - assert_eq!(first.loose[0].position, second.loose[0].position); + assert_eq!( + frame_now(&mut connection, &work.perf).unwrap().height, + 5_000 + ); + assert_eq!(frame_now(&mut connection, &work.docs), None); } -/// A frame is computed once: the gesture that files a card into a full zone is the one -/// that makes room, or the card flows out of sight. #[test] -fn filing_a_card_into_a_full_zone_makes_room_for_it() { +fn a_card_s_place_is_stored_replaced_and_forgotten_note_by_note() { let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let filled: Vec = ["a", "b"] - .iter() - .map(|title| titled(&mut connection, &sql, title).id) - .collect(); - file_many(&mut connection, &filled, Some(&perf.id), CARD).unwrap(); - let before = view(&mut connection, &request(&sql)).zones[0].frame; - - let extra = titled(&mut connection, &sql, "c"); - file_many( - &mut connection, - std::slice::from_ref(&extra.id), - Some(&perf.id), - CARD, - ) - .unwrap(); + let work = space(&mut connection, "Work"); + let home = space(&mut connection, "Home"); + let kept = note_in(&mut connection, &work).id; + let forgotten = note_in(&mut connection, &work).id; + let elsewhere = note_in(&mut connection, &home).id; + for id in [&kept, &forgotten, &elsewhere] { + set_position(connection.db(), id, point(1, 1)).unwrap(); + } - let after = view(&mut connection, &request(&sql)).zones[0].frame; - assert!( - after.height > before.height, - "the zone stayed {}px tall for three cards", - before.height - ); - assert_eq!(after.width, before.width, "the width must not move"); -} + set_position(connection.db(), &kept, point(40, 60)).unwrap(); + forget_positions(connection.db(), std::slice::from_ref(&forgotten)).unwrap(); + forget_positions(connection.db(), &[]).unwrap(); -/// A zone slightly narrower than nominal still flows two across, so the next card filed -/// in needs at most one more row. -#[test] -fn filing_into_a_zone_shaved_narrower_than_nominal_adds_one_row_and_not_two() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - view(&mut connection, &request(&sql)); - - let shaved = BoardFrame { - x: 0, - y: 40, - width: board::default_zone_width() - 14, - height: board::zone_height(2, 2, false, CARD), - }; - connection - .transaction(|connection, _vault| geometry::set_frame(connection, &perf.id, shaved)) - .unwrap(); - - let notes: Vec = ["a", "b", "c"] - .iter() - .map(|title| titled(&mut connection, &sql, title).id) - .collect(); - file_many(&mut connection, ¬es, Some(&perf.id), CARD).unwrap(); - - let after = view(&mut connection, &request(&sql)).zones[0].frame; - assert_eq!(after.width, shaved.width, "the width must not move"); assert_eq!( - after.height, - board::zone_height(3, 2, false, CARD), - "three cards two across are two rows, not three" + places(&mut connection, &work), + HashMap::from([(kept, point(40, 60))]) ); + assert_eq!(places(&mut connection, &home).len(), 1); } -/// Grow only: shrinking would move the board under the pointer every time a card -/// is taken out, and a zone somebody stretched is a zone they chose the size of. +/// Clamped rather than refused: an error mid-gesture would leave the screen holding a frame +/// the library refused. #[test] -fn a_zone_made_bigger_by_hand_keeps_its_size() { +fn a_gesture_saves_its_zones_and_its_cards_kept_on_the_board() { let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - view(&mut connection, &request(&sql)); - - let stretched = BoardFrame { - x: 40, - y: 40, - width: 600, - height: 900, - }; - connection - .transaction(|connection, _vault| geometry::set_frame(connection, &perf.id, stretched)) - .unwrap(); + let work = space_with_folders(&mut connection); + let loose = note_in(&mut connection, &work.id).id; - let note = titled(&mut connection, &sql, "a"); - file_many( + save_layout( &mut connection, - std::slice::from_ref(¬e.id), - Some(&perf.id), - CARD, + None, + &[zone(&work.infra, frame(-5, 20, 10, 10))], + &[card(&loose, point(-1, MAX_SIDE + 1))], ) .unwrap(); assert_eq!( - view(&mut connection, &request(&sql)).zones[0].frame, - stretched + frame_now(&mut connection, &work.infra), + Some(frame(0, 20, MIN_ZONE_WIDTH, MIN_ZONE_HEIGHT)) + ); + assert_eq!( + places(&mut connection, &work.id)[&loose], + point(0, MAX_SIDE) ); } -/// Taking a card out leaves the room it needed: the board must not move on its own. +/// One filed elsewhere between the drag and the save would get back the place filing dropped. #[test] -fn unfiling_a_card_does_not_close_the_zone_again() { +fn a_gesture_places_only_the_cards_filed_in_the_root_of_its_board() { let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let notes: Vec = ["a", "b", "c"] - .iter() - .map(|title| titled(&mut connection, &sql, title).id) - .collect(); - file_many(&mut connection, ¬es, Some(&perf.id), CARD).unwrap(); - let grown = view(&mut connection, &request(&sql)).zones[0].frame; - - file_many(&mut connection, ¬es[..1], None, CARD).unwrap(); - - assert_eq!(view(&mut connection, &request(&sql)).zones[0].frame, grown); -} + let work = space_with_folders(&mut connection); + let loose = note_in(&mut connection, &work.id).id; + let in_infra = filed(&mut connection, &work.id, &work.infra); + let in_perf = filed(&mut connection, &work.id, &work.perf); + let cards = [&loose, &in_infra, &in_perf].map(|id| card(id, point(40, 40))); -/// Undoing puts notes back into a zone that may no longer be tall enough for them. -#[test] -fn undoing_a_filing_makes_room_for_what_comes_back() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let notes: Vec = ["a", "b", "c"] - .iter() - .map(|title| titled(&mut connection, &sql, title).id) - .collect(); - file_many(&mut connection, ¬es, Some(&perf.id), CARD).unwrap(); - let grown = view(&mut connection, &request(&sql)).zones[0].frame; - - // Squashed back down behind the zone's back, as a resize would. - connection - .transaction(|connection, _vault| { - geometry::set_frame( - connection, - &perf.id, - BoardFrame { - height: 212, - ..grown - }, - ) - }) - .unwrap(); - let left = file_many(&mut connection, ¬es[..1], None, CARD).unwrap(); - restore_filings(&mut connection, &left, CARD).unwrap(); + save_layout(&mut connection, Some(&work.infra), &[], &cards).unwrap(); - assert_eq!( - view(&mut connection, &request(&sql)).zones[0].frame.height, - grown.height - ); + let placed = places(&mut connection, &work.id); + assert_eq!(placed.keys().collect::>(), [&in_infra]); } +/// A board half written is a board nobody arranged. #[test] -fn a_stored_frame_survives_the_next_read() { +fn a_gesture_naming_a_folder_gone_saves_nothing() { let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - view(&mut connection, &request(&sql)); - - let moved = BoardFrame { - x: 700, - y: 500, - width: 300, - height: 200, - }; - connection - .transaction(|connection, _vault| geometry::set_frame(connection, &perf.id, moved)) - .unwrap(); - - assert_eq!(view(&mut connection, &request(&sql)).zones[0].frame, moved); + let work = space_with_folders(&mut connection); + let zones = [ + zone(&work.infra, frame(40, 40, 600, 400)), + zone("missing", frame(0, 0, 600, 400)), + ]; + + assert!(matches!( + save_layout(&mut connection, None, &zones, &[]), + Err(StorageError::FolderNotFound(id)) if id == "missing" + )); + assert_eq!(frame_now(&mut connection, &work.infra), None); + assert!(save_layout(&mut connection, None, &[], &[]).is_ok()); } +/// A read that writes, once: the first drag must not land among cards that have no place. A +/// zone added later takes its slot in reading order, not the first zone's. #[test] -fn a_folder_added_later_lands_beside_the_others_rather_than_on_top() { +fn reading_a_board_lays_out_what_never_was_keeps_what_was_and_writes_once() { let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - create(&mut connection, &sql, None, "Migrations", t0()).unwrap(); - let first = view(&mut connection, &request(&sql)).zones[0].frame; - - create(&mut connection, &sql, None, "Perf", t1()).unwrap(); - let board = view(&mut connection, &request(&sql)); + let work = space_with_folders(&mut connection); + let placed = note_in(&mut connection, &work.id).id; + let first_new = note_in(&mut connection, &work.id).id; + let second_new = note_in(&mut connection, &work.id).id; + let infra = frame(2_000, 40, 600, 400); + set_frame(connection.db(), &work.infra, infra).unwrap(); + set_position(connection.db(), &placed, point(16, 3_000)).unwrap(); + let zones = [(work.infra.clone(), true), (work.docs.clone(), false)]; + let occupancy = Occupancy { + per_folder: HashMap::from([(work.docs.clone(), 3)]), + loose: vec![placed.clone(), first_new.clone(), second_new.clone()], + }; - assert_eq!(board.zones[0].frame, first); - assert_ne!(board.zones[1].frame, first); -} + let (laid, seats) = geometry(&mut connection, &work.id, &zones, &occupancy, CARD).unwrap(); -/// Dimmed, never dropped: reflowing the survivors throws away the only thing the board -/// has that the date view does not. -#[test] -fn a_search_dims_what_it_does_not_match_and_removes_nothing() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let wanted = titled(&mut connection, &sql, "Index sur orders"); - titled(&mut connection, &sql, "Dump nocturne"); - file_many( - &mut connection, - std::slice::from_ref(&wanted.id), - Some(&perf.id), + let arranged = arrange_zones( + &[ + ZoneContents { + notes: 0, + nested: true, + }, + ZoneContents { + notes: 3, + nested: false, + }, + ], CARD, - ) - .unwrap(); - - let board = view( - &mut connection, - &BoardQuery { - search: "orders".to_string(), - ..request(&sql) - }, ); - - assert_eq!(board.zones[0].notes.len(), 1); - assert_eq!(board.loose.len(), 1); - assert!(board.zones[0].notes[0].matches); - assert!(!board.loose[0].matches); - assert_eq!(board.matched, 1); - assert!(board.is_filtering); + let docs = arranged[1]; + assert_eq!( + laid, + HashMap::from([(work.infra.clone(), infra), (work.docs.clone(), docs)]) + ); + let standing = [infra, docs]; + let top = loose_top(&standing); + let first = free_slot(top, &[point(16, 3_000)], &standing, CARD); + let second = free_slot(top, &[point(16, 3_000), first], &standing, CARD); + assert_ne!(first, second); + assert_eq!( + (seats[&placed], seats[&first_new], seats[&second_new]), + (point(16, 3_000), first, second) + ); + assert_eq!(frame_now(&mut connection, &work.docs), Some(docs)); + let again = geometry(&mut connection, &work.id, &zones, &occupancy, CARD).unwrap(); + assert_eq!(again, (laid, seats)); } -/// Accents fold both ways here too: it is `notes::view`'s own matcher, not a second one. +/// Another board's geometry must not take a seat on this one. #[test] -fn the_board_search_folds_accents_like_the_canvas_does() { +fn a_board_answers_only_its_own_zones_and_its_own_free_cards() { let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - titled(&mut connection, &sql, "Étape suivante"); + let work = space_with_folders(&mut connection); + let in_infra = filed(&mut connection, &work.id, &work.infra); + set_frame(connection.db(), &work.perf, frame(40, 40, 600, 400)).unwrap(); + set_position(connection.db(), &in_infra, point(40, 40)).unwrap(); + let zones = [(work.infra.clone(), true), (work.docs.clone(), false)]; + let nothing = Occupancy::default(); - let board = view( - &mut connection, - &BoardQuery { - search: "etape".to_string(), - ..request(&sql) - }, - ); + let (laid, seats) = geometry(&mut connection, &work.id, &zones, ¬hing, CARD).unwrap(); - assert!(board.loose[0].matches); + assert!(!laid.contains_key(&work.perf)); + assert!(seats.is_empty()); } +/// Zones in creation order sized to their whole sub-tree, the cards flowed under them; the +/// answer is what had a place, for the undo. #[test] -fn a_quick_filter_dims_rather_than_narrows_too() { +fn tidying_everything_lays_the_zones_out_again_and_the_free_cards_under_them() { let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - create_note( + let work = space_with_folders(&mut connection); + filed(&mut connection, &work.id, &work.perf); + // In the trash, they take no room in the zone they were in. + for _ in 0..3 { + let trashed = filed(&mut connection, &work.id, &work.docs); + trash(&mut connection, &trashed, t1()).unwrap(); + } + let loose = note_in(&mut connection, &work.id).id; + let by_hand = frame(3_000, 3_000, 900, 900); + set_frame(connection.db(), &work.infra, by_hand).unwrap(); + set_position(connection.db(), &loose, point(5_000, 5_000)).unwrap(); + + let done = arrange( &mut connection, - NoteDraft { - pinned: true, - ..draft(&sql) - }, - t0(), + &work.id, + None, + BoardScope::Everything, + CARD, ) .unwrap(); - create_note(&mut connection, draft(&sql), t0()).unwrap(); - let board = view( - &mut connection, - &BoardQuery { - filter: NoteFilter::Pinned, - ..request(&sql) - }, + let expected = arrange_everything( + &[ + ( + work.infra.clone(), + ZoneContents { + notes: 1, + nested: true, + }, + ), + (work.docs.clone(), ZoneContents::default()), + ], + std::slice::from_ref(&loose), + CARD, ); - - assert_eq!(board.loose.len(), 2); - assert_eq!(board.matched, 1); + assert_eq!( + frame_now(&mut connection, &work.infra), + Some(expected.zones[0].frame) + ); + assert_eq!( + frame_now(&mut connection, &work.docs), + Some(expected.zones[1].frame) + ); + assert_eq!( + places(&mut connection, &work.id)[&loose], + expected.cards[0].position + ); + assert_eq!(done.moved, 2); + assert_eq!(done.previous.zones, [zone(&work.infra, by_hand)]); + assert_eq!(done.previous.cards, [card(&loose, point(5_000, 5_000))]); } +/// A board already in order moves nothing, and opens no undo. #[test] -fn a_priority_dims_rather_than_narrows_too() { +fn a_board_tidied_twice_moves_nothing_the_second_time() { let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - create_note(&mut connection, draft(&sql), t0()).unwrap(); - create_note( + let work = space_with_folders(&mut connection); + note_in(&mut connection, &work.id); + arrange( &mut connection, - NoteDraft { - priority: Priority::High, - ..draft(&sql) - }, - t0(), + &work.id, + None, + BoardScope::Everything, + CARD, ) .unwrap(); - let board = view( - &mut connection, - &BoardQuery { - priorities: vec![Priority::High], - ..request(&sql) - }, - ); - - assert_eq!(board.loose.len(), 2); - assert_eq!(board.matched, 1); -} - -#[test] -fn a_kind_dims_rather_than_narrows_too() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - create_note(&mut connection, draft(&sql), t0()).unwrap(); - create_note( + let again = arrange( &mut connection, - NoteDraft { - kind: NoteKind::Note, - ..draft(&sql) - }, - t0(), + &work.id, + None, + BoardScope::Everything, + CARD, ) .unwrap(); - let board = view( - &mut connection, - &BoardQuery { - kinds: vec![NoteKind::Note], - ..request(&sql) - }, - ); - - assert_eq!(board.loose.len(), 2); - assert_eq!(board.matched, 1); - assert!(board.is_filtering); -} - -/// The two views answer the same question, and must not answer it differently. Tags -/// are compared as the column compares them — ASCII case only, `#` stripped — and a -/// tag that normalises to nothing asks for nothing. -#[test] -fn the_board_and_the_date_view_agree_on_what_matches() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - for (title, tags) in [ - ("accented", vec!["étape"]), - ("capital", vec!["Étape"]), - ("urgent", vec!["URGENT"]), - ("plain", Vec::new()), - ] { - create_note( - &mut connection, - NoteDraft { - title: title.to_string(), - tags: tags.into_iter().map(ToString::to_string).collect(), - ..draft(&sql) - }, - t0(), - ) - .unwrap(); - } - - for asked in [vec!["étape"], vec!["#urgent"], vec![" # "], Vec::new()] { - let tags: Vec = asked.iter().map(ToString::to_string).collect(); - - let query = NotesQuery { - space_id: Some(sql.clone()), - folder_id: None, - search: String::new(), - filter: NoteFilter::All, - tags: tags.clone(), - languages: Vec::new(), - kinds: Vec::new(), - priorities: Vec::new(), - order: NoteOrder::default(), - grouping: Grouping::default(), - ranked: false, - now: t1(), - tz_offset_minutes: 0, - pinned_first: true, - }; - let (notes, facets) = fetch(&mut connection, &query).unwrap(); - let dated = engine::notes::view::build(notes, facets, &query); - let mut on_the_date_view: Vec = dated - .sections - .iter() - .flat_map(|section| section.cards.iter().map(|card| card.title.clone())) - .collect(); - - let board = view( - &mut connection, - &BoardQuery { - tags, - ..request(&sql) - }, - ); - let mut lit_on_the_board: Vec = board - .loose - .iter() - .filter(|entry| entry.matches) - .map(|entry| entry.note.title.clone()) - .collect(); - - on_the_date_view.sort(); - lit_on_the_board.sort(); - assert_eq!(on_the_date_view, lit_on_the_board, "asked for {asked:?}"); - assert_eq!( - dated.is_filtering, board.is_filtering, - "asked for {asked:?}" - ); - } + assert_eq!(again.moved, 0); } -/// Filing a card into a zone drops the place it had on the background. +/// The only manual work the board holds is a zone placed and sized by hand. #[test] -fn filing_a_loose_note_forgets_where_it_sat() { +fn tidying_the_free_cards_flows_them_under_the_zones_as_they_stand() { let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let note = note_in(&mut connection, &sql); - view(&mut connection, &request(&sql)); - - let placed = connection - .transaction(|connection, _vault| geometry::positions(connection, &sql)) - .unwrap(); - assert!(placed.contains_key(¬e.id)); + let work = space_with_folders(&mut connection); + let by_hand = frame(40, 40, 600, 900); + set_frame(connection.db(), &work.infra, by_hand).unwrap(); + let older = note_in(&mut connection, &work.id).id; + let pinned = NoteDraft { + pinned: true, + ..snippet(&work.id) + }; + let pinned = create_note(&mut connection, pinned, t0()).unwrap().id; - file_many( + let done = arrange( &mut connection, - std::slice::from_ref(¬e.id), - Some(&perf.id), + &work.id, + None, + BoardScope::LooseCards, CARD, ) .unwrap(); - let after = connection - .transaction(|connection, _vault| geometry::positions(connection, &sql)) - .unwrap(); - assert!(!after.contains_key(¬e.id)); -} - -#[test] -fn a_stored_position_is_what_a_later_read_hands_back() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let note = note_in(&mut connection, &sql); - view(&mut connection, &request(&sql)); - - let chosen = BoardPoint { x: 640, y: 480 }; - connection - .transaction(|connection, _vault| geometry::set_position(connection, ¬e.id, chosen)) - .unwrap(); - - assert_eq!( - view(&mut connection, &request(&sql)).loose[0].position, - Some(chosen) - ); + let seats = arrange_loose(2, loose_top(&[by_hand]), CARD); + let placed = places(&mut connection, &work.id); + assert_eq!((placed[&pinned], placed[&older]), (seats[0], seats[1])); + assert_eq!(frame_now(&mut connection, &work.infra), Some(by_hand)); + assert!(done.previous.zones.is_empty()); + assert!(done.previous.cards.is_empty()); } -/// A new note is the most recently updated, so it comes first in the list: it must not -/// be handed seat zero, where another card already sits. +/// A folder's board is its sub-folders and what is filed in it: the space's zones stay put. #[test] -fn a_note_created_later_is_placed_beside_the_cards_rather_than_on_one() { +fn a_folder_s_board_is_tidied_on_its_own() { let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - titled(&mut connection, &sql, "Dump nocturne"); - let already_there = view(&mut connection, &request(&sql)).loose[0].position; - - create_note( + let work = space_with_folders(&mut connection); + let docs = frame(2_000, 2_000, 600, 400); + set_frame(connection.db(), &work.docs, docs).unwrap(); + let in_infra = filed(&mut connection, &work.id, &work.infra); + let loose = note_in(&mut connection, &work.id).id; + + let root = Some(work.infra.as_str()); + arrange( &mut connection, - NoteDraft { - title: "Collé du presse-papiers".to_string(), - ..draft(&sql) - }, - t1(), + &work.id, + root, + BoardScope::Everything, + CARD, ) .unwrap(); - let board = view(&mut connection, &request(&sql)); - let places: Vec<_> = board.loose.iter().map(|entry| entry.position).collect(); - - assert_eq!(places.len(), 2); - assert!( - places.contains(&already_there), - "the card already there did not move" + let expected = arrange_everything( + &[(work.perf.clone(), ZoneContents::default())], + std::slice::from_ref(&in_infra), + CARD, ); - assert_ne!(places[0], places[1], "two cards were written to one place"); -} - -/// Every unplaced card in the same pass, not just the first one. -#[test] -fn a_first_read_of_several_loose_notes_gives_each_its_own_place() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - for title in ["Un", "Deux", "Trois", "Quatre", "Cinq"] { - titled(&mut connection, &sql, title); - } - - let board = view(&mut connection, &request(&sql)); - let mut places: Vec<_> = board - .loose - .iter() - .map(|entry| entry.position.expect("a loose card is always placed")) - .map(|at| (at.x, at.y)) - .collect(); - places.sort_unstable(); - places.dedup(); - - assert_eq!(places.len(), 5); -} - -#[test] -fn the_surface_grows_to_hold_whatever_is_furthest_out() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let note = note_in(&mut connection, &sql); - view(&mut connection, &request(&sql)); - - connection - .transaction(|connection, _vault| { - geometry::set_position(connection, ¬e.id, BoardPoint { x: 3000, y: 2000 }) - }) - .unwrap(); - - let board = view(&mut connection, &request(&sql)); - assert!(board.width > 3000); - assert!(board.height > 2000); -} - -/// A board of one space says nothing about the next one. -#[test] -fn a_board_never_reaches_into_another_space() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let veille = space(&mut connection, "Veille"); - create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - create(&mut connection, &veille, None, "Liens", t0()).unwrap(); - note_in(&mut connection, &veille); - - let board = view(&mut connection, &request(&sql)); - - assert_eq!(board.zones.len(), 1); - assert!(board.loose.is_empty()); + assert_eq!( + frame_now(&mut connection, &work.perf), + Some(expected.zones[0].frame) + ); + assert_eq!(frame_now(&mut connection, &work.docs), Some(docs)); + assert_eq!(frame_now(&mut connection, &work.infra), None); + let placed = places(&mut connection, &work.id); + assert_eq!(placed[&in_infra], expected.cards[0].position); + assert!(!placed.contains_key(&loose)); } diff --git a/crates/engine/tests/folders/gesture.rs b/crates/engine/tests/folders/gesture.rs deleted file mode 100644 index 696a3c2fd..000000000 --- a/crates/engine/tests/folders/gesture.rs +++ /dev/null @@ -1,458 +0,0 @@ -use super::*; - -// Read with the board's, to be rewritten with it. -use std::collections::HashMap; - -use engine::error::StorageError; -use engine::folders::store::file_many; - -use engine::folders::board::{ - BoardFrame, BoardPoint, CardPlacement, MIN_ZONE_HEIGHT, MIN_ZONE_WIDTH, ZonePlacement, clamp, - clamp_point, zone_at, -}; -use engine::folders::store::board as geometry; - -fn frames(connection: &mut Library, space_id: &str) -> HashMap { - connection - .transaction(|connection, _vault| geometry::frames(connection, space_id)) - .unwrap() -} - -fn positions(connection: &mut Library, space_id: &str) -> HashMap { - connection - .transaction(|connection, _vault| geometry::positions(connection, space_id)) - .unwrap() -} - -/// Puts a zone and a card exactly where a drag would have left them. -fn place(connection: &mut Library, zones: &[ZonePlacement], cards: &[CardPlacement]) { - geometry::save_layout(connection, None, zones, cards).unwrap(); -} - -fn zone_at_frame(folder_id: &str, frame: BoardFrame) -> ZonePlacement { - ZonePlacement { - folder_id: folder_id.to_string(), - frame, - } -} - -fn card_at(note_id: &str, position: BoardPoint) -> CardPlacement { - CardPlacement { - note_id: note_id.to_string(), - position, - } -} - -#[test] -fn a_moved_zone_and_a_moved_card_are_written_as_one_batch() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let note = note_in(&mut connection, &sql); - - let frame = BoardFrame { - x: 600, - y: 320, - width: 520, - height: 400, - }; - let point = BoardPoint { x: 48, y: 720 }; - geometry::save_layout( - &mut connection, - None, - &[ZonePlacement { - folder_id: perf.id.clone(), - frame, - }], - &[CardPlacement { - note_id: note.id.clone(), - position: point, - }], - ) - .unwrap(); - - assert_eq!(frames(&mut connection, &sql).get(&perf.id), Some(&frame)); - assert_eq!(positions(&mut connection, &sql).get(¬e.id), Some(&point)); -} - -/// A zone nothing can be dropped into is not a zone. Clamped rather than refused: -/// answering an error mid-gesture leaves the interface holding a frame nothing stored. -#[test] -fn a_zone_squashed_to_nothing_keeps_room_for_one_card() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - - geometry::save_layout( - &mut connection, - None, - &[ZonePlacement { - folder_id: perf.id.clone(), - frame: BoardFrame { - x: -50, - y: -50, - width: 4, - height: 4, - }, - }], - &[], - ) - .unwrap(); - - let stored = frames(&mut connection, &sql); - let frame = stored.get(&perf.id).unwrap(); - assert_eq!(frame.x, 0); - assert_eq!(frame.y, 0); - assert_eq!(frame.width, MIN_ZONE_WIDTH); - assert_eq!(frame.height, MIN_ZONE_HEIGHT); -} - -/// A filed card flows inside its zone. Writing a position for one would put back the -/// row `file_many` had just dropped, and the table would stop meaning "this is loose". -#[test] -fn a_card_filed_since_the_drag_is_not_given_a_position_back() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let note = note_in(&mut connection, &sql); - file_many( - &mut connection, - std::slice::from_ref(¬e.id), - Some(&perf.id), - CARD, - ) - .unwrap(); - - geometry::save_layout( - &mut connection, - None, - &[], - &[CardPlacement { - note_id: note.id.clone(), - position: BoardPoint { x: 10, y: 10 }, - }], - ) - .unwrap(); - - assert!(!positions(&mut connection, &sql).contains_key(¬e.id)); -} - -/// Every zone or none: half a board is a board nobody arranged. -#[test] -fn a_batch_naming_a_folder_that_is_gone_writes_nothing_at_all() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let note = note_in(&mut connection, &sql); - - let refused = geometry::save_layout( - &mut connection, - None, - &[ - ZonePlacement { - folder_id: perf.id.clone(), - frame: BoardFrame { - x: 600, - y: 320, - width: 520, - height: 400, - }, - }, - ZonePlacement { - folder_id: "gone".to_string(), - frame: BoardFrame { - x: 0, - y: 0, - width: 520, - height: 400, - }, - }, - ], - &[CardPlacement { - note_id: note.id.clone(), - position: BoardPoint { x: 48, y: 720 }, - }], - ); - - assert!(matches!(refused, Err(StorageError::FolderNotFound(_)))); - assert!(frames(&mut connection, &sql).is_empty()); - assert!(positions(&mut connection, &sql).is_empty()); -} - -#[test] -fn an_empty_batch_is_not_an_error() { - let mut connection = open_in_memory().unwrap(); - - assert!(geometry::save_layout(&mut connection, None, &[], &[]).is_ok()); -} - -/// Membership comes from the drop, and from nothing else. -#[test] -fn a_point_names_the_zone_it_falls_in() { - let zones = vec![ - ( - "a".to_string(), - BoardFrame { - x: 0, - y: 0, - width: 100, - height: 100, - }, - ), - ( - "b".to_string(), - BoardFrame { - x: 200, - y: 0, - width: 100, - height: 100, - }, - ), - ]; - - assert_eq!( - zone_at(&zones, BoardPoint { x: 50, y: 50 }), - Some("a".into()) - ); - assert_eq!( - zone_at(&zones, BoardPoint { x: 250, y: 50 }), - Some("b".into()) - ); -} - -/// The free background is a legitimate answer: dropping there unfiles the note. -#[test] -fn a_point_on_the_background_names_no_zone() { - let zones = vec![( - "a".to_string(), - BoardFrame { - x: 0, - y: 0, - width: 100, - height: 100, - }, - )]; - - assert_eq!(zone_at(&zones, BoardPoint { x: 150, y: 50 }), None); - // The far edges belong to the next zone along, not to this one. - assert_eq!(zone_at(&zones, BoardPoint { x: 100, y: 50 }), None); - assert_eq!(zone_at(&zones, BoardPoint { x: 0, y: 0 }), Some("a".into())); -} - -/// Drawn later means drawn on top, so it is what a drop lands in. -#[test] -fn overlapping_zones_hand_the_drop_to_the_topmost() { - let zones = vec![ - ( - "under".to_string(), - BoardFrame { - x: 0, - y: 0, - width: 200, - height: 200, - }, - ), - ( - "over".to_string(), - BoardFrame { - x: 50, - y: 50, - width: 100, - height: 100, - }, - ), - ]; - - assert_eq!( - zone_at(&zones, BoardPoint { x: 100, y: 100 }), - Some("over".into()) - ); -} - -#[test] -fn a_runaway_drag_cannot_put_anything_off_the_board() { - assert_eq!(clamp_point(BoardPoint { x: -40, y: -40 }).x, 0); - assert_eq!( - clamp(BoardFrame { - x: 10, - y: 10, - width: 1_000_000, - height: 10 - }) - .width, - engine::folders::board::MAX_SIDE - ); -} - -/// The one board gesture that cannot be walked back by dragging: it moves everything at -/// once and overwrites sizes chosen by hand. -mod tidy_up { - use super::*; - - use engine::folders::board::{BoardScope, default_zone_height, default_zone_width}; - - const DRAGGED: BoardFrame = BoardFrame { - x: 900, - y: 640, - width: 900, - height: 700, - }; - - #[test] - fn a_zone_dragged_away_comes_back_to_its_seat() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - place(&mut connection, &[zone_at_frame(&perf.id, DRAGGED)], &[]); - - geometry::arrange(&mut connection, &sql, None, BoardScope::Everything, CARD).unwrap(); - - let frame = *frames(&mut connection, &sql).get(&perf.id).unwrap(); - assert_eq!(frame.x, 16); - assert_eq!(frame.y, 16); - assert_eq!(frame.width, default_zone_width()); - assert_eq!(frame.height, default_zone_height(0, false, CARD)); - } - - /// The half that makes it a tidy-up: a zone too small for what it holds is reopened. - #[test] - fn a_zone_is_resized_to_what_it_actually_holds() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let notes: Vec = (0..5).map(|_| note_in(&mut connection, &sql).id).collect(); - file_many(&mut connection, ¬es, Some(&perf.id), CARD).unwrap(); - - geometry::arrange(&mut connection, &sql, None, BoardScope::Everything, CARD).unwrap(); - - let frame = *frames(&mut connection, &sql).get(&perf.id).unwrap(); - assert_eq!(frame.height, default_zone_height(5, false, CARD)); - } - - #[test] - fn the_loose_cards_flow_under_the_zones() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let filed = note_in(&mut connection, &sql).id; - file_many(&mut connection, &[filed], Some(&perf.id), CARD).unwrap(); - let loose = note_in(&mut connection, &sql).id; - - geometry::arrange(&mut connection, &sql, None, BoardScope::Everything, CARD).unwrap(); - - let zone = *frames(&mut connection, &sql).get(&perf.id).unwrap(); - let at = *positions(&mut connection, &sql).get(&loose).unwrap(); - assert!(at.y > zone.y + zone.height); - } - - /// What the undo reads. Restoring the answer has to put the board back exactly as - /// it was, or the tidy-up is a one-way gesture. - #[test] - fn it_answers_the_layout_it_replaced() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let note = note_in(&mut connection, &sql); - let seat = BoardPoint { x: 96, y: 900 }; - place( - &mut connection, - &[zone_at_frame(&perf.id, DRAGGED)], - &[card_at(¬e.id, seat)], - ); - - let before = geometry::arrange(&mut connection, &sql, None, BoardScope::Everything, CARD) - .unwrap() - .previous; - place(&mut connection, &before.zones, &before.cards); - - assert_eq!(frames(&mut connection, &sql).get(&perf.id), Some(&DRAGGED)); - assert_eq!(positions(&mut connection, &sql).get(¬e.id), Some(&seat)); - } - - /// A folder the board has never drawn had no place to go back to, and inventing - /// one on the undo would leave it somewhere nobody chose. - #[test] - fn a_zone_that_never_had_a_place_is_not_offered_back() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - note_in(&mut connection, &sql); - - let before = - geometry::arrange(&mut connection, &sql, None, BoardScope::Everything, CARD).unwrap(); - - assert!(before.previous.zones.is_empty()); - assert!(before.previous.cards.is_empty()); - } - - /// The half worth a single click: what goes to pieces is the cards outside the - /// zones, and a zone somebody sized by hand is the only manual work the board holds. - #[test] - fn aligning_the_loose_cards_leaves_every_zone_exactly_where_it_was() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let note = note_in(&mut connection, &sql); - place( - &mut connection, - &[zone_at_frame(&perf.id, DRAGGED)], - &[card_at(¬e.id, BoardPoint { x: 640, y: 1200 })], - ); - - let done = - geometry::arrange(&mut connection, &sql, None, BoardScope::LooseCards, CARD).unwrap(); - - assert_eq!(frames(&mut connection, &sql).get(&perf.id), Some(&DRAGGED)); - assert!(done.previous.zones.is_empty()); - assert_eq!(done.moved, 1); - } - - /// The cards flow under the zones **as they stand**, not under where a full - /// reorganisation would have put them. - #[test] - fn the_aligned_cards_clear_the_zones_where_they_actually_are() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let note = note_in(&mut connection, &sql); - place(&mut connection, &[zone_at_frame(&perf.id, DRAGGED)], &[]); - - geometry::arrange(&mut connection, &sql, None, BoardScope::LooseCards, CARD).unwrap(); - - let at = *positions(&mut connection, &sql).get(¬e.id).unwrap(); - assert!(at.y > DRAGGED.y + DRAGGED.height); - } - - /// What the undo bar reads. A board nobody disturbed must open no undo window, - /// or the bar offers to put back an arrangement that never changed. - #[test] - fn a_board_already_in_order_reports_nothing_moved() { - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - note_in(&mut connection, &sql); - geometry::arrange(&mut connection, &sql, None, BoardScope::Everything, CARD).unwrap(); - - let again = - geometry::arrange(&mut connection, &sql, None, BoardScope::Everything, CARD).unwrap(); - - assert_eq!(again.moved, 0); - } - - #[test] - fn a_trashed_note_takes_no_room_in_the_zone_it_was_in() { - use engine::notes::store::trash::trash_many; - - let mut connection = open_in_memory().unwrap(); - let sql = space(&mut connection, "SQL"); - let perf = create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let notes: Vec = (0..4).map(|_| note_in(&mut connection, &sql).id).collect(); - file_many(&mut connection, ¬es, Some(&perf.id), CARD).unwrap(); - trash_many(&mut connection, ¬es[..3], t1()).unwrap(); - - geometry::arrange(&mut connection, &sql, None, BoardScope::Everything, CARD).unwrap(); - - let frame = *frames(&mut connection, &sql).get(&perf.id).unwrap(); - assert_eq!(frame.height, default_zone_height(1, false, CARD)); - } -} diff --git a/crates/engine/tests/folders/main.rs b/crates/engine/tests/folders/main.rs index b33f744ff..ace5a79e9 100644 --- a/crates/engine/tests/folders/main.rs +++ b/crates/engine/tests/folders/main.rs @@ -10,14 +10,10 @@ use engine::notes::store::{create as create_note, get}; mod common; use common::{snippet, space, t0, t1}; +mod board; mod nesting; mod store; -// The board's own tests, rewritten in a lot of their own. -mod board; -mod gesture; -mod nested_boards; - /// The height of a card on these boards. const CARD: i32 = 140; diff --git a/crates/engine/tests/folders/nested_boards.rs b/crates/engine/tests/folders/nested_boards.rs deleted file mode 100644 index 3fb461e76..000000000 --- a/crates/engine/tests/folders/nested_boards.rs +++ /dev/null @@ -1,179 +0,0 @@ -use super::board::{request, titled, view}; -use super::*; - -use engine::folders::board::{BoardFrame, BoardPoint, CardPlacement, ZonePlacement}; -use engine::folders::model::Folder; -use engine::folders::store::board as geometry; -use engine::folders::store::file_many; - -/// `SQL › Perf › Index` and `SQL › Migrations`, and `Angular` beside them. -struct Tree { - space: String, - sql: Folder, - perf: Folder, - index: Folder, - angular: Folder, -} - -fn tree(connection: &mut Library) -> Tree { - // A millisecond apart: folders made in one instant would come back in the order of - // their ids. - let after = |ms: i64| t0() + chrono::TimeDelta::milliseconds(ms); - let space = space(connection, "Découverte"); - let sql = create(connection, &space, None, "SQL", after(0)).unwrap(); - let perf = create(connection, &space, Some(&sql.id), "Perf", after(1)).unwrap(); - let index = create(connection, &space, Some(&perf.id), "Index", after(2)).unwrap(); - create(connection, &space, Some(&sql.id), "Migrations", after(3)).unwrap(); - let angular = create(connection, &space, None, "Angular", after(4)).unwrap(); - Tree { - space, - sql, - perf, - index, - angular, - } -} - -fn filed(connection: &mut Library, tree: &Tree, title: &str, folder: &Folder) -> Note { - let note = titled(connection, &tree.space, title); - file_many( - connection, - std::slice::from_ref(¬e.id), - Some(&folder.id), - CARD, - ) - .unwrap(); - note -} - -fn frame_of(connection: &mut Library, id: &str) -> Option { - connection - .transaction(|connection, _vault| geometry::frame_of(connection, id)) - .unwrap() -} - -/// The space's board shows its top folders; each gathers its whole sub-tree. -#[test] -fn a_zone_gathers_the_notes_of_everything_under_it() { - let mut connection = open_in_memory().unwrap(); - let tree = tree(&mut connection); - filed(&mut connection, &tree, "Requête", &tree.sql); - filed(&mut connection, &tree, "EXPLAIN", &tree.perf); - filed(&mut connection, &tree, "Index partiel", &tree.index); - titled(&mut connection, &tree.space, "Loose"); - - let board = view(&mut connection, &request(&tree.space)); - - let zones: Vec<&str> = board - .zones - .iter() - .map(|zone| zone.folder.name.as_str()) - .collect(); - assert_eq!(zones, ["SQL", "Angular"]); - assert_eq!(board.zones[0].notes.len(), 3); - let children: Vec<(&str, u32)> = board.zones[0] - .children - .iter() - .map(|child| (child.name.as_str(), child.count)) - .collect(); - assert_eq!(children, [("Migrations", 0), ("Perf", 2)]); - assert!(board.zones[1].children.is_empty()); - assert_eq!(board.loose.len(), 1); -} - -/// A folder's board: its sub-folders as zones, what is filed in it free on its ground, and -/// nothing from outside it. -#[test] -fn a_folders_board_draws_its_sub_folders_and_its_own_notes_free() { - let mut connection = open_in_memory().unwrap(); - let tree = tree(&mut connection); - let own = filed(&mut connection, &tree, "Requête", &tree.sql); - filed(&mut connection, &tree, "Index partiel", &tree.index); - filed(&mut connection, &tree, "Composant", &tree.angular); - titled(&mut connection, &tree.space, "Loose"); - let mut inside = request(&tree.space); - inside.root_id = Some(tree.sql.id.clone()); - - let board = view(&mut connection, &inside); - - let zones: Vec<(&str, usize)> = board - .zones - .iter() - .map(|zone| (zone.folder.name.as_str(), zone.notes.len())) - .collect(); - assert_eq!(zones, [("Perf", 1), ("Migrations", 0)]); - assert_eq!(board.loose.len(), 1); - assert_eq!(board.loose[0].note.id, own.id); - assert!(board.loose[0].position.is_some()); - assert_eq!(board.matched, 2); -} - -/// A row of chips under the title is height the cards must not pay for. -#[test] -fn a_zone_with_sub_folders_is_taller_by_their_row() { - let mut connection = open_in_memory().unwrap(); - let tree = tree(&mut connection); - - let board = view(&mut connection, &request(&tree.space)); - - assert_eq!( - board.zones[0].frame.height - board.zones[1].frame.height, - engine::folders::board::ZONE_SUBFOLDERS - ); -} - -/// A card's place is on its own folder's board: saved from another board, it is refused. -#[test] -fn a_place_is_kept_only_on_the_board_of_the_cards_own_folder() { - let mut connection = open_in_memory().unwrap(); - let tree = tree(&mut connection); - let own = filed(&mut connection, &tree, "Requête", &tree.sql); - let deeper = filed(&mut connection, &tree, "EXPLAIN", &tree.perf); - let place = BoardPoint { x: 640, y: 480 }; - let cards = [own.id.clone(), deeper.id.clone()].map(|note_id| CardPlacement { - note_id, - position: place, - }); - - geometry::save_layout(&mut connection, Some(&tree.sql.id), &[], &cards).unwrap(); - - let placed = connection - .transaction(|connection, _vault| geometry::positions(connection, &tree.space)) - .unwrap(); - assert_eq!(placed.get(&own.id), Some(&place)); - assert!(!placed.contains_key(&deeper.id)); -} - -#[test] -fn a_folders_board_is_tidied_on_its_own() { - let mut connection = open_in_memory().unwrap(); - let tree = tree(&mut connection); - let frame = BoardFrame { - x: 2000, - y: 2000, - width: 600, - height: 400, - }; - geometry::save_layout( - &mut connection, - None, - &[ZonePlacement { - folder_id: tree.angular.id.clone(), - frame, - }], - &[], - ) - .unwrap(); - - geometry::arrange( - &mut connection, - &tree.space, - Some(&tree.sql.id), - engine::folders::board::BoardScope::Everything, - CARD, - ) - .unwrap(); - - assert_eq!(frame_of(&mut connection, &tree.angular.id), Some(frame)); - assert!(frame_of(&mut connection, &tree.perf.id).is_some()); -} From fe18b0c018892174685ab59575b05566e9da3bea Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 07:41:53 +0100 Subject: [PATCH 23/95] Spaces: the deletion test checks an index it filled (#1748) Co-authored-by: Claude Opus 5.5 --- crates/engine/tests/commands/spaces.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/engine/tests/commands/spaces.rs b/crates/engine/tests/commands/spaces.rs index ff069ddbf..27dcf503b 100644 --- a/crates/engine/tests/commands/spaces.rs +++ b/crates/engine/tests/commands/spaces.rs @@ -105,6 +105,7 @@ fn a_space_deleted_says_what_it_held_and_hands_its_notes_to_the_refuge() { .unwrap() .note .id; + session.wait(engine::index::fill); let held = session.call(|e| count_space_contents(e, &work)).unwrap(); let moved = session From 85151a4e9e129d504a0bb66b0f75ab04b0d53930 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:57:28 +0100 Subject: [PATCH 24/95] Folders services: unit tests rewritten (#1745) * Rewrite the tests of the folders' service functions Co-Authored-By: Claude Opus 5.5 * Fill the index before each write whose declaration is checked Co-Authored-By: Claude Opus 5.5 * Move a folder under another through the service Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/tests/commands/folders.rs | 869 ++++++++++++------------ 1 file changed, 423 insertions(+), 446 deletions(-) diff --git a/crates/engine/tests/commands/folders.rs b/crates/engine/tests/commands/folders.rs index 78d9f5121..36bc57e7a 100644 --- a/crates/engine/tests/commands/folders.rs +++ b/crates/engine/tests/commands/folders.rs @@ -1,40 +1,38 @@ use chrono::Utc; +use engine::Engine; use engine::error::ErrorCode; use engine::folders::board::{ - BoardFrame, BoardQuery, BoardScope, MIN_ZONE_HEIGHT, MIN_ZONE_WIDTH, PreviewLines, - ZonePlacement, + BoardFrame, BoardQuery, BoardScope, BoardView, PreviewLines, ZonePlacement, }; -use engine::folders::count_folder_contents; -use engine::folders::model::{FolderColour, FolderDraft}; +use engine::folders::model::{FolderColour, FolderContents, FolderDraft}; use engine::folders::{ - arrange_board, board_view, create_folder, delete_folder, file_notes, file_notes_back, - list_folders, move_folder, move_folder_back, move_notes_into, recolour_folder, rename_folder, - save_board_layout, + arrange_board, board_view, count_folder_contents, create_folder, delete_folder, file_notes, + file_notes_back, list_folders, move_folder, move_folder_back, move_notes_into, recolour_folder, + rename_folder, save_board_layout, }; -use engine::notes::model::HeldNotes; -use engine::notes::view::{Grouping, NoteFilter, NoteOrder, NotesQuery}; +use engine::notes::model::{HeldNotes, NoteDraft}; +use engine::notes::view::{Grouping, NoteFilter, NoteOrder, NotesQuery, NotesView}; use engine::notes::{ - create_note, delete_notes, get_note, list_trash, move_notes, move_notes_back, query_notes, - restore_notes, + create_note, get_note, list_trash, move_notes_back, query_notes, restore_notes, }; use super::common::snippet; use super::{Session, code}; -fn folder(session: &Session, space_id: &str, name: &str) -> String { - let draft = FolderDraft { +const LINES: PreviewLines = PreviewLines::Four; + +fn draft(space_id: &str, parent_id: Option<&String>, name: &str) -> FolderDraft { + FolderDraft { space_id: space_id.to_string(), - parent_id: None, name: name.to_string(), - }; - - session.call(|e| create_folder(e, &draft)).unwrap().id + parent_id: parent_id.cloned(), + } } -fn board(space_id: &str) -> BoardQuery { +fn board_query(space_id: &str, root_id: Option<&String>) -> BoardQuery { BoardQuery { space_id: space_id.to_string(), - root_id: None, + root_id: root_id.cloned(), search: String::new(), filter: NoteFilter::All, tags: Vec::new(), @@ -43,533 +41,512 @@ fn board(space_id: &str) -> BoardQuery { priorities: Vec::new(), now: Utc::now(), tz_offset_minutes: 0, - preview_lines: PreviewLines::default(), + preview_lines: LINES, } } -#[test] -fn a_folder_is_created_renamed_recoloured_and_deleted() { - let session = Session::open(); - let space = session.space("Personal"); - let id = folder(&session, &space, "Scripts"); +fn list_query(space_id: &str, folder_id: Option<&String>) -> NotesQuery { + NotesQuery { + space_id: Some(space_id.to_string()), + folder_id: folder_id.cloned(), + search: String::new(), + filter: NoteFilter::All, + tags: Vec::new(), + languages: Vec::new(), + kinds: Vec::new(), + priorities: Vec::new(), + order: NoteOrder::default(), + grouping: Grouping::default(), + ranked: false, + now: Utc::now(), + tz_offset_minutes: 0, + pinned_first: true, + } +} - let renamed = session.call(|e| rename_folder(e, &id, "Shell")).unwrap(); - let recoloured = session - .call(|e| recolour_folder(e, &id, FolderColour::Amber)) - .unwrap(); - let listed = session.call(|e| list_folders(e, Some(&space))).unwrap(); - session - .call(|e| delete_folder(e, &id, PreviewLines::default(), HeldNotes::Keep)) - .unwrap(); +impl Session { + fn folder(&self, space_id: &str, parent_id: Option<&String>, name: &str) -> String { + let draft = draft(space_id, parent_id, name); + self.call(|e| create_folder(e, &draft)).unwrap().id + } - assert_eq!(renamed.name, "Shell"); - assert_eq!(recoloured.colour, FolderColour::Amber); - assert_eq!(listed.len(), 1); - assert!(session.call(|e| list_folders(e, None)).unwrap().is_empty()); + fn note(&self, space_id: &str, folder_id: Option<&String>) -> String { + let draft = NoteDraft { + folder_id: folder_id.cloned(), + ..snippet(space_id) + }; + self.call(|e| create_note(e, draft)).unwrap().note.id + } + + /// A note's space and folder, as the library has them. + fn place(&self, id: &str) -> (String, Option) { + let note = self.call(|e| get_note(e, id)).unwrap(); + (note.note.space_id, note.note.folder_id) + } + + fn board(&self, space_id: &str, root_id: Option<&String>) -> BoardView { + let query = board_query(space_id, root_id); + self.call(|e| board_view(e, &query)).unwrap() + } + + fn list(&self, space_id: &str, folder_id: Option<&String>) -> NotesView { + let query = list_query(space_id, folder_id); + self.call(|e| query_notes(e, &query)).unwrap() + } + + /// The index read whole, so a write that forgets to say what it changed leaves it stale. + fn fill_index(&self) { + self.wait(engine::index::fill); + } + + fn index_holds(&self) { + assert_eq!(self.call(Engine::index_matches_library), Ok(())); + } } -/// Checked before the lock, like every name. #[test] -fn a_folder_without_a_readable_name_is_refused() { - let session = Session::open(); - let space = session.space("Personal"); - let draft = FolderDraft { - space_id: space, - parent_id: None, - name: " ".to_string(), - }; +fn nothing_answers_before_a_library_is_open() { + let session = Session::locked(); + let work = "s".to_string(); + let named = draft(&work, None, "Infra"); + let ids = ["n".to_string()]; + let query = board_query(&work, None); + + let codes = [ + code(session.call(|e| list_folders(e, None))), + code(session.call(|e| create_folder(e, &named))), + code(session.call(|e| rename_folder(e, "f", "Ops"))), + code(session.call(|e| recolour_folder(e, "f", FolderColour::Red))), + code(session.call(|e| move_folder(e, "f", (&work, None)))), + code(session.call(|e| count_folder_contents(e, "f"))), + code(session.call(|e| delete_folder(e, "f", LINES, HeldNotes::Keep))), + code(session.call(|e| file_notes(e, &ids, None, LINES))), + code(session.call(|e| move_notes_into(e, &ids, "f", LINES))), + code(session.call(|e| file_notes_back(e, &[], LINES))), + code(session.call(|e| board_view(e, &query))), + code(session.call(|e| save_board_layout(e, None, &[], &[]))), + code(session.call(|e| arrange_board(e, &work, None, BoardScope::Everything, LINES))), + ]; - assert!(matches!( - code(session.call(|e| create_folder(e, &draft))), - ErrorCode::InvalidInput - )); + assert!( + codes.iter().all(|found| *found == ErrorCode::Locked), + "{codes:?}" + ); } +/// Checked before the lock: a name with nothing readable never reaches it. #[test] -fn a_folder_that_does_not_exist_is_named_as_such() { - let session = Session::open(); +fn a_folder_name_with_nothing_readable_is_refused_as_input_first() { + let session = Session::locked(); - assert!(matches!( - code(session.call(|e| rename_folder(e, "missing", "Shell"))), - ErrorCode::FolderNotFound - )); + assert_eq!( + code(session.call(|e| create_folder(e, &draft("s", None, " ")))), + ErrorCode::InvalidInput + ); + assert_eq!( + code(session.call(|e| rename_folder(e, "f", "\t"))), + ErrorCode::InvalidInput + ); } #[test] -fn a_filing_is_undone_by_the_filings_it_answered() { +fn a_folder_is_created_and_renamed_trimmed_and_recoloured() { let session = Session::open(); - let space = session.space("Personal"); - let zone = folder(&session, &space, "Scripts"); - let note = session - .call(|e| create_note(e, snippet(&space))) - .unwrap() - .note - .id; + let work = session.space("Work"); + let id = session.folder(&work, None, " Infra "); - let filings = session - .call(|e| { - file_notes( - e, - std::slice::from_ref(¬e), - Some(&zone), - PreviewLines::default(), - ) - }) - .unwrap(); - let filed = session.call(|e| board_view(e, &board(&space))).unwrap(); - let undone = session - .call(|e| file_notes_back(e, &filings, PreviewLines::default())) + let renamed = session.call(|e| rename_folder(e, &id, " Ops ")).unwrap(); + let recoloured = session + .call(|e| recolour_folder(e, &id, FolderColour::Red)) .unwrap(); - let unfiled = session.call(|e| board_view(e, &board(&space))).unwrap(); - assert_eq!(filed.zones[0].notes.len(), 1); - assert!(filed.loose.is_empty()); - assert_eq!(undone, 1); - assert!(unfiled.zones[0].notes.is_empty()); - assert_eq!(unfiled.loose.len(), 1); + assert_eq!(renamed.name, "Ops"); + assert_eq!(recoloured.colour, FolderColour::Red); + let listed = session.call(|e| list_folders(e, Some(&work))).unwrap(); + assert_eq!( + listed + .iter() + .map(|folder| (folder.name.as_str(), folder.colour)) + .collect::>(), + [("Ops", FolderColour::Red)] + ); } #[test] -fn notes_of_two_spaces_go_into_one_folder_and_back_where_each_was() { +fn what_cannot_be_done_is_answered_by_its_code() { let session = Session::open(); - let (home, work) = (session.space("Personal"), session.space("Work")); - let (scripts, runbooks) = ( - folder(&session, &home, "Scripts"), - folder(&session, &work, "Runbooks"), - ); - let note = |space: &str| { - session - .call(|e| create_note(e, snippet(space))) - .unwrap() - .note - .id - }; - let (filed, there) = (note(&home), note(&work)); - let ids = [filed.clone(), there.clone()]; - let lines = PreviewLines::default(); - session - .call(|e| file_notes(e, std::slice::from_ref(&filed), Some(&scripts), lines)) - .unwrap(); - let place = |id: &String| { - let note = session.call(|e| get_note(e, id)).unwrap().note; - (note.space_id, note.folder_id) - }; + let work = session.space("Work"); + let home = session.space("Home"); + let garden = session.folder(&home, None, "Garden"); + session.folder(&work, None, "Infra"); + let note = [session.note(&work, None)]; + + let cases = [ + ( + code(session.call(|e| create_folder(e, &draft("missing", None, "Infra")))), + ErrorCode::SpaceNotFound, + ), + ( + code(session.call(|e| create_folder(e, &draft(&work, None, "infra")))), + ErrorCode::DuplicateFolderName, + ), + ( + code(session.call(|e| create_folder(e, &draft(&work, Some(&garden), "Perf")))), + ErrorCode::InvalidInput, + ), + ( + code(session.call(|e| rename_folder(e, "missing", "Ops"))), + ErrorCode::FolderNotFound, + ), + ( + code(session.call(|e| recolour_folder(e, "missing", FolderColour::Red))), + ErrorCode::FolderNotFound, + ), + ( + code(session.call(|e| count_folder_contents(e, "missing"))), + ErrorCode::FolderNotFound, + ), + ( + code(session.call(|e| delete_folder(e, "missing", LINES, HeldNotes::Keep))), + ErrorCode::FolderNotFound, + ), + ( + code(session.call(|e| file_notes(e, ¬e, Some(&"missing".to_string()), LINES))), + ErrorCode::FolderNotFound, + ), + ( + code(session.call(|e| move_notes_into(e, ¬e, "missing", LINES))), + ErrorCode::FolderNotFound, + ), + ( + code(session.call(|e| { + let gone = [ZonePlacement { + folder_id: "missing".to_string(), + frame: BoardFrame { + x: 0, + y: 0, + width: 600, + height: 400, + }, + }]; + save_board_layout(e, None, &gone, &[]) + })), + ErrorCode::FolderNotFound, + ), + ]; - let moved = session - .call(|e| move_notes_into(e, &ids, &runbooks, lines)) - .unwrap(); - assert_eq!(moved.len(), 2); - for id in &ids { - assert_eq!(place(id), (work.clone(), Some(runbooks.clone()))); + for (index, (found, expected)) in cases.into_iter().enumerate() { + assert_eq!(found, expected, "case {index}"); } - let again = session.call(|e| move_notes_into(e, &ids, &runbooks, lines)); - assert!(again.unwrap().is_empty(), "already there"); - - session.call(|e| move_notes_back(e, &moved)).unwrap(); - assert_eq!(place(&filed), (home.clone(), Some(scripts))); - assert_eq!(place(&there), (work.clone(), None)); - assert!(matches!( - code(session.call(|e| move_notes_into(e, &ids, "missing", lines))), - ErrorCode::FolderNotFound - )); - - // To the space it is in: out of its folder, and back in with the undo. - let out = session.call(|e| move_notes(e, &ids, &home)).unwrap(); - assert_eq!(out.len(), 2); - assert_eq!(place(&filed), (home.clone(), None)); - session.call(|e| move_notes_back(e, &out)).unwrap(); - assert!(place(&filed).1.is_some() && place(&there).1.is_none()); } -/// A layout saved by hand is the one a tidy-up answers as `previous`, for its undo. +/// Its sub-tree and every note filed in it go along, in the index too; the undo brings them back. #[test] -fn a_saved_layout_is_what_a_tidy_up_hands_back() { +fn a_folder_moved_to_another_space_takes_its_notes_and_comes_back_with_them() { let session = Session::open(); - let space = session.space("Personal"); - let zone = folder(&session, &space, "Scripts"); - let frame = BoardFrame { - x: 960, - y: 640, - width: MIN_ZONE_WIDTH * 2, - height: MIN_ZONE_HEIGHT * 2, - }; - let placement = ZonePlacement { - folder_id: zone.clone(), - frame, - }; + let work = session.space("Work"); + let home = session.space("Home"); + let infra = session.folder(&work, None, "Infra"); + let perf = session.folder(&work, Some(&infra), "Perf"); + let id = session.note(&work, Some(&perf)); + session.fill_index(); - session - .call(|e| save_board_layout(e, None, &[placement], &Vec::new())) - .unwrap(); - let saved = session.call(|e| board_view(e, &board(&space))).unwrap(); - let arranged = session - .call(|e| { - arrange_board( - e, - &space, - None, - BoardScope::Everything, - PreviewLines::default(), - ) - }) + let was = session + .call(|e| move_folder(e, &infra, (&home, None))) .unwrap(); - assert_eq!(saved.zones[0].frame, frame); - assert_eq!(arranged.previous.zones[0].folder_id, zone); - assert_eq!(arranged.previous.zones[0].frame, frame); + assert_eq!(was.notes, std::slice::from_ref(&id)); + assert_eq!(session.place(&id), (home, Some(perf.clone()))); + session.index_holds(); + assert!(session.call(|e| move_folder_back(e, &was)).unwrap()); + assert_eq!(session.place(&id), (work, Some(perf))); + session.index_holds(); } -fn notes_query(space_id: &str) -> NotesQuery { - NotesQuery { - space_id: Some(space_id.to_string()), - folder_id: None, - search: String::new(), - filter: NoteFilter::All, - tags: Vec::new(), - languages: Vec::new(), - kinds: Vec::new(), - priorities: Vec::new(), - order: NoteOrder::default(), - grouping: Grouping::default(), - ranked: false, - now: Utc::now(), - tz_offset_minutes: 0, - pinned_first: true, - } -} +#[test] +fn a_folder_moved_under_another_lands_there_with_what_it_holds() { + let session = Session::open(); + let work = session.space("Work"); + let docs = session.folder(&work, None, "Docs"); + let infra = session.folder(&work, None, "Infra"); + let perf = session.folder(&work, Some(&infra), "Perf"); -fn sub_folder(session: &Session, space_id: &str, parent: &str, name: &str) -> String { - let draft = FolderDraft { - space_id: space_id.to_string(), - parent_id: Some(parent.to_string()), - name: name.to_string(), - }; + session + .call(|e| move_folder(e, &infra, (&work, Some(&docs)))) + .unwrap(); - session.call(|e| create_folder(e, &draft)).unwrap().id + let parents: Vec<(String, Option)> = session + .call(|e| list_folders(e, Some(&work))) + .unwrap() + .into_iter() + .map(|folder| (folder.id, folder.parent_id)) + .collect(); + assert!(parents.contains(&(infra.clone(), Some(docs)))); + assert!(parents.contains(&(perf, Some(infra)))); } -fn filed_note(session: &Session, space_id: &str, folder_id: &str) -> String { - let id = session - .call(|e| create_note(e, snippet(space_id))) - .unwrap() - .note - .id; +/// Its old parent gone, it stays where it is: `false`, and no error. +#[test] +fn a_move_whose_old_parent_is_gone_is_not_undone() { + let session = Session::open(); + let work = session.space("Work"); + let docs = session.folder(&work, None, "Docs"); + let infra = session.folder(&work, Some(&docs), "Infra"); + let was = session + .call(|e| move_folder(e, &infra, (&work, None))) + .unwrap(); session - .call(|e| { - file_notes( - e, - std::slice::from_ref(&id), - Some(&folder_id.to_string()), - PreviewLines::default(), - ) - }) + .call(|e| delete_folder(e, &docs, LINES, HeldNotes::Keep)) .unwrap(); - id + + assert!(!session.call(|e| move_folder_back(e, &was)).unwrap()); } -/// On the board, a card names its folder only when it comes from below its zone, by the deepest -/// folder and its path; inside an opened folder, the same. #[test] -fn a_card_names_the_sub_folder_it_comes_from_and_no_other() { +fn a_folder_counts_the_live_notes_under_it_and_its_sub_folders() { let session = Session::open(); - let space = session.space("Personal"); - let sql = folder(&session, &space, "SQL"); - let perf = sub_folder(&session, &space, &sql, "Perf"); - let own = filed_note(&session, &space, &sql); - let deeper = filed_note(&session, &space, &perf); + let work = session.space("Work"); + let infra = session.folder(&work, None, "Infra"); + let perf = session.folder(&work, Some(&infra), "Perf"); + session.note(&work, Some(&infra)); + session.note(&work, Some(&perf)); - let board = session.call(|e| board_view(e, &board(&space))).unwrap(); - let chip = |id: &str| { - board.zones[0] - .notes - .iter() - .find(|entry| entry.note.id == id) - .and_then(|entry| entry.note.folder.clone()) - }; - assert!(chip(&own).is_none()); - let named = chip(&deeper).unwrap(); - assert_eq!(named.name, "Perf"); - assert_eq!(named.path, ["SQL", "Perf"]); - assert_eq!(board.zones[0].children[0].name, "Perf"); - - let mut inside = notes_query(&space); - inside.folder_id = Some(sql.clone()); - let view = session.call(|e| query_notes(e, &inside)).unwrap(); - let chips: Vec> = view.sections[0] - .cards - .iter() - .map(|card| { - view.display(card) - .folder - .as_ref() - .map(|folder| folder.name.clone()) - }) - .collect(); - assert_eq!(chips.len(), 2); - assert!(chips.contains(&None) && chips.contains(&Some("Perf".to_string()))); + assert_eq!( + session.call(|e| count_folder_contents(e, &infra)).unwrap(), + FolderContents { + notes: 2, + folders: 1 + } + ); } +/// Kept, its notes go to its parent; the index follows. #[test] -fn a_folder_moved_into_another_comes_back_with_its_undo() { +fn a_folder_deleted_keeping_its_notes_hands_them_to_its_parent() { let session = Session::open(); - let space = session.space("Personal"); - let sql = folder(&session, &space, "SQL"); - let perf = folder(&session, &space, "Perf"); + let work = session.space("Work"); + let infra = session.folder(&work, None, "Infra"); + let perf = session.folder(&work, Some(&infra), "Perf"); + let id = session.note(&work, Some(&perf)); + session.fill_index(); - let was = session - .call(|e| move_folder(e, &perf, (&space, Some(&sql)))) + let held = session + .call(|e| delete_folder(e, &perf, LINES, HeldNotes::Keep)) .unwrap(); - let nested = session.call(|e| board_view(e, &board(&space))).unwrap(); - let refused = session.call(|e| move_folder(e, &sql, (&space, Some(&perf)))); - let back = session.call(|e| move_folder_back(e, &was)).unwrap(); - let flat = session.call(|e| board_view(e, &board(&space))).unwrap(); - - assert_eq!(nested.zones.len(), 1); - assert_eq!(nested.zones[0].children[0].id, perf); - assert!(matches!(code(refused), ErrorCode::InvalidInput)); - assert!(back); - assert_eq!(flat.zones.len(), 2); + + assert_eq!(held, 1); + assert_eq!(session.place(&id), (work, Some(infra))); + session.index_holds(); } -/// Into another space, a folder takes its sub-folder and every note filed in it, the trashed one -/// included; its undo brings exactly that back. +/// Nothing is erased: trashed, its notes come back loose in the space. #[test] -fn a_folder_moved_into_another_space_takes_its_tree_and_notes_and_comes_back() { +fn a_folder_deleted_with_its_notes_sends_them_to_the_trash_to_come_back_loose() { let session = Session::open(); let work = session.space("Work"); - let home = session.space("Home"); - let sql = folder(&session, &work, "SQL"); - let perf = sub_folder(&session, &work, &sql, "Perf"); - let filed = filed_note(&session, &work, &sql); - let deeper = filed_note(&session, &work, &perf); - let trashed = filed_note(&session, &work, &perf); - let loose = session - .call(|e| create_note(e, snippet(&work))) - .unwrap() - .note - .id; + let infra = session.folder(&work, None, "Infra"); + let id = session.note(&work, Some(&infra)); + session.fill_index(); + + let held = session + .call(|e| delete_folder(e, &infra, LINES, HeldNotes::Trash)) + .unwrap(); + + assert_eq!(held, 1); + assert_eq!(session.call(|e| list_trash(e, "")).unwrap().len(), 1); + session.index_holds(); session - .call(|e| delete_notes(e, std::slice::from_ref(&trashed))) + .call(|e| restore_notes(e, std::slice::from_ref(&id))) .unwrap(); - let placed = |id: &str| { - let note = session.call(|e| get_note(e, id)).unwrap(); - (note.space_id.clone(), note.folder_id.clone()) - }; + assert_eq!(session.place(&id), (work, None)); +} - let was = session - .call(|e| move_folder(e, &sql, (&home, None))) +#[test] +fn a_filing_answers_where_each_note_was_and_its_undo_puts_them_back() { + let session = Session::open(); + let work = session.space("Work"); + let infra = session.folder(&work, None, "Infra"); + let ids = [session.note(&work, None), session.note(&work, None)]; + session.fill_index(); + + let filings = session + .call(|e| file_notes(e, &ids, Some(&infra), LINES)) .unwrap(); - assert_eq!(was.space_id, work); - assert_eq!(was.notes.len(), 3); - let folders = session.call(|e| list_folders(e, Some(&home))).unwrap(); - assert_eq!(folders.len(), 2); + assert_eq!(filings.len(), 2); assert!( - session - .call(|e| list_folders(e, Some(&work))) - .unwrap() - .is_empty() + ids.iter() + .all(|id| session.place(id).1.as_ref() == Some(&infra)) ); - assert_eq!(placed(&filed), (home.clone(), Some(sql.clone()))); - assert_eq!(placed(&deeper), (home.clone(), Some(perf.clone()))); - assert_eq!(placed(&loose).0, work); - let listed = |space: &str| { - let view = session - .call(|e| query_notes(e, ¬es_query(space))) - .unwrap(); - view.sections - .iter() - .map(|section| section.cards.len()) - .sum::() - }; - assert_eq!(listed(&home), 2); - session - .call(|e| restore_notes(e, std::slice::from_ref(&trashed))) + session.index_holds(); + let undone = session + .call(|e| file_notes_back(e, &filings, LINES)) .unwrap(); - assert_eq!(placed(&trashed), (home.clone(), Some(perf.clone()))); + assert_eq!(undone, 2); + assert!(ids.iter().all(|id| session.place(id).1.is_none())); + session.index_holds(); +} - assert!(session.call(|e| move_folder_back(e, &was)).unwrap()); - assert_eq!(placed(&filed), (work.clone(), Some(sql.clone()))); - assert_eq!(placed(&trashed), (work.clone(), Some(perf.clone()))); - assert_eq!( - session - .call(|e| list_folders(e, Some(&work))) - .unwrap() - .len(), - 2 - ); - assert!( - session - .call(|e| list_folders(e, Some(&home))) - .unwrap() - .is_empty() - ); +/// From any space, each answered where it was; one already there is left out. The notes' own +/// move back undoes it. +#[test] +fn notes_moved_into_a_folder_join_its_space_until_the_move_is_undone() { + let session = Session::open(); + let home = session.space("Home"); + let work = session.space("Work"); + let scripts = session.folder(&home, None, "Scripts"); + let runbooks = session.folder(&work, None, "Runbooks"); + let filed = session.note(&home, Some(&scripts)); + let loose = session.note(&work, None); + let ids = [filed.clone(), loose.clone()]; + session.fill_index(); + + let placements = session + .call(|e| move_notes_into(e, &ids, &runbooks, LINES)) + .unwrap(); + + assert_eq!(placements.len(), 2); + for id in &ids { + assert_eq!(session.place(id), (work.clone(), Some(runbooks.clone()))); + } + let again = session.call(|e| move_notes_into(e, &ids, &runbooks, LINES)); + assert!(again.unwrap().is_empty()); + session.index_holds(); + session.call(|e| move_notes_back(e, &placements)).unwrap(); + assert_eq!(session.place(&filed), (home, Some(scripts))); + assert_eq!(session.place(&loose), (work, None)); + session.index_holds(); } -/// Into another space, a name taken among the new siblings or a tree too deep there is refused, -/// and nothing moves. +/// The zone says where a card is; only a card from below it names its folder, by its path. #[test] -fn a_folder_that_cannot_go_into_another_space_moves_nothing() { +fn the_board_draws_the_zones_and_names_a_card_s_folder_only_from_below() { let session = Session::open(); let work = session.space("Work"); - let home = session.space("Home"); - let sql = folder(&session, &work, "SQL"); - let filed = filed_note(&session, &work, &sql); - folder(&session, &home, "SQL"); + let infra = session.folder(&work, None, "Infra"); + let perf = session.folder(&work, Some(&infra), "Perf"); + let own = session.note(&work, Some(&infra)); + let deeper = session.note(&work, Some(&perf)); + session.note(&work, None); + + let board = session.board(&work, None); - let taken = session.call(|e| move_folder(e, &sql, (&home, None))); + let chip = |id: &str| { + let entry = board.zones[0] + .notes + .iter() + .find(|entry| entry.note.note.id == id); + entry.and_then(|entry| entry.note.folder.clone()) + }; + assert_eq!(board.zones.len(), 1); + assert!(chip(&own).is_none()); + assert_eq!(chip(&deeper).unwrap().path, ["Infra", "Perf"]); + assert_eq!(board.loose.len(), 1); + assert!(board.loose[0].note.folder.is_none()); +} - assert!(matches!(code(taken), ErrorCode::DuplicateFolderName)); - let note = session.call(|e| get_note(e, &filed)).unwrap(); - assert_eq!(note.space_id, work); +/// The list inside an opened folder follows the same rule as its zone. +#[test] +fn an_opened_folder_s_list_names_only_the_folders_below_it() { + let session = Session::open(); + let work = session.space("Work"); + let infra = session.folder(&work, None, "Infra"); + let perf = session.folder(&work, Some(&infra), "Perf"); + session.note(&work, Some(&infra)); + session.note(&work, Some(&perf)); - let mut parent = folder(&session, &home, "Deep"); - for level in 1..engine::folders::model::MAX_DEPTH { - parent = sub_folder(&session, &home, &parent, &format!("L{level}")); - } - let deep = session.call(|e| move_folder(e, &sql, (&home, Some(&parent)))); - assert!(matches!(code(deep), ErrorCode::InvalidInput)); - assert_eq!( - session - .call(|e| list_folders(e, Some(&work))) - .unwrap() - .len(), - 1 - ); + let view = session.list(&work, Some(&infra)); + + let chips: Vec> = view + .cards() + .map(|card| { + view.display(card) + .folder + .as_ref() + .map(|chip| chip.name.clone()) + }) + .collect(); + assert_eq!(chips.len(), 2); + assert!(chips.contains(&None) && chips.contains(&Some("Perf".to_string()))); } /// A sheet's `aujourd'hui` is the local day on the board as in the list: at 00:30 at UTC+2, -/// both read the same date (#1478, N16). +/// both read the same date. #[test] fn the_board_reads_today_as_the_list_does() { let session = Session::open(); - let space = session.space("Personal"); - let draft = engine::notes::model::NoteDraft { + let work = session.space("Work"); + let sheet = NoteDraft { kind: engine::notes::kind::NoteKind::Calc, content: "jour = aujourd'hui".to_string(), - ..snippet(&space) + ..snippet(&work) }; - session.call(|e| create_note(e, draft)).unwrap(); + session.call(|e| create_note(e, sheet)).unwrap(); let now = chrono::DateTime::parse_from_rfc3339("2026-07-25T22:30:00Z") .unwrap() .with_timezone(&Utc); - - let listed = session - .call(|e| { - query_notes( - e, - &NotesQuery { - now, - tz_offset_minutes: -120, - ..notes_query(&space) - }, - ) - }) - .unwrap(); - let on_board = session - .call(|e| { - board_view( - e, - &BoardQuery { - now, - tz_offset_minutes: -120, - ..board(&space) - }, - ) - }) - .unwrap(); - - let list_card = listed.display(listed.cards().next().unwrap()).calc.clone(); - let board_card = on_board.loose[0].note.calc.clone(); - assert_eq!(board_card, list_card); -} - -fn nested(session: &Session, space_id: &str, parent: &str, name: &str) -> String { - let draft = FolderDraft { - space_id: space_id.to_string(), - parent_id: Some(parent.to_string()), - name: name.to_string(), + let in_list = NotesQuery { + now, + tz_offset_minutes: -120, + ..list_query(&work, None) + }; + let on_board = BoardQuery { + now, + tz_offset_minutes: -120, + ..board_query(&work, None) }; - session.call(|e| create_folder(e, &draft)).unwrap().id -} + let listed = session.call(|e| query_notes(e, &in_list)).unwrap(); + let board = session.call(|e| board_view(e, &on_board)).unwrap(); -fn filed(session: &Session, space_id: &str, folder: &str) -> String { - let id = session - .call(|e| create_note(e, snippet(space_id))) - .unwrap() - .note - .id; - let ids = [id.clone()]; - let into = folder.to_string(); - session - .call(|e| file_notes(e, &ids, Some(&into), PreviewLines::default())) - .unwrap(); - id + let card = listed.display(listed.cards().next().unwrap()); + assert_eq!(board.loose[0].note.calc, card.calc); } -/// What the panel names before the second click: every live note under it, and its sub-folders. +/// A read that writes, once: the first layout is what the next read hands back. #[test] -fn a_folder_counts_what_is_under_it() { +fn the_board_s_first_layout_is_kept_for_the_next_read() { let session = Session::open(); - let space = session.space("Personal"); - let ops = folder(&session, &space, "Ops"); - let deep = nested(&session, &space, &ops, "Deep"); - filed(&session, &space, &ops); - filed(&session, &space, &deep); + let work = session.space("Work"); + session.folder(&work, None, "Infra"); + session.note(&work, None); - let contents = session.call(|e| count_folder_contents(e, &ops)).unwrap(); + let first = session.board(&work, None); + let again = session.board(&work, None); - assert_eq!((contents.notes, contents.folders), (2, 1)); + assert_eq!(first.zones[0].frame, again.zones[0].frame); + assert_eq!(first.loose[0].position, again.loose[0].position); } -/// Its whole subtree goes, every note under it waits in the trash, and comes back loose. +/// The undo of a tidy-up is a save of the layout it answered. #[test] -fn a_folder_deleted_with_its_notes_takes_its_sub_folders_and_trashes_them() { +fn a_tidy_up_answers_the_layout_it_replaced_and_saving_that_puts_the_board_back() { let session = Session::open(); - let space = session.space("Personal"); - let ops = folder(&session, &space, "Ops"); - let deep = nested(&session, &space, &ops, "Deep"); - let kept = folder(&session, &space, "Kept"); - let mut held = vec![ - filed(&session, &space, &ops), - filed(&session, &space, &deep), - ]; - let other = filed(&session, &space, &kept); - let loose = session - .call(|e| create_note(e, snippet(&space))) - .unwrap() - .note - .id; + let work = session.space("Work"); + let infra = session.folder(&work, None, "Infra"); + let by_hand = BoardFrame { + x: 2_000, + y: 2_000, + width: 900, + height: 900, + }; + let zones = [ZonePlacement { + folder_id: infra.clone(), + frame: by_hand, + }]; + session + .call(|e| save_board_layout(e, None, &zones, &[])) + .unwrap(); - let trashed = session - .call(|e| delete_folder(e, &ops, PreviewLines::default(), HeldNotes::Trash)) + let done = session + .call(|e| arrange_board(e, &work, None, BoardScope::Everything, LINES)) .unwrap(); - assert_eq!(trashed, 2); - let left: Vec = session - .call(|e| list_folders(e, Some(&space))) - .unwrap() - .into_iter() - .map(|folder| folder.id) - .collect(); - assert_eq!(left, std::slice::from_ref(&kept)); - let mut in_trash: Vec = session - .call(|e| list_trash(e, "")) - .unwrap() - .into_iter() - .map(|row| row.note.id) - .collect(); - in_trash.sort(); - held.sort(); - assert_eq!(in_trash, held); - assert!(session.call(|e| get_note(e, &other)).is_ok()); - assert!(session.call(|e| get_note(e, &loose)).is_ok()); - - session.call(|e| restore_notes(e, &held)).unwrap(); - for id in &held { - let back = session.call(|e| get_note(e, id)).unwrap(); - assert_eq!(back.note.space_id, space); - assert_eq!(back.note.folder_id, None, "loose in its space"); - } + assert_eq!(done.moved, 1); + assert_ne!(session.board(&work, None).zones[0].frame, by_hand); + let previous = done.previous; + session + .call(|e| save_board_layout(e, None, &previous.zones, &previous.cards)) + .unwrap(); + assert_eq!(session.board(&work, None).zones[0].frame, by_hand); } From 1878fd484ae60af4e8d7d1b84b5a7fa57da2df52 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:57:44 +0100 Subject: [PATCH 25/95] Attachments: unit tests rewritten (#1746) * Rewrite the tests of attachments around their rules Co-Authored-By: Claude Opus 5.5 * Fill the index before the writes whose declaration is checked Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/attachments.rs | 26 -- crates/engine/src/attachments/files.rs | 225 ++++++++--------- crates/engine/src/attachments/model.rs | 236 +++++++++++------- crates/engine/src/attachments/sealed.rs | 11 - crates/engine/src/attachments/store.rs | 254 ++++++++++++++----- crates/engine/tests/commands/attachments.rs | 259 ++++++++++++++------ 6 files changed, 650 insertions(+), 361 deletions(-) diff --git a/crates/engine/src/attachments.rs b/crates/engine/src/attachments.rs index 774f11918..bee45db98 100644 --- a/crates/engine/src/attachments.rs +++ b/crates/engine/src/attachments.rs @@ -130,29 +130,3 @@ fn delete(db: &Db, id: &str) -> Result<(), StorageError> { Ok(()) } - -#[cfg(test)] -mod tests { - use super::*; - use files::tests::{a_library_with_a_note, attachments_of}; - - #[test] - fn deleting_an_attachment_takes_its_file_with_it() { - let (_scratch, db, note_id) = a_library_with_a_note(); - let directory = attachments_of(&db); - let stored = store_new(note_id.clone(), "capture.png".to_string(), b"png", &db).unwrap(); - - delete(&db, &stored.id).unwrap(); - - assert!(!directory.join(stored.stored_name()).exists()); - assert!( - store::list(&mut lock(&db).unwrap(), ¬e_id) - .unwrap() - .is_empty() - ); - assert!(matches!( - delete(&db, &stored.id), - Err(StorageError::AttachmentNotFound(_)) - )); - } -} diff --git a/crates/engine/src/attachments/files.rs b/crates/engine/src/attachments/files.rs index b0da4be63..54e14ad23 100644 --- a/crates/engine/src/attachments/files.rs +++ b/crates/engine/src/attachments/files.rs @@ -152,174 +152,177 @@ pub fn sweep_orphan_files(db: &Db) -> Result { pub(crate) mod tests { use super::*; + /// A library on disk, its attachments directory made, holding one note: answered with the + /// scratch directory that must outlive it, and the note's id. pub(crate) fn a_library_with_a_note() -> (tempfile::TempDir, Db, String) { - use crate::notes::model::NoteDraft; - let scratch = tempfile::tempdir().unwrap(); let mut library = crate::db::open_in_memory() .unwrap() .with_directory(scratch.path().to_path_buf()); - let space = crate::spaces::store::create(&mut library, "Personal").unwrap(); - let note = crate::notes::store::create( - &mut library, - NoteDraft { - space_id: space.id, - folder_id: None, - title: "T".to_string(), - language: crate::notes::language::Language::Txt, - content: String::new(), - source: String::new(), - tags: Vec::new(), - pinned: false, - lifecycle: crate::notes::model::NoteLifecycle::Permanent, - kind: crate::notes::kind::NoteKind::Snippet, - priority: crate::notes::priority::Priority::None, - items: Vec::new(), - }, - Utc::now(), - ) - .unwrap(); + let space = crate::spaces::store::create(&mut library, "Work").unwrap(); + let draft = crate::notes::model::NoteDraft { + folder_id: None, + title: "T".to_string(), + language: crate::notes::language::Language::Txt, + content: String::new(), + source: String::new(), + tags: Vec::new(), + pinned: false, + lifecycle: crate::notes::model::NoteLifecycle::Permanent, + kind: crate::notes::kind::NoteKind::Snippet, + priority: crate::notes::priority::Priority::None, + items: Vec::new(), + space_id: space.id, + }; + let note = crate::notes::store::create(&mut library, draft, Utc::now()).unwrap(); + std::fs::create_dir_all(directory(&library)).unwrap(); (scratch, std::sync::Mutex::new(Some(library)), note.id) } pub(crate) fn attachments_of(db: &Db) -> PathBuf { - let directory = directory(&lock(db).unwrap()); - std::fs::create_dir_all(&directory).unwrap(); + directory(&lock(db).unwrap()) + } - directory + fn listed(db: &Db, note_id: &str) -> Vec { + store::list(&mut lock(db).unwrap(), note_id).unwrap() } #[test] - fn a_new_attachment_is_sealed_beside_the_library_then_recorded() { - let (_scratch, db, note_id) = a_library_with_a_note(); - let directory = attachments_of(&db); - let attachment = - store_new(note_id.clone(), "capture.png".to_string(), b"png", &db).unwrap(); + fn attachments_live_in_the_library_s_own_directory() { + let (scratch, db, _) = a_library_with_a_note(); - let written = std::fs::read(directory.join(attachment.stored_name())).unwrap(); - assert_ne!(written, b"png"); - let listed = store::list(&mut lock(&db).unwrap(), ¬e_id).unwrap(); - assert_eq!(listed[0].mime_type, "image/png"); + assert_eq!( + attachments_of(&db), + scratch.path().join(crate::layout::ATTACHMENTS) + ); } - /// A file without a record would sit there until the next launch's sweep. + /// Sealed like the rows beside it: the plain bytes are nowhere on disk. #[test] - fn an_attachment_that_cannot_be_recorded_leaves_no_file_behind() { - let (_scratch, db, _) = a_library_with_a_note(); - let directory = attachments_of(&db); - let refused = store_new("ghost".to_string(), "capture.png".to_string(), b"png", &db); + fn a_new_attachment_is_sealed_on_disk_and_recorded_with_its_plain_size_and_type() { + let (_scratch, db, note_id) = a_library_with_a_note(); + let bytes = b"a credentials page"; + + let stored = store_new(note_id.clone(), "capture.png".to_string(), bytes, &db).unwrap(); - assert!(matches!(refused, Err(StorageError::NoteNotFound(_)))); - assert_eq!(std::fs::read_dir(&directory).unwrap().count(), 0); + let on_disk = std::fs::read(attachments_of(&db).join(stored.stored_name())).unwrap(); + assert!(!on_disk.windows(bytes.len()).any(|window| window == bytes)); + assert_eq!( + (stored.byte_size, stored.mime_type.as_str()), + (18, "image/png") + ); + assert_eq!(listed(&db, ¬e_id)[0].id, stored.id); } + /// A file without a record would only be swept later; none is left behind. #[test] - fn an_attachment_reads_back_as_the_bytes_it_was_given() { - let (_scratch, db, note_id) = a_library_with_a_note(); - attachments_of(&db); - let stored = store_new(note_id, "capture.png".to_string(), b"png", &db).unwrap(); + fn an_attachment_of_a_note_not_there_leaves_no_file() { + let (_scratch, db, _) = a_library_with_a_note(); - let (attachment, bytes) = read_plain(&mut lock(&db).unwrap(), &stored.id).unwrap(); + let refused = store_new( + "missing".to_string(), + "capture.png".to_string(), + b"png", + &db, + ); - assert_eq!(attachment.id, stored.id); - assert_eq!(bytes, b"png"); + assert!(matches!(refused, Err(StorageError::NoteNotFound(id)) if id == "missing")); + assert_eq!(std::fs::read_dir(attachments_of(&db)).unwrap().count(), 0); } - /// The read commands' path: the same bytes, and the lock free again once they are in hand. #[test] - fn an_attachment_read_outside_the_lock_leaves_it_free() { + fn an_attachment_is_read_back_opened_with_its_record() { let (_scratch, db, note_id) = a_library_with_a_note(); - attachments_of(&db); - let stored = store_new(note_id, "capture.png".to_string(), b"png", &db).unwrap(); + let stored = store_new(note_id, "notes.txt".to_string(), b"plain", &db).unwrap(); - let (attachment, bytes) = read_outside_lock(&db, &stored.id).unwrap(); + let (record, bytes) = read_plain(&mut lock(&db).unwrap(), &stored.id).unwrap(); + let (_, outside) = read_outside_lock(&db, &stored.id).unwrap(); assert_eq!( - (attachment.id, bytes.as_slice()), - (stored.id, b"png".as_slice()) + (record.file_name.as_str(), bytes.as_slice()), + ("notes.txt", &b"plain"[..]) + ); + assert_eq!(outside, b"plain"); + assert!( + db.try_lock().is_ok(), + "the lock is free once the bytes are in hand" ); - assert!(db.try_lock().is_ok()); - assert!(matches!( - read_outside_lock(&db, "unknown"), - Err(StorageError::AttachmentNotFound(_)) - )); } + /// Opening a file nothing refers to would read outside what the library knows. #[test] - fn two_decrypted_copies_of_the_same_name_do_not_overwrite_each_other() { - let (scratch, db, note_id) = a_library_with_a_note(); - attachments_of(&db); - let first = store_new(note_id.clone(), "capture.png".to_string(), b"1", &db).unwrap(); - let second = store_new(note_id, "capture.png".to_string(), b"2", &db).unwrap(); - let open = scratch.path().join("open"); - - let one = write_plaintext_copy(&open, &first, b"1").unwrap(); - let two = write_plaintext_copy(&open, &second, b"2").unwrap(); + fn a_file_no_record_names_is_never_read() { + let (_scratch, db, _) = a_library_with_a_note(); + std::fs::write(attachments_of(&db).join("stray"), b"stray").unwrap(); - assert_ne!(one, two); - assert_eq!(one.file_name().unwrap(), "capture.png"); - assert_eq!(std::fs::read(one).unwrap(), b"1"); - assert_eq!(std::fs::read(two).unwrap(), b"2"); + for id in ["stray", "missing"] { + assert!(matches!( + read_outside_lock(&db, id), + Err(StorageError::AttachmentNotFound(_)) + )); + } } + /// One byte past the limit is enough to refuse: a growing file cannot outrun the read. #[test] - fn an_attachment_nobody_recorded_is_not_read() { - let (_scratch, db, _) = a_library_with_a_note(); + fn a_source_is_read_one_byte_past_the_limit_at_most() { + let scratch = tempfile::tempdir().unwrap(); + let source = scratch.path().join("big.bin"); + let too_long = usize::try_from(model::MAX_BYTES).unwrap() + 10; + std::fs::write(&source, vec![0u8; too_long]).unwrap(); - let refused = read_plain(&mut lock(&db).unwrap(), "../vault"); + let read = read_within_limit(&source.to_string_lossy()).unwrap(); - assert!(matches!(refused, Err(StorageError::AttachmentNotFound(_)))); + assert_eq!(read.len() as u64, model::MAX_BYTES + 1); + let missing = scratch.path().join("missing.bin"); + assert!(matches!( + read_within_limit(&missing.to_string_lossy()), + Err(StorageError::File(_)) + )); } + /// Two copies of one name do not overwrite each other. #[test] - fn the_sweep_removes_the_files_no_record_claims_and_only_those() { + fn an_opened_copy_is_written_in_the_clear_in_a_folder_of_its_own() { let (_scratch, db, note_id) = a_library_with_a_note(); - let directory = attachments_of(&db); - let kept = store_new(note_id, "capture.png".to_string(), b"png", &db).unwrap(); - std::fs::write(directory.join("orphan.png"), b"left behind").unwrap(); + let copies = tempfile::tempdir().unwrap(); + let first = store_new(note_id.clone(), "capture.png".to_string(), b"one", &db).unwrap(); + let second = store_new(note_id, "capture.png".to_string(), b"two", &db).unwrap(); - assert_eq!(sweep_orphan_files(&db).unwrap(), 1); + let one = write_plaintext_copy(copies.path(), &first, b"one").unwrap(); + let two = write_plaintext_copy(copies.path(), &second, b"two").unwrap(); - assert!(directory.join(kept.stored_name()).exists()); - assert!(!directory.join("orphan.png").exists()); + assert_eq!(one, copies.path().join(first.opened_copy())); + assert_ne!(one, two); + assert_eq!(std::fs::read(&one).unwrap(), b"one"); + assert_eq!(std::fs::read(&two).unwrap(), b"two"); } + /// That is what "save as" means. #[test] - fn a_file_within_the_limit_is_read_whole() { + fn a_saved_attachment_is_written_in_the_clear_where_asked() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let source = directory.join("capture.png"); - std::fs::write(&source, vec![7u8; 2048]).unwrap(); + let path = scratch.path().join("saved.txt"); - let bytes = read_within_limit(&source.to_string_lossy()).unwrap(); + write_plain(&path.to_string_lossy(), b"plain").unwrap(); - assert_eq!(bytes, vec![7u8; 2048]); + assert_eq!(std::fs::read(&path).unwrap(), b"plain"); } - /// A file that grew past the limit is still refused, and no more than one byte past it is - /// ever held. + /// An interrupted copy or a purge cut short leaves one; a file already gone is no error. #[test] - fn a_file_over_the_limit_is_read_one_byte_past_it_and_refused() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let source = directory.join("huge.bin"); - let limit = usize::try_from(model::MAX_BYTES).unwrap(); - std::fs::write(&source, vec![0u8; limit + 10]).unwrap(); - - let bytes = read_within_limit(&source.to_string_lossy()).unwrap(); - - assert_eq!(bytes.len(), limit + 1); - assert!(matches!( - model::validate_size(bytes.len() as u64, "huge.bin"), - Err(StorageError::TooLarge { .. }) - )); - } + fn the_sweep_removes_the_files_no_record_claims_and_keeps_the_others() { + let (_scratch, db, note_id) = a_library_with_a_note(); + let directory = attachments_of(&db); + let kept = store_new(note_id, "capture.png".to_string(), b"png", &db).unwrap(); + std::fs::write(directory.join("orphan.png"), b"orphan").unwrap(); - #[test] - fn a_missing_source_is_reported_rather_than_panicking() { - let error = read_within_limit("no-such-file.png").unwrap_err(); + let swept = sweep_orphan_files(&db).unwrap(); - assert!(matches!(error, StorageError::File(_)), "{error}"); + assert_eq!(swept, 1); + assert!(!directory.join("orphan.png").exists()); + assert!(directory.join(kept.stored_name()).exists()); + remove_files(&directory, &["orphan.png".to_string()]); } } diff --git a/crates/engine/src/attachments/model.rs b/crates/engine/src/attachments/model.rs index 62ea23f90..cd7a875d3 100644 --- a/crates/engine/src/attachments/model.rs +++ b/crates/engine/src/attachments/model.rs @@ -216,63 +216,43 @@ pub fn validate_size(byte_size: u64, name: &str) -> Result { #[cfg(test)] mod tests { - use std::path::Path; - use super::*; - #[test] - fn the_stored_name_comes_from_the_identifier_not_from_the_user() { - assert_eq!(stored_name("a-1", "capture.png"), "a-1.png"); - assert_eq!(stored_name("a-2", "capture.png"), "a-2.png"); - } - - fn opened(id: &str, file_name: &str) -> PathBuf { + fn attachment(id: &str, file_name: &str) -> Attachment { Attachment { id: id.to_string(), - note_id: "n".to_string(), + note_id: "n-1".to_string(), file_name: file_name.to_string(), mime_type: mime_of(file_name), - byte_size: 1, - created_at: Utc::now(), + byte_size: 3, + created_at: DateTime::::UNIX_EPOCH, } - .opened_copy() } #[test] - fn an_opened_copy_keeps_its_own_name_in_a_folder_of_its_own() { - assert_eq!( - opened("7d44d90f", "image-test.png"), - Path::new("7d44d90f").join("image-test.png") - ); - assert_eq!(opened("../x", "a:b?.png"), Path::new("x").join("a_b_.png")); - assert_eq!(opened("a", "notes. "), Path::new("a").join("notes")); - } - - #[test] - fn a_name_windows_will_not_write_falls_back_on_the_stored_one() { - assert_eq!(opened("a", "CON.txt"), Path::new("a").join("a.txt")); - assert_eq!(opened("a", "lpt1"), Path::new("a").join("a")); - assert_eq!(opened("a", "..."), Path::new("a").join("a")); - let long = format!("{}.png", "x".repeat(300)); - let cut = opened("a", &long); - let name = cut.file_name().unwrap().to_string_lossy(); - assert_eq!(name.chars().count(), 100); - assert!(name.ends_with(".png")); - } - - #[test] - fn a_hostile_extension_is_dropped_rather_than_written() { - for name in ["x.../../evil", "x.p g", "x.", "x.verylongextension"] { - assert_eq!(stored_name("a-1", name), "a-1"); + fn a_stored_name_is_the_id_and_the_extension_lowercased() { + let cases = [ + ("a-1", "Capture.PNG", "a-1.png"), + ("a-1", "archive.tar.gz", "a-1.gz"), + ("a-1", "notes", "a-1"), + ( + "3f2504e0-4f89-41d3-9a0c-0305e82c3301", + "x.png", + "3f2504e0-4f89-41d3-9a0c-0305e82c3301.png", + ), + ]; + + for (id, file_name, stored) in cases { + assert_eq!(stored_name(id, file_name), stored, "{file_name}"); } } /// An import decides the id: a record claiming `../vault` must not reach the key file. #[test] - fn a_hostile_identifier_cannot_leave_the_directory() { + fn a_stored_name_is_one_plain_component_whatever_id_it_is_given() { use std::path::{Component, Path}; - for id in [ + let hostile = [ "../vault", "..\\vault", "../../../../Users/me/Startup/run", @@ -282,81 +262,173 @@ mod tests { ".", "", "a/b", - ] { + ]; + + for id in hostile { for file_name in ["capture.png", "no-extension"] { let name = stored_name(id, file_name); - let components: Vec> = Path::new(&name).components().collect(); - - assert_eq!( - components.len(), - 1, - "{id:?} + {file_name:?} gave {name:?}, which is not one component" - ); + let parts: Vec> = Path::new(&name).components().collect(); assert!( - matches!(components[0], Component::Normal(_)), + matches!(parts.as_slice(), [Component::Normal(_)]), "{id:?} + {file_name:?} gave {name:?}" ); } } + assert_eq!(stored_name("../../etc", "x.png"), "etc.png"); + assert_eq!(stored_name("", "x.png"), "attachment.png"); } #[test] - fn the_identifiers_the_application_generates_pass_through_untouched() { - let id = "3f2504e0-4f89-41d3-9a0c-0305e82c3301"; + fn a_stored_name_drops_an_extension_that_is_not_plain_letters_and_digits() { + let cases = [ + ("a-1", "x.p/ng", "a-1"), + ("a-1", "x.ph:p", "a-1"), + ("a-1", "x.abcdefghi", "a-1"), + ("a-1", "x.", "a-1"), + ]; + + for (id, file_name, stored) in cases { + assert_eq!(stored_name(id, file_name), stored, "{id:?} {file_name:?}"); + } + } - assert_eq!(stored_name(id, "capture.png"), format!("{id}.png")); + /// An unknown type stays attachable; it is only not previewed. + #[test] + fn a_type_is_read_from_the_extension() { + let cases = [ + ("a.PNG", "image/png"), + ("a.jpeg", "image/jpeg"), + ("a.jpg", "image/jpeg"), + ("a.svg", "image/svg+xml"), + ("a.pdf", "application/pdf"), + ("a.log", "text/plain"), + ("a.csv", "text/csv"), + ("a.exe", "application/octet-stream"), + ("a", "application/octet-stream"), + ]; + + for (file_name, mime) in cases { + assert_eq!(mime_of(file_name), mime, "{file_name}"); + } } #[test] - fn the_extension_decides_the_type_case_insensitively() { - assert_eq!(mime_of("Capture.PNG"), "image/png"); - assert_eq!(mime_of("dump.unknown"), "application/octet-stream"); + fn a_displayed_name_is_the_file_s_own_without_any_path() { + let cases = [ + ("../../secrets/key.pem", "key.pem"), + ("C:\\Users\\me\\report.pdf", "report.pdf"), + (" spaced.txt ", "spaced.txt"), + ]; + + for (path, shown) in cases { + assert_eq!(display_name(path), Ok(shown.to_string()), "{path}"); + } + for unreadable in ["", "folder/", ".", "..", " "] { + assert_eq!( + display_name(unreadable).unwrap_err().field, + "fileName", + "{unreadable:?}" + ); + } } + /// Without its extension a pasted image would not be previewed. #[test] - fn only_the_last_segment_of_a_path_is_displayed() { - assert_eq!( - display_name(r"C:\Users\me\capture.png").unwrap(), - "capture.png" - ); - assert_eq!(display_name("/home/me/capture.png").unwrap(), "capture.png"); + fn a_pasted_image_is_named_as_a_png() { + let cases = [ + ("", "capture.png"), + (" shot ", "shot.png"), + ("Screen.PNG", "Screen.PNG"), + ("photo.jpg", "photo.jpg.png"), + ]; + + for (base, named) in cases { + assert_eq!(png_name(base), named, "{base:?}"); + } + } + + /// What the clipboard hands over is raw RGBA; bytes past the image are not read. + #[test] + fn raw_pixels_are_encoded_as_a_png() { + let red = [255, 0, 0, 255]; + + let png = encode_png(1, 1, &red).unwrap(); + + assert!(png.starts_with(b"\x89PNG\r\n\x1a\n")); + assert_eq!(encode_png(1, 1, &[red, red].concat()).unwrap(), png); } #[test] - fn a_path_with_no_file_name_is_refused_with_its_field() { - assert_eq!(display_name(" ").unwrap_err().field, "fileName"); - assert_eq!(display_name("/tmp/..").unwrap_err().field, "fileName"); + fn an_image_without_pixels_or_short_of_them_is_refused() { + for (width, height, bytes) in [(0, 1, 4), (1, 0, 4), (2, 2, 15)] { + let rgba = vec![0; bytes]; + + assert!( + matches!(encode_png(width, height, &rgba), Err(StorageError::File(_))), + "{width}×{height} with {bytes} bytes" + ); + } } #[test] - fn a_file_over_the_limit_is_refused_before_being_copied() { - assert!(validate_size(MAX_BYTES, "capture.png").is_ok()); + fn a_file_is_attached_up_to_ten_megabytes_and_refused_past_them() { + assert_eq!( + validate_size(MAX_BYTES, "big.bin").unwrap(), + 10 * 1024 * 1024 + ); assert!(matches!( - validate_size(MAX_BYTES + 1, "capture.mov"), - Err(StorageError::TooLarge { name, limit_mb: 10 }) if name == "capture.mov" + validate_size(MAX_BYTES + 1, "big.bin"), + Err(StorageError::TooLarge { name, limit_mb: 10 }) if name == "big.bin" )); } + /// Two copies of one name must not meet: each sits in a folder of its own. #[test] - fn a_pasted_image_always_ends_up_with_its_extension() { - assert_eq!(png_name("capture-2026"), "capture-2026.png"); - assert_eq!(png_name("capture.PNG"), "capture.PNG"); - assert_eq!(png_name(" "), "capture.png"); + fn an_opened_copy_sits_in_a_folder_of_its_own_under_its_own_name() { + assert_eq!( + attachment("a-1", "Rapport.pdf").opened_copy(), + PathBuf::from("a-1").join("Rapport.pdf") + ); + assert_eq!( + attachment("../a-1", "x.pdf").opened_copy(), + PathBuf::from("a-1").join("x.pdf") + ); } + /// What Windows forbids is replaced; a device name or nothing left falls back on the + /// stored name. #[test] - fn raw_clipboard_pixels_become_a_readable_png() { - let rgba = vec![255u8; 2 * 2 * 4]; - - let png = encode_png(2, 2, &rgba).unwrap(); - - assert_eq!(&png[..8], b"\x89PNG\r\n\x1a\n"); - assert_eq!(mime_of(&png_name("capture")), "image/png"); + fn an_opened_copy_is_named_as_windows_accepts_a_file() { + let cases = [ + ("a:c?.txt", "a_b__c_.txt"), + ("tab\tname.txt", "tab_name.txt"), + ("name. . ", "name"), + (" lead.txt", "lead.txt"), + ("CON.txt", "a-1.txt"), + ("nul", "a-1"), + ("com1.log", "a-1.log"), + ("LPT9", "a-1"), + ("COM10.txt", "COM10.txt"), + ("console.txt", "console.txt"), + ("...", "a-1"), + ]; + + for (file_name, copy) in cases { + let opened = attachment("a-1", file_name).opened_copy(); + assert_eq!(opened, PathBuf::from("a-1").join(copy), "{file_name:?}"); + } } + /// The profile's path comes first: a long name is cut, its extension kept. #[test] - fn a_truncated_clipboard_image_is_refused_rather_than_written() { - assert!(encode_png(2, 2, &[0u8; 4]).is_err()); - assert!(encode_png(0, 0, &[]).is_err()); + fn a_long_opened_copy_name_is_cut_before_its_extension() { + let long = "a".repeat(150); + + let with_extension = attachment("a-1", &format!("{long}.pdf")).opened_copy(); + let without = attachment("a-1", &long).opened_copy(); + + let name = |path: &std::path::Path| path.file_name().unwrap().to_string_lossy().to_string(); + assert_eq!(name(&with_extension), format!("{}.pdf", "a".repeat(96))); + assert_eq!(name(&without), "a".repeat(100)); } } diff --git a/crates/engine/src/attachments/sealed.rs b/crates/engine/src/attachments/sealed.rs index 645334a67..b3b149241 100644 --- a/crates/engine/src/attachments/sealed.rs +++ b/crates/engine/src/attachments/sealed.rs @@ -75,17 +75,6 @@ mod tests { assert!(!directory.exists()); } - /// The property the name has to have, asserted without waiting for a coincidence. - #[test] - fn two_scratch_directories_are_never_the_same_one() { - let scratch = tempfile::tempdir().unwrap(); - let first = scratch.path().to_path_buf(); - let scratch = tempfile::tempdir().unwrap(); - let second = scratch.path().to_path_buf(); - - assert_ne!(first, second); - } - #[test] fn a_sealed_file_reads_back_byte_for_byte() { let scratch = tempfile::tempdir().unwrap(); diff --git a/crates/engine/src/attachments/store.rs b/crates/engine/src/attachments/store.rs index 87c1fa8a6..5de5a2d49 100644 --- a/crates/engine/src/attachments/store.rs +++ b/crates/engine/src/attachments/store.rs @@ -182,89 +182,223 @@ pub fn counts(connection: &mut SqliteConnection) -> Result, #[cfg(test)] mod tests { - use chrono::Utc; + use chrono::{DateTime, Utc}; use super::*; use crate::db::open_in_memory; - use crate::notes::kind::NoteKind; - use crate::notes::language::Language; - use crate::notes::model::{NoteDraft, NoteLifecycle}; - use crate::notes::priority::Priority; - - fn note(connection: &mut Library) -> String { - let space = crate::spaces::store::create(connection, "Personal").unwrap(); - crate::notes::store::create( - connection, - NoteDraft { - space_id: space.id, - folder_id: None, - title: "T".to_string(), - language: Language::Txt, - content: String::new(), - source: String::new(), - tags: Vec::new(), - pinned: false, - lifecycle: NoteLifecycle::Permanent, - kind: NoteKind::Snippet, - priority: Priority::None, - items: Vec::new(), - }, - Utc::now(), - ) - .unwrap() - .id + use crate::notes::fixtures::at; + + fn note_in(library: &mut Library) -> String { + let space = crate::spaces::store::create(library, &uuid::Uuid::new_v4().to_string()) + .unwrap() + .id; + let draft = crate::notes::model::NoteDraft { + space_id: space, + folder_id: None, + title: "T".to_string(), + language: crate::notes::language::Language::Txt, + content: String::new(), + source: String::new(), + tags: Vec::new(), + pinned: false, + lifecycle: crate::notes::model::NoteLifecycle::Permanent, + kind: crate::notes::kind::NoteKind::Snippet, + priority: crate::notes::priority::Priority::None, + items: Vec::new(), + }; + crate::notes::store::create(library, draft, at("2026-07-25T09:00:00.000Z")) + .unwrap() + .id } - /// The tests hold a library; `create` takes the pair, as an import does. - fn create_here(connection: &mut Library, attachment: &Attachment) -> Result<(), StorageError> { - let (db, vault) = connection.split(); - create(db, vault, attachment) - } - - fn sample(id: &str, note_id: &str) -> Attachment { + fn attachment( + id: &str, + note_id: &str, + file_name: &str, + created_at: DateTime, + ) -> Attachment { Attachment { id: id.to_string(), note_id: note_id.to_string(), - file_name: "capture.png".to_string(), - mime_type: "image/png".to_string(), - byte_size: 12, - created_at: Utc::now(), + file_name: file_name.to_string(), + mime_type: model::mime_of(file_name), + byte_size: 3, + created_at, + } + } + + fn record(library: &mut Library, attachment: &Attachment) { + let (db, vault) = library.split(); + create(db, vault, attachment).unwrap(); + } + + fn ids(attachments: &[Attachment]) -> Vec<&str> { + attachments + .iter() + .map(|attachment| attachment.id.as_str()) + .collect() + } + + /// The foreign key would refuse it too, in words the screen cannot translate. + #[test] + fn an_attachment_is_recorded_only_for_a_live_note() { + let mut library = open_in_memory().unwrap(); + let trashed = note_in(&mut library); + crate::notes::store::trash::trash(&mut library, &trashed, Utc::now()).unwrap(); + let (db, vault) = library.split(); + + for note_id in ["missing", trashed.as_str()] { + let refused = create(db, vault, &attachment("a-1", note_id, "x.png", Utc::now())); + + assert!( + matches!(refused, Err(StorageError::NoteNotFound(id)) if id == note_id), + "{note_id}" + ); } } #[test] - fn an_attachment_is_read_back_whole() { - let mut connection = open_in_memory().unwrap(); - let note_id = note(&mut connection); + fn a_note_s_attachments_are_listed_in_the_order_they_came() { + let mut library = open_in_memory().unwrap(); + let note = note_in(&mut library); + let other = note_in(&mut library); + record( + &mut library, + &attachment("late", ¬e, "b.png", at("2026-07-25T11:00:00.000Z")), + ); + record( + &mut library, + &attachment("early", ¬e, "a.png", at("2026-07-25T10:00:00.000Z")), + ); + record( + &mut library, + &attachment("else", &other, "c.png", at("2026-07-25T10:00:00.000Z")), + ); + + assert_eq!(ids(&list(&mut library, ¬e).unwrap()), ["early", "late"]); + } - create_here(&mut connection, &sample("a-1", ¬e_id)).unwrap(); - let listed = list(&mut connection, ¬e_id).unwrap(); + /// The type stays in the clear: the file on disk already says it by its extension. + #[test] + fn a_record_s_name_is_sealed_and_read_back_whole() { + let mut library = open_in_memory().unwrap(); + let note = note_in(&mut library); + let made = attachment( + "a-1", + ¬e, + "secret plan.png", + at("2026-07-25T10:00:00.000Z"), + ); + record(&mut library, &made); + + let (name, mime): (String, String) = attachments::table + .select((attachments::file_name, attachments::mime_type)) + .first(library.db()) + .unwrap(); + let found = find(&mut library, "a-1").unwrap().unwrap(); + + assert!(!name.contains("secret")); + assert_eq!(mime, "image/png"); + assert_eq!( + (found.file_name, found.byte_size, found.created_at), + (made.file_name, 3, made.created_at) + ); + assert!(find(&mut library, "missing").unwrap().is_none()); + } - assert_eq!(listed.len(), 1); - assert_eq!(listed[0].file_name, "capture.png"); - assert_eq!(listed[0].byte_size, 12); + #[test] + fn an_unreadable_instant_is_answered_as_a_corrupt_row() { + let mut library = open_in_memory().unwrap(); + let note = note_in(&mut library); + record(&mut library, &attachment("a-1", ¬e, "x.png", Utc::now())); + diesel::update(attachments::table.find("a-1")) + .set(attachments::created_at.eq("yesterday")) + .execute(library.db()) + .unwrap(); + + assert!(matches!( + find(&mut library, "a-1"), + Err(StorageError::CorruptRow { id, field: "createdAt" }) if id == "a-1" + )); } #[test] - fn attaching_to_an_unknown_note_is_refused() { - let mut connection = open_in_memory().unwrap(); + fn a_record_is_deleted_once_and_a_second_time_is_not_found() { + let mut library = open_in_memory().unwrap(); + let note = note_in(&mut library); + record(&mut library, &attachment("a-1", ¬e, "x.png", Utc::now())); + + delete(library.db(), "a-1").unwrap(); + + assert!(list(&mut library, ¬e).unwrap().is_empty()); + assert!(matches!( + delete(library.db(), "a-1"), + Err(StorageError::AttachmentNotFound(id)) if id == "a-1" + )); + } - let error = create_here(&mut connection, &sample("a-1", "ghost")).unwrap_err(); + /// What an export carries, and the names its files are read under. + #[test] + fn the_records_of_some_notes_come_with_the_names_their_files_are_stored_under() { + let mut library = open_in_memory().unwrap(); + let first = note_in(&mut library); + let second = note_in(&mut library); + let left = note_in(&mut library); + record( + &mut library, + &attachment("a-1", &first, "Shot.PNG", at("2026-07-25T10:00:00.000Z")), + ); + record( + &mut library, + &attachment("a-2", &second, "notes", at("2026-07-25T11:00:00.000Z")), + ); + record( + &mut library, + &attachment("a-3", &left, "x.pdf", at("2026-07-25T12:00:00.000Z")), + ); + let chosen = [first, second]; + + let records = for_notes(&mut library, &chosen).unwrap(); + let mut names = stored_names_of(&mut library, &chosen).unwrap(); + names.sort(); + let mut every = all_stored_names(&mut library).unwrap(); + every.sort(); + + assert_eq!(ids(&records), ["a-1", "a-2"]); + assert_eq!(names, ["a-1.png", "a-2"]); + assert_eq!(every, ["a-1.png", "a-2", "a-3.pdf"]); + assert!(for_notes(&mut library, &[]).unwrap().is_empty()); + assert!(stored_names_of(&mut library, &[]).unwrap().is_empty()); + } + + /// The cascade takes the records, never the files: their names are read before a purge. + #[test] + fn a_purged_note_s_records_go_with_it() { + let mut library = open_in_memory().unwrap(); + let note = note_in(&mut library); + record(&mut library, &attachment("a-1", ¬e, "x.png", Utc::now())); + let names = stored_names_of(&mut library, std::slice::from_ref(¬e)).unwrap(); - assert!(matches!(error, StorageError::NoteNotFound(_))); + crate::notes::store::trash::trash(&mut library, ¬e, Utc::now()).unwrap(); + crate::notes::store::trash::purge(&mut library, std::slice::from_ref(¬e)).unwrap(); + + assert_eq!(names, ["a-1.png"]); + assert!(list(&mut library, ¬e).unwrap().is_empty()); } #[test] - fn purging_a_note_takes_its_attachment_rows_with_it() { - let mut connection = open_in_memory().unwrap(); - let note_id = note(&mut connection); - create_here(&mut connection, &sample("a-1", ¬e_id)).unwrap(); + fn each_note_is_counted_its_attachments_in_one_read() { + let mut library = open_in_memory().unwrap(); + let note = note_in(&mut library); + let other = note_in(&mut library); + let bare = note_in(&mut library); + for (id, owner) in [("a-1", ¬e), ("a-2", ¬e), ("a-3", &other)] { + record(&mut library, &attachment(id, owner, "x.png", Utc::now())); + } - let files = stored_names_of(&mut connection, std::slice::from_ref(¬e_id)).unwrap(); - crate::notes::store::trash::trash(&mut connection, ¬e_id, Utc::now()).unwrap(); - crate::notes::store::trash::purge(&mut connection, std::slice::from_ref(¬e_id)).unwrap(); + let counted = counts(library.db()).unwrap(); - assert_eq!(files, ["a-1.png"]); - assert!(list(&mut connection, ¬e_id).unwrap().is_empty()); + assert_eq!(counted, HashMap::from([(note, 2), (other, 1)])); + assert!(!counted.contains_key(&bare)); } } diff --git a/crates/engine/tests/commands/attachments.rs b/crates/engine/tests/commands/attachments.rs index a116cac8e..9120a8925 100644 --- a/crates/engine/tests/commands/attachments.rs +++ b/crates/engine/tests/commands/attachments.rs @@ -1,6 +1,9 @@ +use std::path::{Path, PathBuf}; + +use engine::Engine; use engine::attachments::{ attach_file, attach_image, decrypted_copy, delete_attachment, list_attachments, - read_attachment, save_attachment, + read_attachment, save_attachment, sweep_copies, }; use engine::error::ErrorCode; use engine::notes::create_note; @@ -8,108 +11,222 @@ use engine::notes::create_note; use super::common::snippet; use super::{Session, code}; -/// Stored sealed beside the library, handed back as the `data:` URI the preview reads, and -/// saved in the clear where the user chose. -#[test] -fn a_file_is_attached_read_saved_and_deleted() { - let scratch = tempfile::tempdir().unwrap(); - let session = Session::on_disk(scratch.path()); - let space = session.space("Personal"); - let note = session +const RED: [u8; 4] = [255, 0, 0, 255]; + +fn a_note(session: &Session) -> String { + let space = session.space("Work"); + session .call(|e| create_note(e, snippet(&space))) .unwrap() .note - .id; - let source = scratch.path().join("capture.png"); - std::fs::write(&source, b"\x89PNG").unwrap(); - let saved = scratch.path().join("saved.png"); + .id +} - let attachment = session - .wait(|e| attach_file(e, note.clone(), source.to_string_lossy().to_string())) - .unwrap(); - let listed = session.call(|e| list_attachments(e, ¬e)).unwrap(); - let read = session - .call(|e| read_attachment(e, &attachment.id)) - .unwrap(); - session - .call(|e| save_attachment(e, &attachment.id, saved.to_string_lossy().as_ref())) - .unwrap(); - session - .call(|e| delete_attachment(e, &attachment.id)) +fn source(directory: &Path, name: &str, bytes: &[u8]) -> String { + let path = directory.join(name); + std::fs::write(&path, bytes).unwrap(); + path.to_string_lossy().to_string() +} + +fn stored_files(directory: &Path) -> Vec { + let attachments = directory.join("attachments"); + let entries = std::fs::read_dir(attachments).unwrap(); + entries.map(|entry| entry.unwrap().path()).collect() +} + +#[test] +fn nothing_answers_before_a_library_is_open() { + let scratch = tempfile::tempdir().unwrap(); + let session = Session::locked(); + let path = source(scratch.path(), "report.pdf", b"pdf"); + let saved = scratch.path().join("saved").to_string_lossy().to_string(); + + let codes = [ + code(session.wait(|e| attach_file(e, "n".to_string(), path))), + code(session.call(|e| attach_image(e, "n".to_string(), "", (1, 1), &RED))), + code(session.call(|e| list_attachments(e, "n"))), + code(session.call(|e| read_attachment(e, "a"))), + code(session.call(|e| decrypted_copy(e, "a"))), + code(session.call(|e| save_attachment(e, "a", &saved))), + code(session.call(|e| delete_attachment(e, "a"))), + ]; + + assert!( + codes.iter().all(|found| *found == ErrorCode::Locked), + "{codes:?}" + ); +} + +/// Under its own name, whatever path it came from; read back opened, with its type. +#[test] +fn a_file_is_attached_under_its_own_name_and_read_back_whole() { + let scratch = tempfile::tempdir().unwrap(); + let session = Session::on_disk(&scratch.path().join("library")); + let note = a_note(&session); + let path = source(scratch.path(), "report.pdf", b"%PDF-1.7"); + session.wait(engine::index::fill); + + let attached = session + .wait(|e| attach_file(e, note.clone(), path)) .unwrap(); - assert_eq!(attachment.file_name, "capture.png"); + assert_eq!(attached.file_name, "report.pdf"); + assert_eq!( + (attached.mime_type.as_str(), attached.byte_size), + ("application/pdf", 8) + ); + let listed = session.call(|e| list_attachments(e, ¬e)).unwrap(); assert_eq!(listed.len(), 1); - assert_eq!(read, ("image/png".to_string(), b"\x89PNG".to_vec())); - assert_eq!(std::fs::read(&saved).unwrap(), b"\x89PNG"); + let read = session.call(|e| read_attachment(e, &attached.id)).unwrap(); + assert_eq!(read, ("application/pdf".to_string(), b"%PDF-1.7".to_vec())); + assert_eq!(session.call(Engine::index_matches_library), Ok(())); +} + +#[test] +fn a_file_past_ten_megabytes_or_unreadable_is_refused_by_its_code() { + let scratch = tempfile::tempdir().unwrap(); + let session = Session::on_disk(&scratch.path().join("library")); + let note = a_note(&session); + let big = vec![0u8; 10 * 1024 * 1024 + 1]; + let too_big = source(scratch.path(), "big.bin", &big); + let missing = scratch + .path() + .join("missing.bin") + .to_string_lossy() + .to_string(); + + let refused = session + .wait(|e| attach_file(e, note.clone(), too_big)) + .unwrap_err(); + assert_eq!(refused.code, ErrorCode::FileTooLarge); + assert_eq!( + refused.params.get("name").map(String::as_str), + Some("big.bin") + ); + assert_eq!(refused.params.get("limit").map(String::as_str), Some("10")); + assert_eq!( + code(session.wait(|e| attach_file(e, note.clone(), missing))), + ErrorCode::FileAccess + ); assert!( session .call(|e| list_attachments(e, ¬e)) .unwrap() .is_empty() ); - assert!(matches!( - code(session.call(|e| read_attachment(e, &attachment.id))), - ErrorCode::AttachmentNotFound - )); } +/// What the clipboard hands over, raw, comes out a PNG under a name the preview knows. #[test] -fn a_file_that_cannot_be_read_is_named_as_such() { +fn a_pasted_image_is_stored_as_a_png() { let scratch = tempfile::tempdir().unwrap(); let session = Session::on_disk(scratch.path()); - let missing = scratch.path().join("gone.png"); - - assert!(matches!( - code(session.wait(|e| attach_file( - e, - "n-1".to_string(), - missing.to_string_lossy().to_string() - ))), - ErrorCode::FileAccess - )); + let note = a_note(&session); + + let attached = session + .call(|e| attach_image(e, note.clone(), " ", (1, 1), &RED)) + .unwrap(); + + assert_eq!(attached.file_name, "capture.png"); + let (mime, bytes) = session.call(|e| read_attachment(e, &attached.id)).unwrap(); + assert_eq!(mime, "image/png"); + assert!(bytes.starts_with(b"\x89PNG")); } -/// Past the limit: its own code, with the file and the limit for the sentence. #[test] -fn a_file_past_the_limit_is_refused_by_its_name_and_the_limit() { +fn an_image_short_of_its_pixels_or_for_a_note_not_there_is_refused_by_its_code() { let scratch = tempfile::tempdir().unwrap(); let session = Session::on_disk(scratch.path()); - let huge = scratch.path().join("capture.mov"); - let limit = usize::try_from(engine::attachments::model::MAX_BYTES).unwrap(); - std::fs::write(&huge, vec![0u8; limit + 1]).unwrap(); - - let refused = session - .wait(|e| attach_file(e, "n-1".to_string(), huge.to_string_lossy().to_string())) - .unwrap_err(); + let note = a_note(&session); - assert!(matches!(refused.code, ErrorCode::FileTooLarge)); assert_eq!( - refused.params.get("name").map(String::as_str), - Some("capture.mov") + code(session.call(|e| attach_image(e, note.clone(), "", (2, 2), &RED))), + ErrorCode::FileAccess ); - assert_eq!(refused.params.get("limit").map(String::as_str), Some("10")); + assert_eq!( + code(session.call(|e| attach_image(e, "missing".to_string(), "", (1, 1), &RED))), + ErrorCode::NoteNotFound + ); + assert!(stored_files(scratch.path()).is_empty()); +} + +/// The one place a decrypted copy reaches the disk, under the profile, gone by the next sweep. +#[test] +fn an_attachment_opened_is_a_decrypted_copy_under_the_profile_until_the_sweep() { + let scratch = tempfile::tempdir().unwrap(); + let session = Session::on_disk(&scratch.path().join("library")); + let note = a_note(&session); + let attached = session + .call(|e| attach_image(e, note, "shot", (1, 1), &RED)) + .unwrap(); + + let copy = session.call(|e| decrypted_copy(e, &attached.id)).unwrap(); + + let profile = session.engine.paths().profile.clone(); + assert!(copy.starts_with(&profile)); + assert!(std::fs::read(©).unwrap().starts_with(b"\x89PNG")); + session.call(sweep_copies).unwrap(); + assert!(!copy.exists()); } -/// What the shell hands over: the clipboard's pixels in, a path to open out. +/// That is what "save as" means: in the clear, where the user chose. #[test] -fn an_image_read_by_the_shell_is_stored_as_a_png_and_opened_from_a_decrypted_copy() { +fn an_attachment_saved_as_is_written_in_the_clear() { + let scratch = tempfile::tempdir().unwrap(); + let session = Session::on_disk(&scratch.path().join("library")); + let note = a_note(&session); + let path = source(scratch.path(), "notes.txt", b"plain words"); + let attached = session.wait(|e| attach_file(e, note, path)).unwrap(); + let saved = scratch.path().join("saved.txt"); + + let target = saved.to_string_lossy().to_string(); + session + .call(|e| save_attachment(e, &attached.id, &target)) + .unwrap(); + + assert_eq!(std::fs::read(&saved).unwrap(), b"plain words"); +} + +/// The record, then its file; a second deletion has nothing left to name. +#[test] +fn an_attachment_deleted_takes_its_file_with_it() { let scratch = tempfile::tempdir().unwrap(); let session = Session::on_disk(scratch.path()); - let space = session.space("Personal"); - let note = session - .call(|e| create_note(e, snippet(&space))) - .unwrap() - .note - .id; - let red = [255, 0, 0, 255].repeat(4); + let note = a_note(&session); + let attached = session + .call(|e| attach_image(e, note.clone(), "", (1, 1), &RED)) + .unwrap(); + session.wait(engine::index::fill); - let attachment = session - .call(|e| attach_image(e, note, "capture", (2, 2), &red)) + session + .call(|e| delete_attachment(e, &attached.id)) .unwrap(); - let copy = session.call(|e| decrypted_copy(e, &attachment.id)).unwrap(); - assert_eq!(attachment.file_name, "capture.png"); - assert!(copy.starts_with(session.engine.paths().profile.join("open"))); - assert!(std::fs::read(©).unwrap().starts_with(b"\x89PNG")); + assert!( + session + .call(|e| list_attachments(e, ¬e)) + .unwrap() + .is_empty() + ); + assert!(stored_files(scratch.path()).is_empty()); + assert_eq!( + code(session.call(|e| delete_attachment(e, &attached.id))), + ErrorCode::AttachmentNotFound + ); + assert_eq!(session.call(Engine::index_matches_library), Ok(())); +} + +#[test] +fn an_attachment_not_there_is_answered_by_its_code() { + let scratch = tempfile::tempdir().unwrap(); + let session = Session::on_disk(scratch.path()); + let saved = scratch.path().join("saved").to_string_lossy().to_string(); + + for answer in [ + code(session.call(|e| read_attachment(e, "missing"))), + code(session.call(|e| decrypted_copy(e, "missing"))), + code(session.call(|e| save_attachment(e, "missing", &saved))), + ] { + assert_eq!(answer, ErrorCode::AttachmentNotFound); + } } From 38577f3017cf308bf18148aef66108e3fd36eed7 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:58:06 +0100 Subject: [PATCH 26/95] Export format: unit tests rewritten (#1747) * Rewrite the tests of the export format: bundle, archive and protection Co-Authored-By: Claude Opus 5.5 * An export that cannot replace its target leaves no staging file Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/transfer/file.rs | 632 ++++++++++++++-------------- crates/engine/src/transfer/model.rs | 352 ++++++++++------ 2 files changed, 533 insertions(+), 451 deletions(-) diff --git a/crates/engine/src/transfer/file.rs b/crates/engine/src/transfer/file.rs index b2e7adbb6..806c71bd7 100644 --- a/crates/engine/src/transfer/file.rs +++ b/crates/engine/src/transfer/file.rs @@ -353,436 +353,438 @@ fn staging_path(path: &str) -> PathBuf { #[cfg(test)] mod tests { - /// A bundle written as plain JSON, past what an archive may expand to, is refused before it - /// is read whole (#1477, N30). - #[test] - fn a_plain_bundle_past_the_ceiling_is_refused_unread() { - let folder = tempfile::tempdir().unwrap(); - let path = folder.path().join("notes.json"); - let file = std::fs::File::create(&path).unwrap(); - file.set_len(PLAIN_CEILING + 1).unwrap(); - - let refused = read(path.to_str().unwrap(), None).err().unwrap(); - - assert!( - matches!(&refused, StorageError::ImportFormat(said) if said.contains("past")), - "{refused:?}" - ); - } + use chrono::DateTime; use super::*; - use crate::notes::fixtures::note as sample; - use crate::spaces::model::Space; + use crate::attachments::sealed::write_sealed; + use crate::notes::fixtures::{NOW, at, note}; + use crate::notes::model::Note; use crate::vault::key::Cost; fn library() -> Vault { Vault::derive("the library", b"0123456789abcdef", Cost::FOR_TESTS).unwrap() } - fn bundle() -> Bundle { - Bundle { - version: super::super::model::FORMAT_VERSION, - exported_at: sample().created_at, - spaces: vec![Space { - id: "s-1".to_string(), - name: "Personal".to_string(), - pinned: false, - }], - folders: Vec::new(), - notes: vec![sample()], - attachments: Vec::new(), + fn attachment(id: &str, file_name: &str) -> Attachment { + Attachment { + id: id.to_string(), + note_id: "n-1".to_string(), + file_name: file_name.to_string(), + mime_type: crate::attachments::model::mime_of(file_name), + byte_size: 5, + created_at: DateTime::::UNIX_EPOCH, } } - fn record() -> Attachment { - Attachment { - id: "a-1".to_string(), - note_id: sample().id, - file_name: "capture.png".to_string(), - mime_type: "image/png".to_string(), - byte_size: 4, - created_at: sample().created_at, + fn bundle(attachments: Vec) -> Bundle { + Bundle { + version: crate::transfer::model::FORMAT_VERSION, + exported_at: at(NOW), + spaces: Vec::new(), + folders: Vec::new(), + notes: vec![note()], + attachments, } } - /// The attachment as it really sits beside the database: sealed under the library. - fn seal_beside(directory: &Path, vault: &Vault, bytes: &[u8]) { - let sealed = vault.seal_bytes(bytes).unwrap(); - std::fs::write(directory.join(record().stored_name()), sealed).unwrap(); + /// A scratch folder holding the library's sealed attachment files, and the export's path. + struct Scratch { + _folder: tempfile::TempDir, + attachments: PathBuf, + export: String, } - #[test] - fn the_staging_file_sits_next_to_its_target() { - let target = std::env::temp_dir() - .join("documents") - .join("library.devnotes"); + fn scratch() -> Scratch { + let folder = tempfile::tempdir().unwrap(); + let attachments = folder.path().join("attachments"); + std::fs::create_dir_all(&attachments).unwrap(); + let export = folder + .path() + .join("notes.devnotes") + .to_string_lossy() + .to_string(); + Scratch { + _folder: folder, + attachments, + export, + } + } - let staged = staging_path(&target.to_string_lossy()); + fn sealed_beside(scratch: &Scratch, record: &Attachment, bytes: &[u8]) { + write_sealed( + &library(), + &scratch.attachments.join(record.stored_name()), + bytes, + ) + .unwrap(); + } - assert_eq!(staged.parent(), target.parent()); - assert_ne!(staged.file_name(), target.file_name()); + fn entries(path: &str) -> Vec { + let mut archive = ZipArchive::new(File::open(path).unwrap()).unwrap(); + let mut names: Vec = (0..archive.len()) + .map(|at| archive.by_index(at).unwrap().name().unwrap().to_string()) + .collect(); + names.sort(); + names } - #[test] - fn two_exports_of_the_same_target_never_stage_the_same_file() { - let scratch = tempfile::tempdir().unwrap(); - let target = scratch.path().join("library.devnotes"); + fn entry_bytes(path: &str, name: &str) -> Vec { + let mut archive = ZipArchive::new(File::open(path).unwrap()).unwrap(); + let mut bytes = Vec::new(); + archive + .by_name(name) + .unwrap() + .read_to_end(&mut bytes) + .unwrap(); + bytes + } - let first = staging_path(&target.to_string_lossy()); - let second = staging_path(&target.to_string_lossy()); + /// A zip of these entries, each written as given. + fn zip_of(path: &Path, files: &[(&str, &[u8])]) { + let mut writer = ZipWriter::new(File::create(path).unwrap()); + for (name, bytes) in files { + writer.start_file(*name, deflated()).unwrap(); + writer.write_all(bytes).unwrap(); + } + writer.finish().unwrap(); + } - assert_ne!(first, second); + fn notes_of(read: &(IncomingBundle, Payload)) -> &[Note] { + &read.0.bundle.notes } + /// The library's key never leaves: its files are opened on the way out. #[test] - fn an_export_leaves_no_staging_file_behind() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let target = directory.join("library.devnotes"); + fn a_plain_export_is_an_archive_of_the_bundle_and_the_attachments_in_the_clear() { + let scratch = scratch(); + let record = attachment("a-1", "shot.png"); + sealed_beside(&scratch, &record, b"pixels"); - write( - &target.to_string_lossy(), - &bundle(), - &directory, + let report = write( + &scratch.export, + &bundle(vec![record]), + &scratch.attachments, &library(), None, ) .unwrap(); - let left: Vec<_> = std::fs::read_dir(&directory) - .unwrap() - .filter_map(Result::ok) - .map(|entry| entry.file_name()) - .collect(); - - assert_eq!(left, ["library.devnotes"]); + assert_eq!( + entries(&scratch.export), + ["attachments/a-1.png", "bundle.json"] + ); + assert_eq!( + entry_bytes(&scratch.export, "attachments/a-1.png"), + b"pixels" + ); + let json = String::from_utf8(entry_bytes(&scratch.export, "bundle.json")).unwrap(); + assert!(json.contains(¬e().title)); + assert_eq!( + (report.notes, report.attachments, report.protected), + (1, 1, false) + ); } + /// No plaintext bundle to fall back on: the sealed one replaces it, the recipe beside it. #[test] - fn exporting_over_an_existing_file_replaces_it_whole() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let target = directory.join("library.devnotes"); - std::fs::write(&target, "previous export, longer than what replaces it").unwrap(); + fn a_protected_export_carries_its_recipe_and_its_sealed_bundle_and_nothing_in_the_clear() { + let scratch = scratch(); + let record = attachment("a-1", "shot.png"); + sealed_beside(&scratch, &record, b"pixels"); - write( - &target.to_string_lossy(), - &bundle(), - &directory, + let report = write( + &scratch.export, + &bundle(vec![record]), + &scratch.attachments, &library(), - None, + Some("export phrase"), ) .unwrap(); - let written = std::fs::read(&target).unwrap(); - assert_eq!(written[..4], ZIP_MAGIC); + assert_eq!( + entries(&scratch.export), + ["attachments/a-1.png", "bundle.sealed", "recipe.json"] + ); + let sealed = entry_bytes(&scratch.export, "bundle.sealed"); + assert!(!String::from_utf8_lossy(&sealed).contains(¬e().title)); + assert_ne!( + entry_bytes(&scratch.export, "attachments/a-1.png"), + b"pixels" + ); + assert!(report.protected); } #[test] - fn an_export_to_an_unreachable_directory_reports_rather_than_panicking() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - - let error = write( - "/no/such/directory/library.devnotes", - &bundle(), - &directory, + fn an_export_reads_back_with_its_attachments() { + let scratch = scratch(); + let record = attachment("a-1", "shot.png"); + sealed_beside(&scratch, &record, b"pixels"); + write( + &scratch.export, + &bundle(vec![record]), + &scratch.attachments, &library(), None, ) - .unwrap_err(); + .unwrap(); - assert!(matches!(error, StorageError::File(_)), "{error}"); + let mut read = read(&scratch.export, None).unwrap(); + + assert_eq!(notes_of(&read), [note()]); + assert_eq!(read.1.take("a-1.png"), Some(b"pixels".to_vec())); + assert_eq!(read.1.take("a-2.png"), None); + assert!(!is_protected(&scratch.export).unwrap()); } + /// Only looking inside can tell: the payload's own tag is the check. #[test] - fn a_written_bundle_reads_back_as_itself() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let target = directory.join("library.devnotes"); - + fn a_protected_export_asks_for_its_phrase_refuses_another_and_opens_with_its_own() { + let scratch = scratch(); + let record = attachment("a-1", "shot.png"); + sealed_beside(&scratch, &record, b"pixels"); write( - &target.to_string_lossy(), - &bundle(), - &directory, + &scratch.export, + &bundle(vec![record]), + &scratch.attachments, &library(), - None, + Some("export phrase"), ) .unwrap(); - let (read_back, _) = read(&target.to_string_lossy(), None).unwrap(); - assert_eq!(read_back.bundle.notes.len(), 1); - assert_eq!(read_back.bundle.spaces[0].name, "Personal"); + assert!(is_protected(&scratch.export).unwrap()); + assert!(matches!( + read(&scratch.export, None), + Err(StorageError::PassphraseRequired) + )); + assert!(matches!( + read(&scratch.export, Some("another")), + Err(StorageError::WrongPassphrase) + )); + let mut opened = read(&scratch.export, Some("export phrase")).unwrap(); + assert_eq!(notes_of(&opened), [note()]); + assert_eq!(opened.1.take("a-1.png"), Some(b"pixels".to_vec())); } + /// The export is the one copy that needs no passphrase: a damaged file must not cost it. #[test] - fn an_attachment_travels_with_its_note() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let target = directory.join("library.devnotes"); - let vault = library(); - seal_beside(&directory, &vault, b"\x89PNG"); - - let mut exported = bundle(); - exported.attachments = vec![record()]; - let report = write( - &target.to_string_lossy(), - &exported, - &directory, - &vault, - None, + fn an_attachment_missing_or_not_opened_by_the_library_s_key_is_left_out() { + let scratch = scratch(); + let missing = attachment("a-1", "gone.png"); + let damaged = attachment("a-2", "damaged.png"); + std::fs::write( + scratch.attachments.join(damaged.stored_name()), + b"not sealed", ) .unwrap(); - assert_eq!(report.attachments, 1); - assert!(!report.protected); - - let (read_back, mut payload) = read(&target.to_string_lossy(), None).unwrap(); - assert_eq!(read_back.bundle.attachments.len(), 1); - assert_eq!( - payload.take(&record().stored_name()), - Some(b"\x89PNG".to_vec()) - ); - } - - /// A record whose file has gone missing must not fail the export. - #[test] - fn a_record_whose_file_is_gone_leaves_the_export_rather_than_failing_it() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let target = directory.join("library.devnotes"); - - let mut exported = bundle(); - exported.attachments = vec![record()]; let report = write( - &target.to_string_lossy(), - &exported, - &directory, + &scratch.export, + &bundle(vec![missing, damaged]), + &scratch.attachments, &library(), None, ) .unwrap(); - assert_eq!(report.attachments, 0); - assert_eq!(report.notes, 1); + assert_eq!((report.attachments, report.attachments_unreadable), (0, 1)); + assert_eq!(entries(&scratch.export), ["bundle.json"]); } - /// A `.json` export from before the archive still reads. + /// ⚠️ A rename across volumes is not atomic: the staging file shares its target's folder. #[test] - fn a_json_export_from_before_the_archive_still_imports() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let target = directory.join("library.json"); - let json = serde_json::to_string_pretty(&bundle()).unwrap(); - std::fs::write(&target, json).unwrap(); + fn the_staging_file_sits_next_to_its_target() { + let target = std::env::temp_dir() + .join("documents") + .join("library.devnotes"); - let (read_back, payload) = read(&target.to_string_lossy(), None).unwrap(); + let staged = staging_path(&target.to_string_lossy()); - assert_eq!(read_back.bundle.notes.len(), 1); - assert!(matches!(payload, Payload::Empty)); + assert_eq!(staged.parent(), target.parent()); + assert_ne!(staged.file_name(), target.file_name()); } - /// The file most likely to leave the machine must not carry everything in the clear. + /// Staged beside the target, then renamed: the previous export is never truncated. #[test] - fn a_protected_export_carries_none_of_the_notes_in_the_clear() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let target = directory.join("library.devnotes"); - let vault = library(); - seal_beside(&directory, &vault, b"a screenshot of something"); - - let mut exported = bundle(); - exported.notes[0].content = "psql -h prod -W hunter2".to_string(); - exported.attachments = vec![record()]; + fn an_export_replaces_the_previous_one_whole_and_leaves_no_staging_file() { + let scratch = scratch(); + std::fs::write(&scratch.export, b"the previous export").unwrap(); - let report = write( - &target.to_string_lossy(), - &exported, - &directory, - &vault, - Some("a shared phrase"), + write( + &scratch.export, + &bundle(Vec::new()), + &scratch.attachments, + &library(), + None, ) .unwrap(); - assert!(report.protected); - let raw = std::fs::read(&target).unwrap(); - let haystack = String::from_utf8_lossy(&raw); - assert!(!haystack.contains("hunter2")); - assert!(!haystack.contains("Personal")); - assert!(!haystack.contains("a screenshot of")); + assert_eq!(entries(&scratch.export), ["bundle.json"]); + let folder = Path::new(&scratch.export).parent().unwrap(); + let mut beside: Vec = std::fs::read_dir(folder) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().to_string()) + .collect(); + beside.sort(); + assert_eq!(beside, ["attachments", "notes.devnotes"]); } #[test] - fn a_protected_export_reads_back_whole_with_its_phrase() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let target = directory.join("library.devnotes"); - let vault = library(); - seal_beside(&directory, &vault, b"\x89PNG"); - - let mut exported = bundle(); - exported.attachments = vec![record()]; - write( - &target.to_string_lossy(), - &exported, - &directory, - &vault, - Some("a shared phrase"), - ) - .unwrap(); + fn an_export_that_cannot_be_written_leaves_nothing_behind() { + let scratch = scratch(); + let nowhere = Path::new(&scratch.export) + .with_file_name("missing") + .join("notes.devnotes"); + + let refused = write( + &nowhere.to_string_lossy(), + &bundle(Vec::new()), + &scratch.attachments, + &library(), + None, + ); - let (read_back, mut payload) = - read(&target.to_string_lossy(), Some("a shared phrase")).unwrap(); + assert!(matches!(refused, Err(StorageError::File(_)))); + assert!(!nowhere.parent().unwrap().exists()); + } - assert_eq!(read_back.bundle.notes.len(), 1); - assert_eq!( - payload.take(&record().stored_name()), - Some(b"\x89PNG".to_vec()) + /// Asked before an import starts: the recipe alone answers, whatever the bundle holds. + #[test] + fn whether_a_file_is_protected_is_answered_without_reading_its_bundle() { + let scratch = scratch(); + zip_of( + Path::new(&scratch.export), + &[("bundle.json", b"not json at all")], ); + + assert!(!is_protected(&scratch.export).unwrap()); + assert!(read(&scratch.export, None).is_err()); } - /// Offered without one, it asks rather than failing. + /// A target the rename cannot replace: the staging file it wrote goes too. #[test] - fn a_protected_export_asks_for_a_phrase_rather_than_failing() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let target = directory.join("library.devnotes"); - - write( - &target.to_string_lossy(), - &bundle(), - &directory, + fn an_export_that_cannot_replace_its_target_leaves_no_staging_file() { + let scratch = scratch(); + std::fs::create_dir_all(&scratch.export).unwrap(); + std::fs::write(Path::new(&scratch.export).join("kept"), b"inside").unwrap(); + + let refused = write( + &scratch.export, + &bundle(Vec::new()), + &scratch.attachments, &library(), - Some("a shared phrase"), - ) - .unwrap(); + None, + ); - let error = read(&target.to_string_lossy(), None).unwrap_err(); - assert!(matches!(error, StorageError::PassphraseRequired), "{error}"); - assert!(is_protected(&target.to_string_lossy()).unwrap()); + assert!(matches!(refused, Err(StorageError::File(_)))); + let folder = Path::new(&scratch.export).parent().unwrap(); + let staged = std::fs::read_dir(folder) + .unwrap() + .filter_map(Result::ok) + .any(|entry| entry.file_name().to_string_lossy().ends_with(".tmp")); + assert!(!staged); + assert!(Path::new(&scratch.export).join("kept").is_file()); } + /// A plain JSON export from before the archive is still read: no attachments, no phrase. #[test] - fn the_wrong_phrase_is_refused_rather_than_read_as_nonsense() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let target = directory.join("library.devnotes"); - - write( - &target.to_string_lossy(), - &bundle(), - &directory, - &library(), - Some("a shared phrase"), + fn a_json_export_from_before_the_archive_is_read_without_attachments() { + let scratch = scratch(); + std::fs::write( + &scratch.export, + serde_json::to_string(&bundle(Vec::new())).unwrap(), ) .unwrap(); - let error = read(&target.to_string_lossy(), Some("the wrong one")).unwrap_err(); + let mut read = read(&scratch.export, None).unwrap(); - assert!(matches!(error, StorageError::WrongPassphrase), "{error}"); + assert_eq!(notes_of(&read), [note()]); + assert_eq!(read.1.take("a-1.png"), None); + assert!(!is_protected(&scratch.export).unwrap()); } - /// Asked before an import starts: a file whose payload does not parse still answers. #[test] - fn whether_a_file_is_protected_is_answered_without_reading_the_bundle() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let target = directory.join("library.devnotes"); - write( - &target.to_string_lossy(), - &bundle(), - &directory, - &library(), - None, - ) - .unwrap(); - - // The entry is there and is nonsense; the recipe alone decides the answer. - let mut rewritten = ZipWriter::new(std::fs::File::create(&target).unwrap()); - rewritten.start_file(BUNDLE_ENTRY, deflated()).unwrap(); - rewritten.write_all(b"not json at all").unwrap(); - rewritten.finish().unwrap(); + fn a_file_that_is_no_export_is_refused_as_a_format() { + let scratch = scratch(); + let path = Path::new(&scratch.export); + let json = serde_json::to_vec(&bundle(Vec::new())).unwrap(); + let refused = || { + matches!( + read(&scratch.export, Some("phrase")), + Err(StorageError::ImportFormat(_)) + ) + }; - assert!(!is_protected(&target.to_string_lossy()).unwrap()); - // The import that follows is what says the file is unreadable. - assert!(read(&target.to_string_lossy(), None).is_err()); + zip_of(path, &[("other.txt", b"x")]); + assert!(refused(), "an archive without a bundle"); + zip_of(path, &[("bundle.json", &[0xff, 0xfe])]); + assert!(refused(), "an archived bundle that is not text"); + zip_of(path, &[("recipe.json", b"garbage"), ("bundle.json", &json)]); + assert!(refused(), "an unreadable recipe"); + std::fs::write(path, b"PK\x03\x04 and nothing else").unwrap(); + assert!(refused(), "a broken archive"); + std::fs::write(path, [0xff, 0xfe]).unwrap(); + assert!(refused(), "a plain file that is not text"); } - /// An ordinary export needs no phrase, and must not be made to ask for one. + /// A hundred times its compressed size, past a floor, is a decompression bomb. #[test] - fn an_unprotected_export_is_not_reported_as_protected() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let target = directory.join("library.devnotes"); + fn an_entry_that_expands_past_its_ceiling_is_refused() { + let scratch = scratch(); + let bomb = vec![b' '; usize::try_from(MIN_CEILING).unwrap() + 1]; + zip_of(Path::new(&scratch.export), &[("bundle.json", &bomb)]); - write( - &target.to_string_lossy(), - &bundle(), - &directory, - &library(), - None, - ) - .unwrap(); + let refused = read(&scratch.export, None); - assert!(!is_protected(&target.to_string_lossy()).unwrap()); + assert!( + matches!(refused, Err(StorageError::ImportFormat(said)) if said.contains("expands past")) + ); } + /// A bundle written as plain JSON, past what an archive may expand to, is refused before it + /// is read whole. #[test] - fn a_read_stops_one_byte_past_its_limit() { - assert_eq!( - read_at_most(&b"four"[..], 4).unwrap(), - Some(b"four".to_vec()) - ); - assert_eq!(read_at_most(&b"five!"[..], 4).unwrap(), None); + fn a_plain_bundle_past_its_ceiling_is_refused() { + let scratch = scratch(); + let file = File::create(&scratch.export).unwrap(); + file.set_len(PLAIN_CEILING + 1).unwrap(); + drop(file); + + let refused = read(&scratch.export, None); + + assert!(matches!(refused, Err(StorageError::ImportFormat(said)) if said.contains("past"))); } - /// A deflate stream that expands far past what it weighs is refused rather than read. + /// More than an attachment may hold is reported missing, like bytes the archive lacks. #[test] - fn a_bundle_expanding_past_the_ceiling_is_refused() { - let scratch = tempfile::tempdir().unwrap(); - let target = scratch.path().join("bomb.devnotes"); - let mut zip = ZipWriter::new(File::create(&target).unwrap()); - zip.start_file( - BUNDLE_ENTRY, - SimpleFileOptions::default().compression_method(CompressionMethod::Deflated), - ) - .unwrap(); - let chunk = vec![b' '; 1024 * 1024]; - for _ in 0..=MIN_CEILING / 1024 / 1024 { - zip.write_all(&chunk).unwrap(); - } - zip.finish().unwrap(); + fn an_attachment_entry_past_ten_megabytes_is_not_taken() { + let scratch = scratch(); + let json = serde_json::to_vec(&bundle(Vec::new())).unwrap(); + let big = vec![0u8; usize::try_from(MAX_BYTES).unwrap() + 1]; + zip_of( + Path::new(&scratch.export), + &[("bundle.json", &json), ("attachments/a-1.bin", &big)], + ); - assert!(matches!( - read(&target.to_string_lossy(), None), - Err(StorageError::ImportFormat(reason)) if reason.contains("expands past") - )); + let mut read = read(&scratch.export, None).unwrap(); + + assert_eq!(read.1.take("a-1.bin"), None); } - /// Past the limit an attachment is counted missing, as one the archive did not carry. + /// What it prints says whether a key is held, never the key. #[test] - fn an_attachment_larger_than_the_limit_is_not_handed_over() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let vault = library(); - let too_big = usize::try_from(MAX_BYTES).unwrap() + 1; - seal_beside(&directory, &vault, &vec![0u8; too_big]); - let mut exported = bundle(); - exported.attachments = vec![record()]; - - for protected in [None, Some("a phrase for the file")] { - let target = directory.join("library.devnotes"); - write( - &target.to_string_lossy(), - &exported, - &directory, - &vault, - protected, - ) - .unwrap(); - let (_, mut payload) = read(&target.to_string_lossy(), protected).unwrap(); + fn a_payload_prints_whether_it_is_protected_and_nothing_more() { + let scratch = scratch(); + write( + &scratch.export, + &bundle(Vec::new()), + &scratch.attachments, + &library(), + Some("export phrase"), + ) + .unwrap(); + let protected = read(&scratch.export, Some("export phrase")).unwrap().1; - assert!(payload.take(&record().stored_name()).is_none()); - } + assert_eq!(format!("{protected:?}"), "Payload::Archive(protected)"); + assert_eq!(format!("{:?}", Payload::Empty), "Payload::Empty"); } } diff --git a/crates/engine/src/transfer/model.rs b/crates/engine/src/transfer/model.rs index 453c6bf46..4b198433c 100644 --- a/crates/engine/src/transfer/model.rs +++ b/crates/engine/src/transfer/model.rs @@ -261,206 +261,286 @@ pub fn to_markdown(notes: &[Note], space_names: &BTreeMap) -> St #[cfg(test)] mod tests { + use serde_json::{Value, json}; + use super::*; use crate::notes::checklist::ChecklistItem; - use crate::notes::fixtures::note as sample; + use crate::notes::fixtures::{NOW, at, note}; - fn spaces() -> BTreeMap { - BTreeMap::from([("s-1".to_string(), "Personal".to_string())]) + fn with_id(id: &str) -> Note { + Note { + id: id.to_string(), + ..note() + } } - #[test] - fn a_shared_note_carries_its_space_context_and_tags() { - let mut note = sample(); - note.source = "API Gateway / Auth".to_string(); + /// A file of this version holding `notes`, each a note's JSON. + fn file_of(notes: &[Value]) -> String { + json!({ + "version": FORMAT_VERSION, + "exportedAt": NOW, + "spaces": [], + "notes": notes, + }) + .to_string() + } - let markdown = to_markdown(&[note], &spaces()); + fn note_json(id: &str, field: &str, value: Value) -> Value { + let mut written = serde_json::to_value(with_id(id)).unwrap(); + written[field] = value; + written + } - assert!(markdown.contains("## Title")); - assert!(markdown.contains("_Personal · API Gateway / Auth · #auth_")); - assert!(markdown.contains("```txt\nContent\n```")); + fn format_error(answer: Result) -> String { + match answer { + Err(StorageError::ImportFormat(message)) => message, + other => panic!("expected a format error, got {other:?}"), + } } #[test] - fn a_note_is_shared_as_the_markdown_it_is() { - let mut note = sample(); - note.kind = NoteKind::Note; - note.content = "## Standup\n\n- [x] ship it\n".to_string(); + fn a_file_of_this_version_reads_back_whole() { + let bundle = Bundle { + version: FORMAT_VERSION, + exported_at: at(NOW), + spaces: Vec::new(), + folders: Vec::new(), + notes: vec![with_id("a"), with_id("b")], + attachments: Vec::new(), + }; - let markdown = to_markdown(&[note], &spaces()); + let read = read_bundle(&serde_json::to_string(&bundle).unwrap()).unwrap(); - assert!(markdown.contains("## Standup\n\n- [x] ship it\n")); - assert!(!markdown.contains("```")); + assert_eq!(read.bundle.notes, bundle.notes); + assert!(read.degraded.is_empty()); } + /// No version bump for what was added since: an older file still reads. #[test] - fn a_drawing_is_shared_as_its_words() { - let mut note = sample(); - note.kind = NoteKind::Drawing; - note.content = r#"{"scene":{"objects":[{"text":"API"},{"type":"Rect"}]}}"#.to_string(); + fn a_file_from_before_folders_and_attachments_reads_with_none() { + let read = read_bundle(&file_of(&[note_json("a", "title", json!("T"))])).unwrap(); - let markdown = to_markdown(&[note], &spaces()); - - assert!(markdown.contains("\nAPI\n")); - assert!(!markdown.contains("scene")); + assert!(read.bundle.folders.is_empty() && read.bundle.attachments.is_empty()); + assert_eq!(read.bundle.notes.len(), 1); } + /// Read off the raw JSON first: a future format may not deserialise at all. #[test] - fn a_note_already_containing_a_fence_is_not_cut_in_half() { - let mut note = sample(); - note.content = "```sh\necho hi\n```".to_string(); + fn a_file_from_a_newer_version_is_refused_by_its_version() { + let newer = json!({ "version": FORMAT_VERSION + 1, "notes": "not a list" }).to_string(); - let markdown = to_markdown(&[note], &spaces()); + let message = format_error(read_bundle(&newer)); - assert!(markdown.contains("````txt")); - assert!(markdown.ends_with("````\n")); + assert!( + message.contains(&format!("format version {}", FORMAT_VERSION + 1)), + "{message}" + ); } #[test] - fn a_todo_list_is_shared_as_a_markdown_task_list() { - let mut note = sample(); - note.kind = NoteKind::Checklist; - note.content = String::new(); - note.items = vec![ - ChecklistItem { - text: "Review".to_string(), - done: true, - }, - ChecklistItem { - text: "Ship".to_string(), - done: false, - }, - ]; - - let markdown = to_markdown(&[note], &spaces()); - - assert!(markdown.contains("- [x] Review")); - assert!(markdown.contains("- [ ] Ship")); - assert!(!markdown.contains("```")); + fn a_file_that_is_not_a_bundle_is_refused_as_a_format() { + for text in ["not json", "{}", r#"{"version": 1}"#] { + assert!( + matches!(read_bundle(text), Err(StorageError::ImportFormat(_))), + "{text}" + ); + } } + /// One note from a newer DevNotes must not fail the whole file: its value comes down to the + /// default, and the note is named so the loss is said. #[test] - fn an_untitled_note_still_gets_a_heading() { - let mut note = sample(); - note.title = " ".to_string(); + fn a_value_this_build_does_not_know_comes_down_to_the_default_and_is_counted() { + let notes = vec![ + note_json("language", "language", json!("cobol-2099")), + note_json("kind", "kind", json!("hologram")), + note_json("priority", "priority", json!("yesterday")), + note_json("known", "language", json!("sql")), + ]; - assert!(to_markdown(&[note], &spaces()).starts_with("## —")); + let read = read_bundle(&file_of(¬es)).unwrap(); + + let degraded: Vec<&str> = read.degraded.iter().map(String::as_str).collect(); + assert_eq!(degraded, ["kind", "language", "priority"]); + let notes = &read.bundle.notes; + assert_eq!(notes[0].language, Language::default()); + assert_eq!(notes[1].kind, NoteKind::default()); + assert_eq!(notes[2].priority, Priority::default()); + assert_eq!(notes[3].language.to_string(), "sql"); } + /// An export from before priorities carries no such key. #[test] - fn a_bundle_from_a_newer_version_is_refused_rather_than_half_read() { - // Read off the raw JSON first, so the answer names the version and not a serde field. - let json = serde_json::json!({ - "version": FORMAT_VERSION + 1, - "exportedAt": "2026-07-25T09:00:00.000Z", - "spaces": [], - "notes": [{ "shape": "from the future" }], - }) - .to_string(); + fn a_note_without_a_priority_reads_as_having_none() { + let mut written = note_json("a", "title", json!("T")); + written.as_object_mut().unwrap().remove("priority"); - let StorageError::ImportFormat(message) = read_bundle(&json).unwrap_err() else { - panic!("expected a format error"); - }; + let read = read_bundle(&file_of(&[written])).unwrap(); - assert!(message.contains("format version")); + assert_eq!(read.bundle.notes[0].priority, Priority::None); + assert!(read.degraded.is_empty()); } - /// The file a newer DevNotes writes once its `Language` has grown a variant. - fn bundle_with(field: &str, value: serde_json::Value) -> String { - let mut json = serde_json::json!({ - "version": FORMAT_VERSION, - "exportedAt": "2026-07-25T09:00:00.000Z", - "spaces": [{ "id": "s-1", "name": "Personal" }], - "notes": [serde_json::to_value(sample()).unwrap()], - }); - json["notes"][0][field] = value; + /// Malformed is not newer: a value that is no string at all fails the file. + #[test] + fn a_value_that_is_not_even_a_string_is_refused_not_degraded() { + let malformed = file_of(&[note_json("a", "language", json!(42))]); - json.to_string() + assert!(matches!( + read_bundle(&malformed), + Err(StorageError::ImportFormat(_)) + )); } #[test] - fn an_unknown_language_is_brought_down_to_the_default_rather_than_refused() { - let read = read_bundle(&bundle_with("language", "from-the-future".into())).unwrap(); - - assert_eq!(read.bundle.notes[0].language, Language::default()); - assert_eq!(read.degraded.len(), 1); - assert!(read.degraded.contains(&read.bundle.notes[0].id)); + fn an_export_or_an_import_needs_a_file() { + assert_eq!(validate_path(" ").unwrap_err().field, "path"); + assert!(validate_path("notes.devnotes").is_ok()); } #[test] - fn an_unknown_kind_is_brought_down_the_same_way() { - let read = read_bundle(&bundle_with("kind", "from-the-future".into())).unwrap(); - - assert_eq!(read.bundle.notes[0].kind, NoteKind::default()); - assert_eq!(read.degraded.len(), 1); + fn an_export_of_nothing_reports_nothing_written() { + let report = ExportReport::nothing(true); + + let counted = [ + report.notes, + report.spaces, + report.folders, + report.attachments, + ]; + assert_eq!(counted, [0; 4]); + assert_eq!(report.attachments_unreadable, 0); + assert!(report.protected); } + /// Its space, its source and its tags say where it comes from, under its title. #[test] - fn an_unknown_priority_is_brought_down_the_same_way() { - let read = read_bundle(&bundle_with("priority", "from-the-future".into())).unwrap(); + fn a_shared_snippet_is_its_title_where_it_comes_from_and_a_fenced_block_in_its_language() { + let snippet = Note { + title: " Deploy ".to_string(), + source: "https://example.org".to_string(), + tags: vec!["ops".to_string(), "k8s".to_string()], + content: "kubectl apply\n\n".to_string(), + ..note() + }; + let spaces = BTreeMap::from([("s-1".to_string(), "Work".to_string())]); - assert_eq!(read.bundle.notes[0].priority, Priority::default()); - assert_eq!(read.degraded.len(), 1); + let shared = to_markdown(&[snippet], &spaces); + + let language = Language::Txt; + assert_eq!( + shared, + format!( + "## Deploy\n\n_Work · https://example.org · #ops #k8s_\n\n```{language}\nkubectl apply\n```\n" + ) + ); } - /// An export from before priorities carries no such key. #[test] - fn a_note_without_a_priority_reads_as_having_none() { - let mut json: serde_json::Value = - serde_json::from_str(&bundle_with("priority", "high".into())).unwrap(); - json["notes"][0].as_object_mut().unwrap().remove("priority"); + fn a_note_without_a_title_or_anything_to_say_where_it_comes_from_is_headed_by_a_dash() { + let bare = Note { + title: " ".to_string(), + tags: Vec::new(), + ..note() + }; - let read = read_bundle(&json.to_string()).unwrap(); + let shared = to_markdown(&[bare], &BTreeMap::new()); - assert_eq!(read.bundle.notes[0].priority, Priority::None); - assert!(read.degraded.is_empty()); + assert!(shared.starts_with("## —\n\n```"), "{shared}"); } + /// Longer than the longest run inside, or a note holding a block would cut its own in two. #[test] - fn a_known_value_is_left_exactly_as_written() { - let read = read_bundle(&bundle_with("language", "sql".into())).unwrap(); + fn a_fence_is_longer_than_any_run_of_backticks_it_holds() { + let cases = [ + ("plain", "```"), + ("a `b` c", "```"), + ("```rust\nx\n```", "````"), + ("`````", "``````"), + ]; - assert_eq!(read.bundle.notes[0].language.to_string(), "sql"); - assert!(read.degraded.is_empty()); + for (content, fence) in cases { + let held = Note { + content: content.to_string(), + ..note() + }; + let shared = to_markdown(&[held], &BTreeMap::new()); + let opening = shared.lines().find(|line| line.starts_with('`')).unwrap(); + assert_eq!( + opening.trim_end_matches(char::is_alphanumeric), + fence, + "{content}" + ); + } } - /// Only a string this build cannot name is degraded. + /// A Note is the Markdown it already is, a list a task list, a sheet its lines, a drawing + /// its words. #[test] - fn a_language_that_is_not_a_string_is_still_a_format_error() { - assert!(matches!( - read_bundle(&bundle_with("language", 42.into())).unwrap_err(), - StorageError::ImportFormat(_) - )); - } + fn each_kind_is_shared_as_what_it_reads_as() { + let items = vec![ + ChecklistItem { + text: "Ship".to_string(), + done: true, + }, + ChecklistItem { + text: "Tell".to_string(), + done: false, + }, + ]; + let scene = r#"{"objects":[{"type":"textbox","text":"Login flow"}]}"#; + let cases = [ + ( + NoteKind::Note, + "# Plan\n\n- one\n".to_string(), + Vec::new(), + "# Plan\n\n- one\n", + ), + ( + NoteKind::Calc, + "2 + 2\n".to_string(), + Vec::new(), + "```\n2 + 2\n```\n", + ), + (NoteKind::Drawing, scene.to_string(), Vec::new(), ""), + (NoteKind::Checklist, String::new(), items.clone(), ""), + ]; - #[test] - fn a_file_that_is_not_a_bundle_is_reported_as_such() { - assert!(matches!( - read_bundle("{\"hello\":true}").unwrap_err(), - StorageError::ImportFormat(_) - )); + for (kind, content, items, body) in cases { + let shared = to_markdown( + &[Note { + kind, + content: content.clone(), + items: items.clone(), + tags: Vec::new(), + ..note() + }], + &BTreeMap::new(), + ); + let expected = match kind { + NoteKind::Drawing => format!("{}\n", drawing::words(&content)), + NoteKind::Checklist => format!("{}\n", checklist::to_markdown(&items)), + _ => body.to_string(), + }; + assert_eq!(shared, format!("## Title\n\n{expected}"), "{kind:?}"); + } } #[test] - fn a_bundle_round_trips_through_its_own_format() { - let bundle = Bundle { - version: FORMAT_VERSION, - exported_at: sample().created_at, - spaces: vec![Space { - id: "s-1".to_string(), - name: "Personal".to_string(), - pinned: false, - }], - folders: Vec::new(), - notes: vec![sample()], - attachments: Vec::new(), + fn notes_are_shared_one_after_the_other_a_blank_line_apart() { + let first = Note { + title: "First".to_string(), + tags: Vec::new(), + ..note() + }; + let second = Note { + title: "Second".to_string(), + ..first.clone() }; - let read = read_bundle(&serde_json::to_string(&bundle).unwrap()).unwrap(); + let shared = to_markdown(&[first, second], &BTreeMap::new()); - assert_eq!(read.bundle.notes.len(), 1); - assert_eq!(read.bundle.notes[0].title, "Title"); - assert_eq!(read.bundle.spaces[0].name, "Personal"); - assert!(read.degraded.is_empty()); + assert!(shared.contains("```\n\n## Second\n"), "{shared}"); + assert_eq!(shared.matches("## ").count(), 2); } } From 64a54976293ecf44e8dfb2841fd4712569ca117c Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:11:03 +0100 Subject: [PATCH 27/95] Vault: unit tests rewritten for the gate and the passphrase floor (#1750) Co-authored-by: Claude Opus 5.5 --- crates/engine/src/vault.rs | 43 ++++++----- crates/engine/src/vault/gate.rs | 133 +++++++++++++++++++++----------- 2 files changed, 110 insertions(+), 66 deletions(-) diff --git a/crates/engine/src/vault.rs b/crates/engine/src/vault.rs index dc70ada4c..48df60f5f 100644 --- a/crates/engine/src/vault.rs +++ b/crates/engine/src/vault.rs @@ -167,30 +167,31 @@ mod tests { assert!(wiped.get()); } - /// An export is the one file meant to travel, so its phrase meets the same floor. + /// In characters: six accented letters are twelve bytes, and a byte count would let them by. #[test] - fn an_export_phrase_meets_the_floor_and_no_phrase_is_no_protection() { - assert!(validate_protection(Some("eleven char")).is_err()); - assert!(validate_protection(Some("twelve chars")).is_ok()); - assert!(validate_protection(None).is_ok()); - } - - #[test] - fn a_passphrase_too_short_to_be_worth_deriving_is_refused() { - assert!(validate("short").is_err()); - assert!(validate("1234567").is_err()); - } - - #[test] - fn a_passphrase_of_the_minimum_length_is_accepted() { - assert!(validate("123456789012").is_ok()); - assert!(validate("12345678901").is_err()); + fn a_passphrase_is_chosen_twelve_characters_long_at_least() { + let cases = [ + ("eleven char", false), + ("twelve chars", true), + ("éééééé", false), + ("éééééééééééé", true), + ]; + + for (phrase, accepted) in cases { + let answer = validate(phrase); + assert_eq!(answer.is_ok(), accepted, "{phrase:?}"); + if let Err(refused) = answer { + assert_eq!(refused.field, "passphrase"); + } + } } - /// Six accented letters are twelve bytes: a byte count would let them pass. + /// An export is the one file meant to travel, so its phrase meets the same floor; no + /// phrase is no protection, which the interface says. #[test] - fn the_length_is_counted_in_characters() { - assert!(validate("éàèùçâêîôûëï").is_ok()); - assert!(validate("éàèùçâ").is_err()); + fn an_export_s_phrase_meets_the_same_floor_and_none_is_allowed() { + assert!(validate_protection(None).is_ok()); + assert!(validate_protection(Some("eleven char")).is_err()); + assert!(validate_protection(Some("twelve chars")).is_ok()); } } diff --git a/crates/engine/src/vault/gate.rs b/crates/engine/src/vault/gate.rs index 88b73cdd9..5c61c1ea9 100644 --- a/crates/engine/src/vault/gate.rs +++ b/crates/engine/src/vault/gate.rs @@ -102,79 +102,122 @@ fn install(directory: &Path, db: &Db, vault: Vault) -> Result<(), StorageError> mod tests { use super::*; + const PHRASE: &str = "a passphrase"; + + /// A scratch library folder and the empty connection slot the gate fills. + fn folder() -> (tempfile::TempDir, Db) { + (tempfile::tempdir().unwrap(), std::sync::Mutex::new(None)) + } + + fn is_open(db: &Db) -> bool { + db.lock().unwrap().is_some() + } + fn close(db: &Db) { *db.lock().unwrap() = None; } + /// ⚠️ A database without its key file is neither new nor locked: asking for a new phrase + /// would be the first step towards a key that opens nothing it holds. #[test] - fn a_library_created_is_open_and_unlocks_again_with_its_phrase_alone() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let db: Db = std::sync::Mutex::new(None); + fn a_folder_is_new_locked_or_missing_its_key_by_what_it_holds() { + let (scratch, db) = folder(); + let directory = scratch.path(); - create("a passphrase", &directory, &db, Cost::FOR_TESTS).unwrap(); - assert!(db.lock().unwrap().is_some()); + assert_eq!(state_of(directory), VaultState::Absent); + create(PHRASE, directory, &db, Cost::FOR_TESTS).unwrap(); close(&db); + assert_eq!(state_of(directory), VaultState::Locked); + std::fs::remove_file(file::path_in(directory)).unwrap(); + assert_eq!(state_of(directory), VaultState::KeyMissing); + } + + /// Created, the library is open, with its attachments folder made for every writer. + #[test] + fn a_library_created_is_open_and_its_attachments_folder_is_there() { + let (scratch, db) = folder(); + let directory = scratch.path().join("nested").join("library"); - assert!(unlock("not the phrase", &directory, &db).is_err()); - unlock("a passphrase", &directory, &db).unwrap(); - assert!(db.lock().unwrap().is_some()); + create(PHRASE, &directory, &db, Cost::FOR_TESTS).unwrap(); - close(&db); + assert!(is_open(&db)); + assert!(directory.join(crate::layout::ATTACHMENTS).is_dir()); } #[test] - fn a_changed_phrase_opens_the_library_and_the_old_one_no_longer_does() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let db: Db = std::sync::Mutex::new(None); - create("a passphrase", &directory, &db, Cost::FOR_TESTS).unwrap(); - - let changed = change("a passphrase", "another phrase", &db, Cost::FOR_TESTS).unwrap(); + fn a_library_unlocks_with_its_phrase_alone() { + let (scratch, db) = folder(); + create(PHRASE, scratch.path(), &db, Cost::FOR_TESTS).unwrap(); close(&db); - assert_eq!(changed.backups_left, 0); - assert!(unlock("a passphrase", &directory, &db).is_err()); - unlock("another phrase", &directory, &db).unwrap(); + let wrong = unlock("not the phrase", scratch.path(), &db); - close(&db); + assert!(matches!(wrong, Err(StorageError::WrongPassphrase))); + assert!(!is_open(&db)); + unlock(PHRASE, scratch.path(), &db).unwrap(); + assert!(is_open(&db)); } + /// The key file is the only way into the notes beside it: never written over, and a + /// database without one is answered as damaged rather than given a new key. #[test] - fn a_phrase_is_not_changed_on_a_library_nobody_opened() { - let db: Db = std::sync::Mutex::new(None); - - let refused = change("a passphrase", "another phrase", &db, Cost::FOR_TESTS); - - assert!(matches!(refused, Err(StorageError::Locked))); + fn a_library_is_never_created_over_a_key_file_or_a_database() { + let (scratch, db) = folder(); + let directory = scratch.path(); + create(PHRASE, directory, &db, Cost::FOR_TESTS).unwrap(); + close(&db); + let database = directory.join(crate::layout::DATABASE); + let key = file::path_in(directory); + + let over_both = create("another phrase", directory, &db, Cost::FOR_TESTS); + let kept = std::fs::read(&database).unwrap(); + std::fs::rename(&database, directory.join("aside")).unwrap(); + let over_the_key = create("another phrase", directory, &db, Cost::FOR_TESTS); + std::fs::rename(directory.join("aside"), &database).unwrap(); + std::fs::remove_file(&key).unwrap(); + let over_the_database = create("another phrase", directory, &db, Cost::FOR_TESTS); + + assert!(over_both.is_err()); + assert!(matches!(over_the_key, Err(StorageError::Vault(_)))); + assert!(matches!(over_the_database, Err(StorageError::Damaged(_)))); + assert_eq!(std::fs::read(&database).unwrap(), kept); + assert!(!is_open(&db)); } - /// A key written over a database it did not seal would open nothing that database holds. + /// Not a re-encryption: the key is rewrapped, and the library stays open on it. #[test] - fn a_database_left_without_its_key_is_answered_as_damaged() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - assert!(refuse_a_database_without_its_key(&directory).is_ok()); + fn a_changed_phrase_opens_the_library_and_the_retired_one_no_longer_does() { + let (scratch, db) = folder(); + create(PHRASE, scratch.path(), &db, Cost::FOR_TESTS).unwrap(); - std::fs::write(directory.join(crate::layout::DATABASE), b"a sealed library").unwrap(); + let changed = change(PHRASE, "the next passphrase", &db, Cost::FOR_TESTS).unwrap(); + assert_eq!((changed.backups_rewrapped, changed.backups_left), (0, 0)); + assert!(is_open(&db)); + close(&db); assert!(matches!( - refuse_a_database_without_its_key(&directory), - Err(StorageError::Damaged(_)) + unlock(PHRASE, scratch.path(), &db), + Err(StorageError::WrongPassphrase) )); + unlock("the next passphrase", scratch.path(), &db).unwrap(); } - /// A database left without its key file is neither new nor locked. #[test] - fn a_database_without_its_key_file_is_named_as_such() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - assert_eq!(state_of(&directory), VaultState::Absent); - - std::fs::write(directory.join(crate::layout::DATABASE), b"a sealed library").unwrap(); - assert_eq!(state_of(&directory), VaultState::KeyMissing); + fn a_phrase_is_changed_only_on_an_open_library_and_from_its_current_one() { + let (scratch, db) = folder(); + create(PHRASE, scratch.path(), &db, Cost::FOR_TESTS).unwrap(); + + let wrong = change( + "not the phrase", + "the next passphrase", + &db, + Cost::FOR_TESTS, + ); + close(&db); + let closed = change(PHRASE, "the next passphrase", &db, Cost::FOR_TESTS); - file::create(&directory, "a passphrase", Cost::FOR_TESTS).unwrap(); - assert_eq!(state_of(&directory), VaultState::Locked); + assert!(matches!(wrong, Err(StorageError::WrongPassphrase))); + assert!(matches!(closed, Err(StorageError::Locked))); + unlock(PHRASE, scratch.path(), &db).unwrap(); } } From e34a724683591bb65c89074cc02699a80900f5fc Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:17:20 +0100 Subject: [PATCH 28/95] Import and export: unit tests rewritten for merging and services (#1749) * Rewrite the tests of what an export takes and an import merges, and of the transfer services Co-Authored-By: Claude Opus 5.5 * A folder of the same name under another parent is not matched Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/tests/commands/transfer.rs | 281 +++-- crates/engine/tests/transfer.rs | 1245 ++++++++-------------- 2 files changed, 643 insertions(+), 883 deletions(-) diff --git a/crates/engine/tests/commands/transfer.rs b/crates/engine/tests/commands/transfer.rs index fab076662..ca029644b 100644 --- a/crates/engine/tests/commands/transfer.rs +++ b/crates/engine/tests/commands/transfer.rs @@ -1,5 +1,6 @@ +use engine::Engine; use engine::error::ErrorCode; -use engine::notes::create_note; +use engine::notes::{create_note, query_notes}; use engine::transfer::model::ExportScope; use engine::transfer::{ count_export, export_is_protected, export_notes, import_notes, share_notes, @@ -8,147 +9,217 @@ use engine::transfer::{ use super::common::snippet; use super::{Session, code}; -/// Out of one library and into another, which gains the space and the note. -#[test] -fn an_export_is_imported_into_another_library() { - let scratch = tempfile::tempdir().unwrap(); - let source = Session::on_disk(&scratch.path().join("source")); - let target = Session::on_disk(&scratch.path().join("target")); - let space = source.space("Personal"); - source.call(|e| create_note(e, snippet(&space))).unwrap(); - let path = scratch - .path() - .join("notes.devnotes") - .to_string_lossy() - .to_string(); - - let exported = source - .wait(|e| export_notes(e, path.clone(), ExportScope::Library, None)) - .unwrap(); - let protected = export_is_protected(&path).unwrap(); - let imported = target.wait(|e| import_notes(e, path, None)).unwrap(); +/// Twelve characters at least, as any phrase chosen here. +const PHRASE: &str = "a long export phrase"; + +fn note(session: &Session, space_id: &str, title: &str) -> String { + let draft = engine::notes::model::NoteDraft { + title: title.to_string(), + ..snippet(space_id) + }; + session.call(|e| create_note(e, draft)).unwrap().note.id +} + +fn path_in(scratch: &tempfile::TempDir, name: &str) -> String { + scratch.path().join(name).to_string_lossy().to_string() +} - assert_eq!((exported.notes, exported.protected), (1, false)); - assert!(!protected); - assert_eq!(imported.notes_imported, 1); - assert_eq!(target.spaces(), ["Personal"]); +fn titles(session: &Session) -> Vec { + let query = engine::notes::view::NotesQuery { + space_id: None, + folder_id: None, + search: String::new(), + filter: engine::notes::view::NoteFilter::All, + tags: Vec::new(), + languages: Vec::new(), + kinds: Vec::new(), + priorities: Vec::new(), + order: engine::notes::view::NoteOrder::default(), + grouping: engine::notes::view::Grouping::default(), + ranked: false, + now: chrono::Utc::now(), + tz_offset_minutes: 0, + pinned_first: true, + }; + let view = session.call(|e| query_notes(e, &query)).unwrap(); + let mut titles: Vec = view + .cards() + .map(|card| view.display(card).note.title.clone()) + .collect(); + titles.sort(); + titles } -/// The floor that holds for a library's phrase holds for a file meant to travel. #[test] -fn an_export_under_a_short_phrase_is_refused() { +fn nothing_answers_before_a_library_is_open() { let scratch = tempfile::tempdir().unwrap(); - let session = Session::on_disk(scratch.path()); - let path = scratch - .path() - .join("notes.devnotes") - .to_string_lossy() - .to_string(); - - assert!(matches!( - code(session.wait(|e| export_notes( - e, - path, - ExportScope::Library, - Some("short".to_string()) - ))), - ErrorCode::InvalidInput - )); + let session = Session::locked(); + let export = path_in(&scratch, "notes.devnotes"); + std::fs::write(&export, b"{}").unwrap(); + + let codes = [ + code(session.wait(|e| export_notes(e, export.clone(), ExportScope::Library, None))), + code(session.call(|e| count_export(e, &ExportScope::Library))), + code(session.call(|e| share_notes(e, &["n".to_string()]))), + ]; + + assert!( + codes.iter().all(|found| *found == ErrorCode::Locked), + "{codes:?}" + ); } +/// Checked before anything is read or written: no file chosen, or a phrase too short to protect. #[test] -fn a_shared_selection_reads_as_markdown() { - let session = Session::open(); - let space = session.space("Personal"); - let id = session - .call(|e| create_note(e, snippet(&space))) - .unwrap() - .note - .id; +fn an_export_without_a_file_or_with_a_short_phrase_is_refused_as_input() { + let session = Session::locked(); + let scratch = tempfile::tempdir().unwrap(); + let export = path_in(&scratch, "notes.devnotes"); - let markdown = session.call(|e| share_notes(e, &[id])).unwrap(); + let answers = [ + code(session.wait(|e| export_notes(e, " ".to_string(), ExportScope::Library, None))), + code( + session + .wait(|e| export_notes(e, export, ExportScope::Library, Some("short".to_string()))), + ), + code(session.wait(|e| import_notes(e, String::new(), None))), + code(export_is_protected("")), + ]; - assert!(markdown.contains("Titre")); - assert!(markdown.contains("Contenu")); + assert!( + answers + .iter() + .all(|found| *found == ErrorCode::InvalidInput), + "{answers:?}" + ); } -/// Counted before any dialog, and an export of nothing leaves no file behind. +/// An empty file would read as an export of something. #[test] -fn an_empty_scope_is_counted_as_such_and_exports_no_file() { +fn an_export_of_nothing_writes_no_file() { let scratch = tempfile::tempdir().unwrap(); let session = Session::on_disk(&scratch.path().join("library")); - let full = session.space("Personal"); - let empty = session.space("Vide"); - session.call(|e| create_note(e, snippet(&full))).unwrap(); - let path = scratch.path().join("empty.devnotes"); - - let counted = session - .call(|e| { - count_export( - e, - &ExportScope::Space { - space_id: empty.clone(), - }, - ) - }) - .unwrap(); + let export = path_in(&scratch, "notes.devnotes"); + let report = session .wait(|e| { export_notes( e, - path.to_string_lossy().to_string(), - ExportScope::Space { space_id: empty }, - None, + export.clone(), + ExportScope::Library, + Some(PHRASE.to_string()), ) }) .unwrap(); - assert_eq!(counted, 0); assert_eq!(report.notes, 0); - assert!(!path.exists()); + assert!(report.protected); + assert!(!std::path::Path::new(&export).exists()); assert_eq!( session .call(|e| count_export(e, &ExportScope::Library)) .unwrap(), - 1 + 0 ); } -/// The export is the one copy that needs no passphrase: an attachment whose file cannot be -/// opened is left out and counted, as a missing one is, rather than costing the whole file -/// (#1478, N52). +/// From one library to another, through a protected file: the second asks for the phrase, +/// refuses another, and takes every note with the right one. #[test] -fn an_attachment_that_cannot_be_opened_is_left_out_of_the_export_and_counted() { +fn a_protected_export_imports_into_another_library_with_its_phrase() { let scratch = tempfile::tempdir().unwrap(); - let session = Session::on_disk(&scratch.path().join("library")); - let space = session.space("Personal"); - let note = session - .call(|e| create_note(e, snippet(&space))) - .unwrap() - .note - .id; - let source = scratch.path().join("capture.png"); - std::fs::write(&source, b"\x89PNG").unwrap(); - let attachment = session + let sender = Session::on_disk(&scratch.path().join("sender")); + let work = sender.space("Work"); + note(&sender, &work, "Deploy"); + note(&sender, &work, "Rollback"); + let export = path_in(&scratch, "notes.devnotes"); + assert_eq!( + sender + .call(|e| count_export(e, &ExportScope::Library)) + .unwrap(), + 2 + ); + + let sent = sender .wait(|e| { - engine::attachments::attach_file(e, note.clone(), source.to_string_lossy().to_string()) + export_notes( + e, + export.clone(), + ExportScope::Library, + Some(PHRASE.to_string()), + ) }) .unwrap(); - let stored = engine::attachments::files::directory( - session.engine.db().lock().unwrap().as_ref().unwrap(), - ) - .join(attachment.stored_name()); - std::fs::write(&stored, b"not sealed").unwrap(); - let path = scratch - .path() - .join("notes.devnotes") - .to_string_lossy() - .to_string(); - let report = session - .wait(|e| export_notes(e, path.clone(), ExportScope::Library, None)) + assert_eq!((sent.notes, sent.spaces, sent.protected), (2, 1, true)); + assert!(export_is_protected(&export).unwrap()); + let receiver = Session::on_disk(&scratch.path().join("receiver")); + receiver.wait(engine::index::fill); + assert_eq!( + code(receiver.wait(|e| import_notes(e, export.clone(), None))), + ErrorCode::PassphraseRequired + ); + let wrong = Some("another long phrase".to_string()); + assert_eq!( + code(receiver.wait(|e| import_notes(e, export.clone(), wrong))), + ErrorCode::WrongPassphrase + ); + let report = receiver + .wait(|e| import_notes(e, export.clone(), Some(PHRASE.to_string()))) + .unwrap(); + assert_eq!((report.spaces_created, report.notes_imported), (1, 2)); + assert_eq!(titles(&receiver), ["Deploy", "Rollback"]); + assert_eq!(receiver.call(Engine::index_matches_library), Ok(())); +} + +/// Without a phrase the file is readable by anyone who has it, and says so. +#[test] +fn an_unprotected_export_imports_without_a_phrase() { + let scratch = tempfile::tempdir().unwrap(); + let sender = Session::on_disk(&scratch.path().join("sender")); + let work = sender.space("Work"); + let kept = note(&sender, &work, "Kept"); + note(&sender, &work, "Left"); + let export = path_in(&scratch, "notes.devnotes"); + let chosen = ExportScope::Notes { ids: vec![kept] }; + + let sent = sender + .wait(|e| export_notes(e, export.clone(), chosen, None)) .unwrap(); - assert_eq!((report.notes, report.attachments), (1, 0)); - assert_eq!(report.attachments_unreadable, 1); + assert_eq!((sent.notes, sent.protected), (1, false)); + assert!(!export_is_protected(&export).unwrap()); + let receiver = Session::on_disk(&scratch.path().join("receiver")); + receiver.wait(|e| import_notes(e, export, None)).unwrap(); + assert_eq!(titles(&receiver), ["Kept"]); +} + +#[test] +fn a_file_that_is_no_export_is_answered_by_its_code() { + let scratch = tempfile::tempdir().unwrap(); + let session = Session::on_disk(&scratch.path().join("library")); + let garbage = path_in(&scratch, "garbage.json"); + std::fs::write(&garbage, b"not an export").unwrap(); + let missing = path_in(&scratch, "missing.devnotes"); + + assert_eq!( + code(session.wait(|e| import_notes(e, garbage, None))), + ErrorCode::ImportFormat + ); + assert_eq!( + code(session.wait(|e| import_notes(e, missing, None))), + ErrorCode::FileAccess + ); +} + +/// Nothing is sent anywhere: "share" stops at Markdown for the clipboard. +#[test] +fn shared_notes_are_markdown_named_by_their_space() { + let session = Session::open(); + let work = session.space("Work"); + let id = note(&session, &work, "Deploy"); + + let shared = session.call(|e| share_notes(e, &[id])).unwrap(); + + assert!(shared.starts_with("## Deploy\n\n_Work"), "{shared}"); } diff --git a/crates/engine/tests/transfer.rs b/crates/engine/tests/transfer.rs index 574db1057..29ce2ddf9 100644 --- a/crates/engine/tests/transfer.rs +++ b/crates/engine/tests/transfer.rs @@ -1,892 +1,581 @@ -use engine::db::Library; +//! What an export takes from a library and what an import merges into another, on temporary +//! libraries: the file between them is the format's own tests' business. +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Path, PathBuf}; + +use chrono::{DateTime, Utc}; use engine::attachments::model::Attachment; -use engine::attachments::store as attachments; -use engine::db::open_in_memory; -use engine::notes::kind::NoteKind; +use engine::attachments::{sealed, store as attachments}; +use engine::db::{Library, open, open_in_memory, test_vault}; +use engine::folders::model::Folder; +use engine::folders::store as folders; use engine::notes::language::Language; -use engine::notes::model::NoteDraft; +use engine::notes::model::{Note, NoteDraft}; use engine::notes::store as notes; -use engine::spaces::store as spaces; -use engine::transfer::bundle::{self, collect, merge as merge_bundle}; -use engine::transfer::file; -use engine::transfer::file::Payload; -use engine::transfer::model::{self, Bundle, ExportScope, ImportReport, IncomingBundle}; +use engine::transfer::bundle::{collect, count, merge, of, space_names}; +use engine::transfer::file::{self, Payload}; +use engine::transfer::model::{Bundle, ExportScope, FORMAT_VERSION, ImportReport, IncomingBundle}; mod common; -use common::{snippet, t0}; +use common::{snippet, space, t0, t1}; -fn draft(space_id: &str, title: &str) -> NoteDraft { - NoteDraft { +fn note_in(connection: &mut Library, space_id: &str, folder_id: Option<&str>, title: &str) -> Note { + let draft = NoteDraft { title: title.to_string(), - language: Language::Sql, - content: "select 1".to_string(), - source: "API / Auth".to_string(), - tags: vec!["auth".to_string()], + folder_id: folder_id.map(str::to_string), ..snippet(space_id) - } + }; + notes::create(connection, draft, t0()).unwrap() } -/// No attachment travels in these scenarios — the archive itself is covered in -/// `transfer::file`. `Payload::Empty` hands over no bytes, so the directory is never -/// written to. -fn merge(connection: &mut Library, bundle: IncomingBundle) -> ImportReport { - merge_bundle( - connection, - bundle, - &mut Payload::Empty, - &std::env::temp_dir(), - ) - .unwrap() +fn folder_in(connection: &mut Library, space_id: &str, parent: Option<&str>, name: &str) -> String { + folders::create(connection, space_id, parent, name, t0()) + .unwrap() + .id } -/// A populated database, the way a user would have one. -fn library() -> Library { - let mut connection = open_in_memory().unwrap(); - let personal = spaces::create(&mut connection, "Personal").unwrap().id; - let boulot = spaces::create(&mut connection, "Boulot").unwrap().id; - notes::create(&mut connection, draft(&personal, "Première"), t0()).unwrap(); - notes::create(&mut connection, draft(&boulot, "Seconde"), t0()).unwrap(); - - connection +fn titles(notes: &[Note]) -> Vec<&str> { + let mut titles: Vec<&str> = notes.iter().map(|note| note.title.as_str()).collect(); + titles.sort_unstable(); + titles } -fn exported(connection: &mut Library) -> Bundle { - let all = notes::all(connection, None).unwrap(); - collect(connection, all).unwrap() +fn names(items: &[T], name: impl Fn(&T) -> &str) -> Vec { + let mut names: Vec = items.iter().map(|item| name(item).to_string()).collect(); + names.sort(); + names } -/// The file as it is really written and read back, serialization included. -fn round_tripped(bundle: &Bundle) -> IncomingBundle { - model::read_bundle(&serde_json::to_string(bundle).unwrap()).unwrap() +/// The bundle as it left, merged into `connection`, with nothing to say about its values. +fn import(connection: &mut Library, bundle: Bundle) -> ImportReport { + let incoming = IncomingBundle { + bundle, + degraded: BTreeSet::new(), + }; + let nowhere = tempfile::tempdir().unwrap(); + merge(connection, incoming, &mut Payload::Empty, nowhere.path()).unwrap() } -/// The file a newer DevNotes would write: the same bundle, with a value in `field` -/// that this build has never heard of. -fn written_by_a_newer_version(bundle: &Bundle, field: &str, value: &str) -> IncomingBundle { - let mut json: serde_json::Value = serde_json::to_value(bundle).unwrap(); - json["notes"][0][field] = serde_json::Value::String(value.to_string()); - - model::read_bundle(&json.to_string()).unwrap() +fn sent_folder(id: &str, space_id: &str, parent: Option<&str>, name: &str) -> Folder { + Folder { + id: id.to_string(), + space_id: space_id.to_string(), + name: name.to_string(), + colour: engine::folders::model::FolderColour::Blue, + created_at: t0(), + parent_id: parent.map(str::to_string), + } } -#[test] -fn a_library_moves_whole_to_another_machine() { - let mut source = library(); - let bundle = round_tripped(&exported(&mut source)); - - let mut target = open_in_memory().unwrap(); - let report = merge(&mut target, bundle); - - assert_eq!(report.notes_imported, 2); - assert_eq!(report.spaces_created, 2); - assert_eq!(report.notes_skipped, 0); - - let arrived = notes::all(&mut target, None).unwrap(); - let mut titles: Vec<&str> = arrived.iter().map(|note| note.title.as_str()).collect(); - titles.sort_unstable(); - assert_eq!(titles, ["Première", "Seconde"]); - assert_eq!(arrived[0].content, "select 1"); - assert_eq!(arrived[0].tags, ["auth"]); - assert_eq!(arrived[0].created_at, t0()); - assert_eq!(spaces::list(&mut target).unwrap().len(), 2); +/// A bundle sent from elsewhere: one space, these folders, these notes. +fn sent(folders: Vec, notes: Vec) -> Bundle { + let mut library = open_in_memory().unwrap(); + let work = space(&mut library, "Work"); + let mut bundle = collect(&mut library, Vec::new()).unwrap(); + bundle.spaces = engine::spaces::store::list(&mut library).unwrap(); + bundle.folders = folders; + bundle.notes = notes + .into_iter() + .map(|note| Note { + space_id: work.clone(), + ..note + }) + .collect(); + bundle } -#[test] -fn only_the_spaces_actually_cited_travel() { - let mut source = library(); - let personal = spaces::list(&mut source).unwrap()[1].id.clone(); - let single = notes::all(&mut source, Some(&personal)).unwrap(); +fn sent_note(id: &str, folder_id: Option<&str>) -> Note { + let mut library = open_in_memory().unwrap(); + let work = space(&mut library, "Elsewhere"); + let made = note_in(&mut library, &work, None, id); + Note { + id: id.to_string(), + folder_id: folder_id.map(str::to_string), + ..made + } +} - let bundle = collect(&mut source, single).unwrap(); +fn the_space(bundle: &Bundle) -> String { + bundle.spaces[0].id.clone() +} - assert_eq!(bundle.spaces.len(), 1); - assert_eq!(bundle.notes.len(), 1); +fn folder_paths(connection: &mut Library) -> Vec { + let all = folders::list(connection, None).unwrap(); + let by_id: BTreeMap<&str, &Folder> = all + .iter() + .map(|folder| (folder.id.as_str(), folder)) + .collect(); + let mut paths: Vec = all + .iter() + .map(|folder| { + let mut path = vec![folder.name.clone()]; + let mut parent = folder.parent_id.as_deref(); + while let Some(id) = parent { + path.push(by_id[id].name.clone()); + parent = by_id[id].parent_id.as_deref(); + } + path.reverse(); + path.join("/") + }) + .collect(); + paths.sort(); + paths } #[test] -fn an_export_scope_takes_the_library_a_space_or_a_selection() { - let mut source = library(); - let personal = spaces::list(&mut source).unwrap()[1].id.clone(); - let one = notes::all(&mut source, None).unwrap()[0].id.clone(); - - let count = - |source: &mut Library, scope: ExportScope| bundle::of(source, &scope).unwrap().notes.len(); - - assert_eq!(count(&mut source, ExportScope::Library), 2); - assert_eq!( - count(&mut source, ExportScope::Space { space_id: personal }), - 1 - ); - assert_eq!(count(&mut source, ExportScope::Notes { ids: vec![one] }), 1); +fn an_export_counts_the_live_notes_its_scope_covers() { + let mut library = open_in_memory().unwrap(); + let work = space(&mut library, "Work"); + let home = space(&mut library, "Home"); + let kept = note_in(&mut library, &work, None, "Kept").id; + note_in(&mut library, &home, None, "Home"); + let trashed = note_in(&mut library, &work, None, "Trashed").id; + notes::trash::trash(&mut library, &trashed, t1()).unwrap(); + let cases = [ + (ExportScope::Library, 2), + (ExportScope::Space { space_id: work }, 1), + ( + ExportScope::Notes { + ids: vec![kept, trashed, "missing".to_string()], + }, + 1, + ), + ]; + + for (scope, counted) in cases { + assert_eq!(count(&mut library, &scope).unwrap(), counted, "{scope:?}"); + } } -/// Counted without opening a note, and the same answer the bundle would give. +/// Exporting one space must not recreate the whole tree, nor a folder without its parents. #[test] -fn an_export_scope_is_counted_before_anything_is_asked() { - let mut source = library(); - let personal = spaces::list(&mut source).unwrap()[1].id.clone(); - let empty = spaces::create(&mut source, "Vide").unwrap().id; - let one = notes::all(&mut source, None).unwrap()[0].id.clone(); - - assert_eq!( - bundle::count(&mut source, &ExportScope::Library).unwrap(), - 2 - ); - assert_eq!( - bundle::count(&mut source, &ExportScope::Space { space_id: personal }).unwrap(), - 1 - ); - assert_eq!( - bundle::count(&mut source, &ExportScope::Space { space_id: empty }).unwrap(), - 0 - ); +fn an_export_carries_its_notes_their_spaces_and_the_folders_they_sit_in_with_their_parents() { + let mut library = open_in_memory().unwrap(); + let work = space(&mut library, "Work"); + space(&mut library, "Home"); + let infra = folder_in(&mut library, &work, None, "Infra"); + let perf = folder_in(&mut library, &work, Some(&infra), "Perf"); + folder_in(&mut library, &work, Some(&infra), "Docs"); + folder_in(&mut library, &work, None, "Empty"); + note_in(&mut library, &work, Some(&perf), "Filed"); + note_in(&mut library, &work, None, "Loose"); + let trashed = note_in(&mut library, &work, None, "Trashed").id; + notes::trash::trash(&mut library, &trashed, t1()).unwrap(); + + let bundle = of(&mut library, &ExportScope::Space { space_id: work }).unwrap(); + + assert_eq!(bundle.version, FORMAT_VERSION); + assert_eq!(titles(&bundle.notes), ["Filed", "Loose"]); + assert_eq!(names(&bundle.spaces, |space| &space.name), ["Work"]); assert_eq!( - bundle::count( - &mut source, - &ExportScope::Notes { - ids: vec![one, "ghost".to_string()] - } - ) - .unwrap(), - 1 + names(&bundle.folders, |folder| &folder.name), + ["Infra", "Perf"] ); } #[test] -fn importing_the_same_file_twice_adds_nothing_the_second_time() { - let mut source = library(); - let file = exported(&mut source); +fn an_export_of_a_selection_carries_those_notes_and_their_attachments_alone() { + let mut library = open_in_memory().unwrap(); + let work = space(&mut library, "Work"); + let chosen = note_in(&mut library, &work, None, "Chosen").id; + let left = note_in(&mut library, &work, None, "Left").id; + for (id, note_id) in [("a-1", &chosen), ("a-2", &left)] { + let record = Attachment { + id: id.to_string(), + note_id: note_id.clone(), + file_name: "x.png".to_string(), + mime_type: "image/png".to_string(), + byte_size: 3, + created_at: t0(), + }; + let (db, vault) = library.split(); + attachments::create(db, vault, &record).unwrap(); + } - let mut target = open_in_memory().unwrap(); - merge(&mut target, round_tripped(&file)); - let second = merge(&mut target, round_tripped(&file)); + let bundle = of(&mut library, &ExportScope::Notes { ids: vec![chosen] }).unwrap(); - assert_eq!(second.notes_imported, 0); - assert_eq!(second.notes_skipped, 2); - assert_eq!(second.spaces_created, 0); - assert_eq!(notes::all(&mut target, None).unwrap().len(), 2); + assert_eq!(titles(&bundle.notes), ["Chosen"]); + assert_eq!(names(&bundle.attachments, |record| &record.id), ["a-1"]); } +/// Merge, never replace: a space matches by name, case aside, and is created when absent. #[test] -fn reimporting_into_the_base_it_came_from_changes_nothing() { - let mut library = library(); - let bundle = round_tripped(&exported(&mut library)); - - let report = merge(&mut library, bundle); - - assert_eq!(report.notes_imported, 0); - assert_eq!(report.notes_skipped, 2); - assert_eq!(notes::all(&mut library, None).unwrap().len(), 2); +fn an_import_matches_spaces_by_name_and_creates_the_others() { + let mut source = open_in_memory().unwrap(); + let work = space(&mut source, "work"); + let home = space(&mut source, "Home"); + note_in(&mut source, &work, None, "In work"); + note_in(&mut source, &home, None, "In home"); + let bundle = of(&mut source, &ExportScope::Library).unwrap(); + let mut destination = open_in_memory().unwrap(); + space(&mut destination, "Work"); + + let report = import(&mut destination, bundle); + + assert_eq!((report.spaces_created, report.notes_imported), (1, 2)); + let spaces = engine::spaces::store::list(&mut destination).unwrap(); + assert_eq!(names(&spaces, |space| &space.name), ["Home", "Work"]); } +/// Importing a file twice duplicates nothing: a note whose id is taken is counted and skipped. #[test] -fn a_space_of_the_same_name_is_reused_rather_than_duplicated() { - let mut source = library(); - let bundle = round_tripped(&exported(&mut source)); - - let mut target = open_in_memory().unwrap(); - spaces::create(&mut target, "PERSONAL").unwrap(); - - let report = merge(&mut target, bundle); - - assert_eq!(report.spaces_created, 1); - assert_eq!(spaces::list(&mut target).unwrap().len(), 2); +fn an_import_replayed_skips_every_note_already_there() { + let mut source = open_in_memory().unwrap(); + let work = space(&mut source, "Work"); + note_in(&mut source, &work, None, "Once"); + let bundle = of(&mut source, &ExportScope::Library).unwrap(); + let mut destination = open_in_memory().unwrap(); + import(&mut destination, bundle.clone()); + + let again = import(&mut destination, bundle); + + assert_eq!((again.notes_imported, again.notes_skipped), (0, 1)); + assert_eq!(notes::all(&mut destination, None).unwrap().len(), 1); } +/// A file cut by hand: inventing a space would file the note out of sight. #[test] -fn a_note_whose_space_is_missing_from_the_file_is_skipped_not_misfiled() { - let mut source = library(); - let mut incoming = round_tripped(&exported(&mut source)); - incoming.bundle.spaces.clear(); +fn a_note_whose_space_the_file_does_not_carry_is_skipped() { + let mut bundle = sent(Vec::new(), vec![sent_note("orphan", None)]); + bundle.spaces.clear(); + let mut destination = open_in_memory().unwrap(); - let mut target = open_in_memory().unwrap(); - let report = merge(&mut target, incoming); + let report = import(&mut destination, bundle); - assert_eq!(report.notes_imported, 0); - assert_eq!(report.notes_skipped, 2); + assert_eq!((report.notes_imported, report.notes_skipped), (0, 1)); } +/// Matched by name under the same parent — a "Perf" at the top is not the one under "Infra" — +/// parents first, whatever order the file wrote them in. #[test] -fn a_trashed_note_does_not_leave_with_the_export() { - let mut source = library(); - let thrown = notes::all(&mut source, None).unwrap()[0].id.clone(); - notes::trash::trash(&mut source, &thrown, t0()).unwrap(); - - let bundle = exported(&mut source); - - assert_eq!(bundle.notes.len(), 1); +fn an_import_matches_folders_under_their_parent_and_creates_the_rest_in_order() { + let mut destination = open_in_memory().unwrap(); + let work = space(&mut destination, "Work"); + let infra = folder_in(&mut destination, &work, None, "Infra"); + folder_in(&mut destination, &work, None, "Perf"); + let mut bundle = sent(Vec::new(), Vec::new()); + let from = the_space(&bundle); + bundle.folders = vec![ + sent_folder("deep", &from, Some("perf"), "Deep"), + sent_folder("perf", &from, Some("infra"), "Perf"), + sent_folder("infra", &from, None, "INFRA"), + ]; + bundle.notes = vec![Note { + space_id: from, + ..sent_note("filed", Some("deep")) + }]; + + let report = import(&mut destination, bundle); + + assert_eq!(report.folders_created, 2); + assert_eq!( + folder_paths(&mut destination), + ["Infra", "Infra/Perf", "Infra/Perf/Deep", "Perf"] + ); + let filed = notes::get(&mut destination, "filed").unwrap(); + let deep = folders::list(&mut destination, None) + .unwrap() + .into_iter() + .find(|folder| folder.name == "Deep") + .unwrap(); + assert_eq!(filed.folder_id, Some(deep.id)); + assert_ne!(filed.folder_id.as_deref(), Some(infra.as_str())); } -/// The case the whole guard exists for: one note in an unknown language must not -/// cost the other 499. +/// Two spaces may both hold an "Infra": the match is per space; a second import creates none. #[test] -fn a_note_in_an_unknown_language_arrives_without_taking_the_file_down() { - let mut source = library(); - let file = exported(&mut source); - - let mut target = open_in_memory().unwrap(); - let report = merge( - &mut target, - written_by_a_newer_version(&file, "language", "from-the-future"), - ); - - assert_eq!(report.notes_imported, 2); - assert_eq!(report.notes_degraded, 1); - - let arrived = notes::all(&mut target, None).unwrap(); - assert_eq!(arrived.len(), 2); - assert!( - arrived - .iter() - .any(|note| note.language == Language::default()) - ); +fn a_folder_is_matched_inside_its_own_space_and_once() { + let mut destination = open_in_memory().unwrap(); + let home = space(&mut destination, "Home"); + folder_in(&mut destination, &home, None, "Infra"); + let mut bundle = sent(Vec::new(), Vec::new()); + let from = the_space(&bundle); + bundle.folders = vec![sent_folder("infra", &from, None, "Infra")]; + + let first = import(&mut destination, bundle.clone()); + let again = import(&mut destination, bundle); + + assert_eq!((first.folders_created, again.folders_created), (1, 0)); + assert_eq!(folder_paths(&mut destination), ["Infra", "Infra"]); } +/// A parent the file does not carry, or a cycle, degrades to the top rather than failing. #[test] -fn a_note_of_an_unknown_kind_is_degraded_the_same_way() { - let mut source = library(); - let file = exported(&mut source); - - let mut target = open_in_memory().unwrap(); - let report = merge( - &mut target, - written_by_a_newer_version(&file, "kind", "from-the-future"), - ); +fn a_folder_whose_parent_cannot_be_placed_lands_at_the_top() { + let mut destination = open_in_memory().unwrap(); + let mut bundle = sent(Vec::new(), Vec::new()); + let from = the_space(&bundle); + bundle.folders = vec![ + sent_folder("lost", &from, Some("not-carried"), "Lost"), + sent_folder("x", &from, Some("y"), "X"), + sent_folder("y", &from, Some("x"), "Y"), + ]; + + import(&mut destination, bundle); + + assert_eq!(folder_paths(&mut destination), ["Lost", "X", "X/Y"]); +} - assert_eq!(report.notes_imported, 2); - assert_eq!(report.notes_degraded, 1); - assert!( - notes::all(&mut target, None) - .unwrap() - .iter() - .all(|note| note.kind == NoteKind::default()) - ); +/// Folders nest at most eight deep: what a file holds past that comes up to the top. +#[test] +fn a_tree_deeper_than_folders_nest_brings_its_last_level_up_to_the_top() { + let mut destination = open_in_memory().unwrap(); + let mut bundle = sent(Vec::new(), Vec::new()); + let from = the_space(&bundle); + let levels = engine::folders::model::MAX_DEPTH + 1; + bundle.folders = (0..levels) + .map(|level| { + let parent = level.checked_sub(1).map(|up| format!("f{up}")); + sent_folder( + &format!("f{level}"), + &from, + parent.as_deref(), + &format!("F{level}"), + ) + }) + .collect(); + + let report = import(&mut destination, bundle); + + assert_eq!(report.folders_created, u32::try_from(levels).unwrap()); + let paths = folder_paths(&mut destination); + assert!(paths.contains(&format!("F{}", levels - 1)), "{paths:?}"); } -/// The count follows what came in, not what the file carried: the second import -/// adds nothing, so it has nothing to report as degraded either. +/// The id is the sending library's: a dangling one would fail the foreign key and the import. #[test] -fn a_degraded_note_is_counted_once_and_not_again_on_a_second_import() { - let mut source = library(); - let file = exported(&mut source); +fn a_note_in_a_folder_the_file_does_not_carry_comes_in_loose() { + let mut destination = open_in_memory().unwrap(); + let bundle = sent(Vec::new(), vec![sent_note("filed", Some("not-carried"))]); - let mut target = open_in_memory().unwrap(); - merge( - &mut target, - written_by_a_newer_version(&file, "language", "from-the-future"), - ); + let report = import(&mut destination, bundle); - let second = merge( - &mut target, - written_by_a_newer_version(&file, "language", "from-the-future"), + assert_eq!(report.notes_imported, 1); + assert_eq!( + notes::get(&mut destination, "filed").unwrap().folder_id, + None ); - - assert_eq!(second.notes_imported, 0); - assert_eq!(second.notes_degraded, 0); } -/// The attachment as it really sits beside the database: sealed under the library key, -/// which is what the export has to open before it can write the file out. -fn seal_beside(directory: &std::path::Path, library: &Library, record: &Attachment, bytes: &[u8]) { - let sealed = library.vault().seal_bytes(bytes).unwrap(); - std::fs::write(directory.join(record.stored_name()), sealed).unwrap(); -} +/// Only what came in: re-importing must not keep reporting the same loss. +#[test] +fn a_note_brought_down_to_a_default_is_counted_once_it_has_come_in() { + let mut destination = open_in_memory().unwrap(); + let bundle = sent(Vec::new(), vec![sent_note("newer", None)]); + let degraded = BTreeSet::from(["newer".to_string()]); + let nowhere = tempfile::tempdir().unwrap(); + let incoming = |bundle: Bundle| IncomingBundle { + bundle, + degraded: degraded.clone(), + }; -/// `create` takes the pair, the way an import inside a transaction does. -fn attach(library: &mut Library, record: &Attachment) -> Result<(), engine::error::StorageError> { - let (db, vault) = library.split(); - attachments::create(db, vault, record) -} + let first = merge( + &mut destination, + incoming(bundle.clone()), + &mut Payload::Empty, + nowhere.path(), + ) + .unwrap(); + let again = merge( + &mut destination, + incoming(bundle), + &mut Payload::Empty, + nowhere.path(), + ) + .unwrap(); -fn capture(note_id: &str) -> Attachment { - Attachment { - id: format!("a-{note_id}"), - note_id: note_id.to_string(), - file_name: "capture.png".to_string(), - mime_type: "image/png".to_string(), - byte_size: 4, - created_at: t0(), - } + assert_eq!((first.notes_degraded, again.notes_degraded), (1, 0)); } -/// The point of the archive. A screenshot is a file beside the database, so an export -/// that carried only the rows handed over notes whose thumbnails would never load — and -/// nothing said so. +/// A note arrives as the store would have written it. #[test] -fn an_attachment_travels_with_the_library() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let source_files = directory.join("source"); - let target_files = directory.join("target"); - std::fs::create_dir_all(&source_files).unwrap(); - std::fs::create_dir_all(&target_files).unwrap(); - - let mut source = library(); - let note_id = notes::all(&mut source, None).unwrap()[0].id.clone(); - let record = capture(¬e_id); - seal_beside(&source_files, &source, &record, b"\x89PNG"); - attach(&mut source, &record).unwrap(); - - let target_path = directory - .join("library.devnotes") - .to_string_lossy() - .to_string(); - let packed = exported(&mut source); - let written = file::write(&target_path, &packed, &source_files, source.vault(), None).unwrap(); - assert_eq!(written.attachments, 1); - - let mut target = open_in_memory().unwrap(); - let (incoming, mut payload) = file::read(&target_path, None).unwrap(); - let report = merge_bundle(&mut target, incoming, &mut payload, &target_files).unwrap(); - - assert_eq!(report.attachments_imported, 1); - assert_eq!(report.attachments_missing, 0); - let landed = attachments::list(&mut target, ¬e_id).unwrap(); - assert_eq!(landed.len(), 1); - // Not `record.stored_name()`: the id is remapped on the way in, because it decides a - // write path and came out of a file. The bytes arrive sealed, and open. - let on_disk = std::fs::read(target_files.join(landed[0].stored_name())).unwrap(); - assert!( - !on_disk.windows(4).any(|window| window == b"\x89PNG"), - "the imported bytes landed in the clear" +fn an_imported_note_is_normalized_on_the_way_in() { + let mut destination = open_in_memory().unwrap(); + let raw = Note { + tags: vec!["#Ops".to_string(), "ops".to_string(), " ".to_string()], + language: Language::Txt, + ..sent_note("tagged", None) + }; + + import(&mut destination, sent(Vec::new(), vec![raw])); + + assert_eq!( + notes::get(&mut destination, "tagged").unwrap().tags, + ["Ops"] ); - assert_eq!(target.vault().open_bytes(&on_disk).unwrap(), b"\x89PNG"); - assert_ne!(landed[0].id, record.id); } -/// The size shown is what arrived, whatever the sending file declared. +/// Revisions would multiply the file by their cap: a note leaves without its history. #[test] -fn an_imported_attachment_reports_the_size_that_arrived() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let source_files = directory.join("source"); - let target_files = directory.join("target"); - std::fs::create_dir_all(&source_files).unwrap(); - std::fs::create_dir_all(&target_files).unwrap(); - - let mut source = library(); - let note_id = notes::all(&mut source, None).unwrap()[0].id.clone(); - let record = Attachment { - byte_size: 999_999, - ..capture(¬e_id) +fn an_export_carries_the_current_body_and_none_of_the_ones_it_replaced() { + let mut library = open_in_memory().unwrap(); + let work = space(&mut library, "Work"); + let draft = NoteDraft { + content: "select 1".to_string(), + ..snippet(&work) }; - seal_beside(&source_files, &source, &record, b"\x89PNG"); - attach(&mut source, &record).unwrap(); + let id = notes::create(&mut library, draft, t0()).unwrap().id; + let patch = engine::notes::model::NotePatch { + content: Some("select 2".to_string()), + ..Default::default() + }; + notes::update(&mut library, &id, &patch, t1()).unwrap(); - let target_path = directory - .join("library.devnotes") - .to_string_lossy() - .to_string(); - let packed = exported(&mut source); - file::write(&target_path, &packed, &source_files, source.vault(), None).unwrap(); + let bundle = of(&mut library, &ExportScope::Library).unwrap(); - let mut target = open_in_memory().unwrap(); - let (incoming, mut payload) = file::read(&target_path, None).unwrap(); - merge_bundle(&mut target, incoming, &mut payload, &target_files).unwrap(); + let written = serde_json::to_string(&bundle).unwrap(); + assert!(written.contains("select 2") && !written.contains("select 1")); +} + +#[test] +fn every_space_is_named_by_its_id_for_a_shared_note_s_breadcrumb() { + let mut library = open_in_memory().unwrap(); + let work = space(&mut library, "Work"); assert_eq!( - attachments::list(&mut target, ¬e_id).unwrap()[0].byte_size, - 4 + space_names(&mut library).unwrap(), + BTreeMap::from([(work, "Work".to_string())]) ); } -/// Re-importing the same archive adds nothing, attachments included: the notes are -/// skipped, so their files have nowhere to land twice. -#[test] -fn importing_the_same_archive_twice_restores_the_attachment_once() { +/// Two libraries on disk, an attachment in the first one, sent through a real file. +struct Shipment { + _scratch: tempfile::TempDir, + destination: Library, + attachments: PathBuf, + read: Option<(IncomingBundle, Payload)>, +} + +fn shipment(passphrase: Option<&str>, file_present: bool) -> Shipment { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let files = directory.join("files"); - std::fs::create_dir_all(&files).unwrap(); - - let mut source = library(); - let note_id = notes::all(&mut source, None).unwrap()[0].id.clone(); - let record = capture(¬e_id); - seal_beside(&files, &source, &record, b"\x89PNG"); - attach(&mut source, &record).unwrap(); - - let target_path = directory - .join("library.devnotes") + let library_at = |name: &str| -> (Library, PathBuf) { + let folder = scratch.path().join(name); + std::fs::create_dir_all(&folder).unwrap(); + let library = open(&folder.join("notes.db"), test_vault().unwrap()).unwrap(); + let attachments = engine::attachments::files::directory(&library); + std::fs::create_dir_all(&attachments).unwrap(); + (library, attachments) + }; + let (mut source, source_files) = library_at("source"); + let work = space(&mut source, "Work"); + let note = note_in(&mut source, &work, None, "With a picture").id; + let record = Attachment { + id: "a-1".to_string(), + note_id: note, + file_name: "shot.png".to_string(), + mime_type: "image/png".to_string(), + byte_size: 999, + created_at: DateTime::::UNIX_EPOCH, + }; + let (db, vault) = source.split(); + attachments::create(db, vault, &record).unwrap(); + if file_present { + sealed::write_sealed(vault, &source_files.join(record.stored_name()), b"pixels").unwrap(); + } + let bundle = of(&mut source, &ExportScope::Library).unwrap(); + let export = scratch + .path() + .join("notes.devnotes") .to_string_lossy() .to_string(); file::write( - &target_path, - &exported(&mut source), - &files, - source.vault(), - None, + &export, + &bundle, + &source_files, + &source.shared_vault(), + passphrase, ) .unwrap(); - - let mut target = open_in_memory().unwrap(); - let (first, mut payload) = file::read(&target_path, None).unwrap(); - merge_bundle(&mut target, first, &mut payload, &files).unwrap(); - - let (again, mut payload) = file::read(&target_path, None).unwrap(); - let second = merge_bundle(&mut target, again, &mut payload, &files).unwrap(); - - assert_eq!(second.notes_imported, 0); - assert_eq!(second.attachments_imported, 0); - assert_eq!(attachments::list(&mut target, ¬e_id).unwrap().len(), 1); + let (destination, attachments) = library_at("destination"); + let read = file::read(&export, passphrase).unwrap(); + Shipment { + _scratch: scratch, + destination, + attachments, + read: Some(read), + } } -/// A record whose bytes the archive does not carry is counted, never swallowed: the -/// note arrives with a preview that will stay empty, and the report is what explains it. -#[test] -fn an_attachment_the_archive_does_not_carry_is_reported() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let files = directory.join("files"); - std::fs::create_dir_all(&files).unwrap(); - - let mut source = library(); - let note_id = notes::all(&mut source, None).unwrap()[0].id.clone(); - // The record exists, its file never did: the export writes the row and no entry. - attach(&mut source, &capture(¬e_id)).unwrap(); - - let target_path = directory - .join("library.devnotes") - .to_string_lossy() - .to_string(); - let written = file::write( - &target_path, - &exported(&mut source), - &files, - source.vault(), - None, +fn land(shipment: &mut Shipment) -> ImportReport { + let (incoming, mut payload) = shipment.read.take().unwrap(); + merge( + &mut shipment.destination, + incoming, + &mut payload, + &shipment.attachments, ) - .unwrap(); - assert_eq!(written.attachments, 0); - - let mut target = open_in_memory().unwrap(); - let (incoming, mut payload) = file::read(&target_path, None).unwrap(); - let report = merge_bundle(&mut target, incoming, &mut payload, &files).unwrap(); - - assert_eq!(report.notes_imported, 2); - assert_eq!(report.attachments_missing, 1); - assert_eq!(report.attachments_imported, 0); + .unwrap() } -mod folders_travelling { - use super::*; - - use engine::folders::board::{BoardFrame, BoardPoint, CardPlacement, ZonePlacement}; - use engine::folders::store as folders; - use engine::folders::store::board as geometry; - - /// A library with its notes filed, and a board arranged — the state a real one is in. - fn arranged() -> (Library, String, String) { - let mut connection = open_in_memory().unwrap(); - let sql = spaces::create(&mut connection, "SQL").unwrap().id; - let perf = folders::create(&mut connection, &sql, None, "Perf", t0()).unwrap(); - let migrations = folders::create(&mut connection, &sql, None, "Migrations", t0()).unwrap(); - - let filed = notes::create(&mut connection, draft(&sql, "EXPLAIN lent"), t0()).unwrap(); - let elsewhere = notes::create(&mut connection, draft(&sql, "Backfill"), t0()).unwrap(); - notes::create(&mut connection, draft(&sql, "Dump nocturne"), t0()).unwrap(); - - folders::file_many( - &mut connection, - std::slice::from_ref(&filed.id), - Some(&perf.id), - 140, - ) - .unwrap(); - folders::file_many( - &mut connection, - std::slice::from_ref(&elsewhere.id), - Some(&migrations.id), - 140, - ) - .unwrap(); - - geometry::save_layout( - &mut connection, - None, - &[ZonePlacement { - folder_id: perf.id.clone(), - frame: BoardFrame { - x: 900, - y: 700, - width: 520, - height: 400, - }, - }], - &[], - ) - .unwrap(); - - (connection, sql, perf.id) - } - - fn folder_names(connection: &mut Library, space_id: &str) -> Vec { - let mut names: Vec = folders::list(connection, Some(space_id)) - .unwrap() - .into_iter() - .map(|folder| folder.name) - .collect(); - names.sort(); - names - } - - fn folder_of(connection: &mut Library, title: &str) -> Option { - notes::all(connection, None) - .unwrap() - .into_iter() - .find(|note| note.title == title) - .and_then(|note| note.folder_id) - .and_then(|id| { - folders::list(connection, None) - .unwrap() - .into_iter() - .find(|folder| folder.id == id) - .map(|folder| folder.name) - }) - } - - #[test] - fn a_library_comes_back_arranged_on_another_machine() { - let (mut source, _, _) = arranged(); - let bundle = round_tripped(&exported(&mut source)); +fn files_in(directory: &Path) -> usize { + std::fs::read_dir(directory).unwrap().count() +} - let mut target = open_in_memory().unwrap(); - let report = merge(&mut target, bundle); +/// Its bytes sealed beside the new library under a new id, its size what actually arrived. +#[test] +fn an_attachment_comes_in_with_its_note_under_a_new_id() { + for passphrase in [None, Some("export phrase")] { + let mut shipment = shipment(passphrase, true); - assert_eq!(report.notes_imported, 3); - assert_eq!(report.spaces_created, 1); - assert_eq!(report.folders_created, 2); + let report = land(&mut shipment); - let space = spaces::list(&mut target).unwrap()[0].id.clone(); - assert_eq!(folder_names(&mut target, &space), ["Migrations", "Perf"]); - assert_eq!( - folder_of(&mut target, "EXPLAIN lent").as_deref(), - Some("Perf") - ); assert_eq!( - folder_of(&mut target, "Backfill").as_deref(), - Some("Migrations") + (report.attachments_imported, report.attachments_missing), + (1, 0) ); - assert_eq!(folder_of(&mut target, "Dump nocturne"), None); - } - - /// Exporting one folder's worth of notes must not recreate the whole tree. - #[test] - fn only_the_folders_actually_cited_travel() { - let (mut source, space_id, perf_id) = arranged(); - let filed: Vec<_> = notes::all(&mut source, None) - .unwrap() - .into_iter() - .filter(|note| note.folder_id.as_deref() == Some(perf_id.as_str())) - .collect(); - - let bundle = collect(&mut source, filed).unwrap(); - - assert_eq!(bundle.folders.len(), 1); - assert_eq!(bundle.folders[0].name, "Perf"); - assert_eq!(bundle.spaces.len(), 1); - assert_eq!(bundle.spaces[0].id, space_id); - } - - /// A board received from elsewhere must not land on top of the one you arranged. - /// Keeping the geometry off the `Folder` model is what makes this free. - #[test] - fn no_coordinate_ever_leaves_the_machine() { - let (mut source, _, _) = arranged(); - - let json = serde_json::to_string(&exported(&mut source)).unwrap(); - - for spelled in [ - "\"x\"", - "\"y\"", - "\"w\"", - "\"h\"", - "\"frame\"", - "\"position\"", - ] { - assert!(!json.contains(spelled), "the export spells {spelled}"); - } - } - - #[test] - fn a_received_folder_is_laid_out_by_the_machine_that_receives_it() { - let (mut source, _, _) = arranged(); - let bundle = round_tripped(&exported(&mut source)); - - let mut target = open_in_memory().unwrap(); - merge(&mut target, bundle); - - let space = spaces::list(&mut target).unwrap()[0].id.clone(); - let placed = target - .transaction(|connection, _vault| geometry::frames(connection, &space)) - .unwrap(); - - // Nothing was written: the board lays it out on its first read, here as anywhere. - assert!(placed.is_empty()); - } - - /// The rule spaces already follow, and for the same reason: merge, never replace. - #[test] - fn a_folder_of_the_same_name_is_reused_rather_than_duplicated() { - let (mut source, _, _) = arranged(); - let bundle = round_tripped(&exported(&mut source)); - - let mut target = open_in_memory().unwrap(); - let space = spaces::create(&mut target, "SQL").unwrap().id; - folders::create(&mut target, &space, None, "perf", t0()).unwrap(); - - let report = merge(&mut target, bundle); - - assert_eq!(report.spaces_created, 0); - assert_eq!(report.folders_created, 1); - assert_eq!(folder_names(&mut target, &space), ["Migrations", "perf"]); - // Matched case-insensitively, so the note lands in the folder already there. + let note = notes::all(&mut shipment.destination, None).unwrap()[0] + .id + .clone(); + let records = attachments::list(&mut shipment.destination, ¬e).unwrap(); + assert_ne!(records[0].id, "a-1"); assert_eq!( - folder_of(&mut target, "EXPLAIN lent").as_deref(), - Some("perf") + (records[0].file_name.as_str(), records[0].byte_size), + ("shot.png", 6) ); + let (_, bytes) = + engine::attachments::files::read_plain(&mut shipment.destination, &records[0].id) + .unwrap(); + assert_eq!(bytes, b"pixels"); } +} - /// Two spaces may both hold a "Perf": the match is per space, never per library. - #[test] - fn a_folder_is_matched_inside_its_own_space() { - let (mut source, _, _) = arranged(); - let bundle = round_tripped(&exported(&mut source)); - - let mut target = open_in_memory().unwrap(); - let elsewhere = spaces::create(&mut target, "Veille").unwrap().id; - folders::create(&mut target, &elsewhere, None, "Perf", t0()).unwrap(); - - let report = merge(&mut target, bundle); - - assert_eq!(report.folders_created, 2); - assert_eq!(folder_names(&mut target, &elsewhere), ["Perf"]); - } - - #[test] - fn importing_the_same_file_twice_creates_no_folder_the_second_time() { - let (mut source, _, _) = arranged(); - let bundle = exported(&mut source); - - let mut target = open_in_memory().unwrap(); - merge(&mut target, round_tripped(&bundle)); - let second = merge(&mut target, round_tripped(&bundle)); - - assert_eq!(second.folders_created, 0); - assert_eq!(second.notes_imported, 0); - assert_eq!(second.notes_skipped, 3); - } - - /// `#[serde(default)]`, exactly as `kind` and `items` carry it: no `FORMAT_VERSION` - /// bump, because such a file still parses. - #[test] - fn an_export_written_before_folders_still_reads() { - let (mut source, _, _) = arranged(); - let mut json: serde_json::Value = serde_json::to_value(exported(&mut source)).unwrap(); - json.as_object_mut().unwrap().remove("folders"); - for note in json["notes"].as_array_mut().unwrap() { - note.as_object_mut().unwrap().remove("folderId"); - } - - let read = model::read_bundle(&json.to_string()).unwrap(); - let mut target = open_in_memory().unwrap(); - let report = merge(&mut target, read); - - assert_eq!(report.notes_imported, 3); - assert_eq!(report.folders_created, 0); - assert_eq!(folder_of(&mut target, "EXPLAIN lent"), None); - } - - /// The id is the *sending* library's: a dangling one would be refused by the foreign - /// key, losing the whole import over a note that is merely unfiled. - #[test] - fn a_note_naming_a_folder_the_file_left_out_arrives_unfiled() { - let (mut source, _, _) = arranged(); - let mut json: serde_json::Value = serde_json::to_value(exported(&mut source)).unwrap(); - json["folders"] = serde_json::Value::Array(Vec::new()); - - let read = model::read_bundle(&json.to_string()).unwrap(); - let mut target = open_in_memory().unwrap(); - let report = merge(&mut target, read); - - assert_eq!(report.notes_imported, 3); - assert_eq!(report.folders_created, 0); - assert_eq!(folder_of(&mut target, "EXPLAIN lent"), None); - } - - #[test] - fn the_export_report_counts_the_folders_it_wrote() { - let (mut source, _, _) = arranged(); - - assert_eq!(exported(&mut source).folders.len(), 2); - } - - /// A position is a local gesture, and it is never asked to travel. - #[test] - fn a_card_position_stays_on_the_machine_that_chose_it() { - let (mut source, space_id, _) = arranged(); - let loose = notes::all(&mut source, None) - .unwrap() - .into_iter() - .find(|note| note.title == "Dump nocturne") - .unwrap(); - geometry::save_layout( - &mut source, - None, - &[], - &[CardPlacement { - note_id: loose.id.clone(), - position: BoardPoint { x: 640, y: 480 }, - }], - ) - .unwrap(); - - let bundle = round_tripped(&exported(&mut source)); - let mut target = open_in_memory().unwrap(); - merge(&mut target, bundle); - - let space = spaces::list(&mut target).unwrap()[0].id.clone(); - let placed = target - .transaction(|connection, _vault| geometry::positions(connection, &space)) - .unwrap(); - assert!(placed.is_empty()); - - // And the sending machine keeps its own, untouched. - let kept = source - .transaction(|connection, _vault| geometry::positions(connection, &space_id)) - .unwrap(); - assert_eq!(kept.get(&loose.id), Some(&BoardPoint { x: 640, y: 480 })); - } - - /// `Base › Perf`, a note filed in `Perf` alone. - fn nested() -> Library { - let mut connection = open_in_memory().unwrap(); - let sql = spaces::create(&mut connection, "SQL").unwrap().id; - let base = folders::create(&mut connection, &sql, None, "Base", t0()).unwrap(); - let perf = folders::create(&mut connection, &sql, Some(&base.id), "Perf", t0()).unwrap(); - folders::create(&mut connection, &sql, None, "Uncited", t0()).unwrap(); - - let filed = notes::create(&mut connection, draft(&sql, "EXPLAIN lent"), t0()).unwrap(); - folders::file_many( - &mut connection, - std::slice::from_ref(&filed.id), - Some(&perf.id), - 140, - ) - .unwrap(); - connection - } - - fn parent_name(connection: &mut Library, name: &str) -> Option { - let all = folders::list(connection, None).unwrap(); - let folder = all.iter().find(|folder| folder.name == name)?; - let parent = folder.parent_id.as_ref()?; - all.iter() - .find(|candidate| &candidate.id == parent) - .map(|candidate| candidate.name.clone()) - } - - /// A folder without the ones above it would land at the top of its space. - #[test] - fn a_folder_travels_with_the_folders_above_it_and_lands_under_them() { - let mut source = nested(); - let bundle = exported(&mut source); - - let mut carried: Vec<&str> = bundle - .folders - .iter() - .map(|folder| folder.name.as_str()) - .collect(); - carried.sort_unstable(); - assert_eq!(carried, ["Base", "Perf"]); - - let mut target = open_in_memory().unwrap(); - let report = merge(&mut target, round_tripped(&bundle)); - - assert_eq!(report.folders_created, 2); - assert_eq!(parent_name(&mut target, "Perf").as_deref(), Some("Base")); - assert_eq!(parent_name(&mut target, "Base"), None); - assert_eq!( - folder_of(&mut target, "EXPLAIN lent").as_deref(), - Some("Perf") - ); - } +/// The only thing that says why a thumbnail will never load. +#[test] +fn an_attachment_the_file_does_not_carry_is_counted_missing() { + let mut shipment = shipment(None, false); - /// A « Perf » at the top is not the « Perf » under « Base »: the match is per parent. - #[test] - fn a_folder_is_matched_by_name_under_the_same_parent() { - let mut source = nested(); - let bundle = round_tripped(&exported(&mut source)); - - let mut target = open_in_memory().unwrap(); - let space = spaces::create(&mut target, "SQL").unwrap().id; - folders::create(&mut target, &space, None, "perf", t0()).unwrap(); - let base = folders::create(&mut target, &space, None, "base", t0()).unwrap(); - - let report = merge(&mut target, bundle); - - assert_eq!(report.folders_created, 1); - assert_eq!(parent_name(&mut target, "Perf").as_deref(), Some("base")); - assert!( - folders::list(&mut target, Some(&space)) - .unwrap() - .iter() - .any( - |folder| folder.name == "Perf" && folder.parent_id.as_deref() == Some(&base.id) - ) - ); - } + let report = land(&mut shipment); - /// A file can say anything: a parent it does not carry, or two folders each the other's. - #[test] - fn a_tree_a_file_cannot_hold_lands_at_the_top_rather_than_failing() { - let mut source = nested(); - let mut bundle = exported(&mut source); - let [first, second] = &mut bundle.folders[..] else { - panic!("two folders travel"); - }; - first.parent_id = Some(second.id.clone()); - second.parent_id = Some(first.id.clone()); - bundle.folders.push(engine::folders::model::Folder { - id: "stray".to_string(), - name: "Stray".to_string(), - parent_id: Some("never-carried".to_string()), - ..bundle.folders[0].clone() - }); - - let mut target = open_in_memory().unwrap(); - let report = merge(&mut target, round_tripped(&bundle)); - - assert_eq!(report.folders_created, 3); - assert_eq!(parent_name(&mut target, "Stray"), None); - assert_eq!(report.notes_imported, 1); - } + assert_eq!( + (report.attachments_imported, report.attachments_missing), + (0, 1) + ); + assert_eq!(files_in(&shipment.attachments), 0); } -/// A deliberate omission: revisions would inflate the bundle by a factor of the cap, and a -/// note arriving elsewhere without its history is the accepted cost. +/// Re-importing adds nothing: only the attachments of notes that arrived come in. #[test] -fn a_bundle_carries_no_history_of_the_bodies_it_holds() { - let mut connection = open_in_memory().unwrap(); - let space_id = spaces::create(&mut connection, "Personal").unwrap().id; - let id = notes::create(&mut connection, draft(&space_id, "Requête"), t0()) - .unwrap() - .id; - notes::update( - &mut connection, - &id, - &engine::notes::model::NotePatch { - content: Some("select 2".to_string()), - ..Default::default() +fn an_attachment_of_a_note_already_there_is_not_brought_in_again() { + let mut shipment = shipment(None, true); + let bundle = shipment.read.as_ref().unwrap().0.bundle.clone(); + land(&mut shipment); + let nowhere = tempfile::tempdir().unwrap(); + + let again = merge( + &mut shipment.destination, + IncomingBundle { + bundle, + degraded: BTreeSet::new(), }, - t0(), + &mut Payload::Empty, + nowhere.path(), ) .unwrap(); - let bundle = exported(&mut connection); - let written = serde_json::to_string(&bundle).unwrap(); - - // The current body travels; the one it replaced does not. - assert!(written.contains("select 2")); - assert!(!written.contains("select 1")); + assert_eq!( + (again.attachments_imported, again.attachments_missing), + (0, 0) + ); + assert_eq!(files_in(&shipment.attachments), 1); } From 8c650a09ebebd1ffe39b9878bd6293007baa7bc0 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:29:51 +0100 Subject: [PATCH 29/95] Libraries: unit tests rewritten for the registry and services (#1751) * Rewrite the tests of the libraries' registry and services Co-Authored-By: Claude Opus 5.5 * A registry the system refuses to read, and a profile with no room for a library folder Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/libraries/registry.rs | 423 ++++++++---------------- crates/engine/tests/commands/profile.rs | 79 ++++- 2 files changed, 209 insertions(+), 293 deletions(-) diff --git a/crates/engine/src/libraries/registry.rs b/crates/engine/src/libraries/registry.rs index ab808e744..a7021c529 100644 --- a/crates/engine/src/libraries/registry.rs +++ b/crates/engine/src/libraries/registry.rs @@ -248,344 +248,209 @@ pub(crate) fn delete_in(profile: &Path, id: &str) -> Result<(), StorageError> { mod tests { use super::*; - fn entry(id: &str, directory: &str) -> LibraryEntry { - LibraryEntry { - id: id.to_string(), - name: String::new(), - directory: directory.to_string(), - created_at: Utc::now(), - } + fn profile() -> tempfile::TempDir { + tempfile::tempdir().unwrap() } - #[test] - fn a_library_sits_under_a_folder_of_its_own() { - let scratch = tempfile::tempdir().unwrap(); - let profile = scratch.path().to_path_buf(); - - assert_eq!( - directory_of(&profile, &entry("b", "libraries/b")), - profile.join("libraries").join("b") - ); + fn ids(registry: &Registry) -> Vec<&str> { + registry + .libraries + .iter() + .map(|entry| entry.id.as_str()) + .collect() } - /// Without the key file the library opens for nobody, and without the attachments the next - /// orphan sweep deletes the pictures. + /// A first launch: one unnamed library, open, in a folder of its own, written down. #[test] - fn gathering_takes_the_key_and_the_attachments_with_the_database() { - let scratch = tempfile::tempdir().unwrap(); - let profile = scratch.path().to_path_buf(); - std::fs::write(profile.join(DATABASE), b"a database").unwrap(); - std::fs::write(profile.join(KEY_FILE), b"{}").unwrap(); - std::fs::create_dir_all(profile.join("attachments")).unwrap(); - std::fs::write(profile.join("attachments").join("a-1.png"), b"\x89PNG").unwrap(); - std::fs::create_dir_all(profile.join("backups")).unwrap(); - let into = profile.join("libraries").join("x"); - std::fs::create_dir_all(&into).unwrap(); - - gather(&profile, &into); - - assert!(into.join(DATABASE).is_file()); - assert!(into.join(KEY_FILE).is_file()); - assert!(into.join("attachments").join("a-1.png").is_file()); - assert!(into.join("backups").is_dir()); - assert!(!profile.join(DATABASE).exists()); - assert!(!profile.join("attachments").exists()); + fn a_virgin_profile_gets_one_library_in_a_folder_of_its_own_and_open() { + let profile = profile(); + + let registry = registry_in(profile.path()); + + assert_eq!(registry.libraries.len(), 1); + let entry = ®istry.libraries[0]; + assert_eq!(entry.name, ""); + assert_eq!(entry.directory, format!("{LIBRARIES}/{}", entry.id)); + assert!(profile.path().join(&entry.directory).is_dir()); + assert_eq!(registry.open.as_deref(), Some(entry.id.as_str())); + assert_eq!(ids(®istry_in(profile.path())), ids(®istry)); } - /// A directory a library gains travels only once `layout` declares it. + /// The migration: everything `layout` declares moves into its own folder — without the key + /// file it opens for nobody, without the attachments every picture is swept as an orphan — + /// and the application's preferences stay with the person. #[test] - fn gathering_moves_every_entry_the_layout_declares() { - let scratch = tempfile::tempdir().unwrap(); - let profile = scratch.path().to_path_buf(); + fn a_library_from_before_the_registry_is_gathered_into_its_own_folder_once() { + let profile = profile(); for name in LIBRARY_FILES { - std::fs::write(profile.join(name), b"x").unwrap(); + std::fs::write(profile.path().join(name), name.as_bytes()).unwrap(); } for name in LIBRARY_DIRECTORIES { - std::fs::create_dir_all(profile.join(name)).unwrap(); + std::fs::create_dir_all(profile.path().join(name)).unwrap(); } - let into = profile.join(LIBRARIES).join("x"); - std::fs::create_dir_all(&into).unwrap(); + std::fs::write(profile.path().join(crate::layout::PREFERENCES), b"{}").unwrap(); - gather(&profile, &into); + let registry = registry_in(profile.path()); + let folder = profile.path().join(®istry.libraries[0].directory); for name in LIBRARY_FILES.iter().chain(LIBRARY_DIRECTORIES.iter()) { - assert!(into.join(name).exists(), "{name} did not arrive"); - assert!(!profile.join(name).exists(), "{name} stayed behind"); + assert!(folder.join(name).exists(), "{name} did not arrive"); + assert!(!profile.path().join(name).exists(), "{name} stayed behind"); } + assert!(profile.path().join(crate::layout::PREFERENCES).is_file()); + std::fs::write(profile.path().join(DATABASE), b"later").unwrap(); + registry_in(profile.path()); + assert!( + profile.path().join(DATABASE).is_file(), + "gathered a second time" + ); } - /// The application's preferences follow the person, not the corpus. + /// Never taken for an absent file, which a first launch would write over: set aside as it + /// was, and the list made again from the folders that hold a library, unnamed. #[test] - fn gathering_leaves_the_application_preferences_where_they_are() { - let scratch = tempfile::tempdir().unwrap(); - let profile = scratch.path().to_path_buf(); - std::fs::write(profile.join(DATABASE), b"a database").unwrap(); - std::fs::write(profile.join("preferences.json"), b"{}").unwrap(); - let into = profile.join("libraries").join("x"); - std::fs::create_dir_all(&into).unwrap(); - - gather(&profile, &into); - - assert!(profile.join("preferences.json").is_file()); - assert!(!into.join("preferences.json").exists()); + fn an_unreadable_registry_is_set_aside_and_rebuilt_from_the_folders_that_hold_a_library() { + let profile = profile(); + let kept = create_in(profile.path(), "Work").unwrap(); + std::fs::write(profile.path().join(&kept.directory).join(KEY_FILE), b"key").unwrap(); + let empty = create_in(profile.path(), "Empty").unwrap(); + std::fs::write(profile.path().join(REGISTRY), b"{ not json").unwrap(); + + let registry = registry_in(profile.path()); + + assert_eq!(ids(®istry), [kept.id.as_str()]); + assert_eq!(registry.libraries[0].name, ""); + assert_eq!(registry.open.as_deref(), Some(kept.id.as_str())); + let aside = std::fs::read_dir(profile.path()) + .unwrap() + .filter_map(Result::ok) + .any(|entry| { + entry + .file_name() + .to_string_lossy() + .starts_with("libraries.json.unreadable-") + }); + assert!(aside); + assert!( + profile.path().join(&empty.directory).is_dir(), + "a folder is never deleted here" + ); } + /// A registry the system refuses to read is no absent one either. #[test] - fn a_profile_with_no_library_in_it_holds_none() { - let scratch = tempfile::tempdir().unwrap(); - let profile = scratch.path().to_path_buf(); - assert!(!holds_a_library(&profile)); + fn a_registry_that_cannot_be_read_at_all_is_rebuilt_too() { + let profile = profile(); + let kept = create_in(profile.path(), "Work").unwrap(); + std::fs::write(profile.path().join(&kept.directory).join(KEY_FILE), b"key").unwrap(); + std::fs::remove_file(profile.path().join(REGISTRY)).unwrap(); + std::fs::create_dir(profile.path().join(REGISTRY)).unwrap(); - std::fs::write(profile.join(KEY_FILE), b"{}").unwrap(); + let registry = registry_in(profile.path()); - assert!(holds_a_library(&profile)); + assert_eq!(ids(®istry), [kept.id.as_str()]); } + /// Where no folder can be made for a library, the profile itself holds it, as before the + /// registry: the gate still has somewhere to look. #[test] - fn the_registry_is_staged_and_renamed_rather_than_truncated() { - let scratch = tempfile::tempdir().unwrap(); - let profile = scratch.path().to_path_buf(); - let registry = Registry { - libraries: vec![entry("a", "")], - open: Some("a".to_string()), - }; - - write(&profile, ®istry).unwrap(); - - assert!(profile.join(REGISTRY).is_file()); - assert!(!profile.join(format!("{REGISTRY}.writing")).exists()); - assert_eq!(read(&profile).unwrap().libraries, registry.libraries); - } + fn a_profile_where_no_library_folder_can_be_made_keeps_its_library_in_place() { + let profile = profile(); + std::fs::write(profile.path().join(LIBRARIES), b"not a folder").unwrap(); - #[test] - fn a_registry_that_cannot_be_read_is_told_from_an_absent_one() { - let scratch = tempfile::tempdir().unwrap(); - let profile = scratch.path().to_path_buf(); - assert!(read(&profile).is_some_and(|registry| registry.libraries.is_empty())); - - std::fs::write(profile.join(REGISTRY), b"not json at all").unwrap(); + let directory = open_directory_in(profile.path()).unwrap(); - assert!(read(&profile).is_none()); + assert_eq!(directory, profile.path()); } + /// One is always open once anything exists: the gate asks for a library's passphrase. #[test] - fn a_registry_cut_short_is_set_aside_and_its_libraries_found_again() { - let scratch = tempfile::tempdir().unwrap(); - let profile = scratch.path().to_path_buf(); - let first = create_in(&profile, "Travail").unwrap(); - let second = create_in(&profile, "Perso").unwrap(); - for entry in [&first, &second] { - std::fs::write(directory_of(&profile, entry).join(DATABASE), b"a database").unwrap(); + fn a_registry_naming_no_open_library_or_one_gone_opens_the_first() { + let profile = profile(); + let first = registry_in(profile.path()).libraries[0].id.clone(); + create_in(profile.path(), "Second").unwrap(); + for open in [None, Some("gone".to_string())] { + let mut registry = registry_in(profile.path()); + registry.open = open; + write(profile.path(), ®istry).unwrap(); + + let directory = open_directory_in(profile.path()).unwrap(); + + assert_eq!(directory, profile.path().join(LIBRARIES).join(&first)); } - let whole = std::fs::read(profile.join(REGISTRY)).unwrap(); - std::fs::write(profile.join(REGISTRY), &whole[..whole.len() / 2]).unwrap(); - - let registry = registry_in(&profile); - - let mut found: Vec<&str> = registry - .libraries - .iter() - .map(|entry| entry.id.as_str()) - .collect(); - found.sort_unstable(); - let mut made = vec![first.id.as_str(), second.id.as_str()]; - made.sort_unstable(); - assert_eq!(found, made); - let aside = std::fs::read_dir(&profile) - .unwrap() - .filter_map(|entry| entry.unwrap().file_name().into_string().ok()) - .find(|name| name.starts_with(&format!("{REGISTRY}.unreadable"))) - .expect("the cut registry is set aside"); - assert_eq!( - std::fs::read(profile.join(aside)).unwrap(), - &whole[..whole.len() / 2] - ); } + /// Added closed: opening it is a second, deliberate gesture. #[test] - fn the_first_one_stands_in_when_nothing_is_marked_open() { - let registry = Registry { - libraries: vec![entry("a", ""), entry("b", "libraries/b")], - open: None, - }; + fn a_library_is_added_trimmed_in_a_folder_of_its_own_and_left_closed() { + let profile = profile(); + let first = registry_in(profile.path()).open; - assert_eq!(registry.opened().map(|entry| entry.id.as_str()), Some("a")); - } + let added = create_in(profile.path(), " Personal ").unwrap(); - #[test] - fn an_open_id_naming_nothing_falls_back_rather_than_answering_none() { - let registry = Registry { - libraries: vec![entry("a", "")], - open: Some("gone".to_string()), - }; - - assert_eq!(registry.opened().map(|entry| entry.id.as_str()), Some("a")); + let registry = registry_in(profile.path()); + assert_eq!(added.name, "Personal"); + assert!(profile.path().join(&added.directory).is_dir()); + assert_eq!(registry.libraries.last(), Some(&added)); + assert_eq!(registry.open, first); } - /// The migration, end to end. #[test] - fn a_profile_from_before_the_registry_is_adopted_and_gathered() { - let scratch = tempfile::tempdir().unwrap(); - let profile = scratch.path().to_path_buf(); - std::fs::write(profile.join(DATABASE), b"a database").unwrap(); - std::fs::write(profile.join(KEY_FILE), b"{}").unwrap(); + fn a_library_is_opened_and_renamed_trimmed_by_its_id() { + let profile = profile(); + let added = create_in(profile.path(), "Personal").unwrap(); - let registry = registry_in(&profile); + point_at(profile.path(), &added.id).unwrap(); + rename_in(profile.path(), &added.id, " Home ").unwrap(); - assert_eq!(registry.libraries.len(), 1); - let into = directory_of(&profile, ®istry.libraries[0]); - assert!(into.join(DATABASE).is_file()); - assert!(!profile.join(DATABASE).exists()); + let registry = registry_in(profile.path()); + assert_eq!(registry.open.as_deref(), Some(added.id.as_str())); + assert_eq!(registry.entry(&added.id).unwrap().name, "Home"); assert_eq!( - registry.open.as_deref(), - Some(registry.libraries[0].id.as_str()) + open_directory_in(profile.path()).unwrap(), + profile.path().join(&added.directory) ); } - /// A first launch has nothing to gather, and still gets a library of its own. #[test] - fn a_virgin_profile_gets_one_library_and_no_files_moved() { - let scratch = tempfile::tempdir().unwrap(); - let profile = scratch.path().to_path_buf(); - - let registry = registry_in(&profile); - - assert_eq!(registry.libraries.len(), 1); - assert!(directory_of(&profile, ®istry.libraries[0]).is_dir()); - } - - #[test] - fn adopting_happens_once() { - let scratch = tempfile::tempdir().unwrap(); - let profile = scratch.path().to_path_buf(); - let first = registry_in(&profile); - - let second = registry_in(&profile); - - assert_eq!(second.libraries.len(), 1); - assert_eq!(second.libraries[0].id, first.libraries[0].id); - } - - #[test] - fn the_open_directory_is_the_one_the_registry_points_at() { - let scratch = tempfile::tempdir().unwrap(); - let profile = scratch.path().to_path_buf(); - let created = create_in(&profile, "Boulot").unwrap(); - point_at(&profile, &created.id).unwrap(); - - let directory = open_directory_in(&profile).unwrap(); - - assert_eq!(directory, directory_of(&profile, &created)); - } - - #[test] - fn creating_one_adds_it_to_the_registry_and_leaves_it_closed() { - let scratch = tempfile::tempdir().unwrap(); - let profile = scratch.path().to_path_buf(); - let first = registry_in(&profile).open; - - let created = create_in(&profile, " Boulot ").unwrap(); - - let registry = registry_in(&profile); - assert_eq!(registry.libraries.len(), 2); - assert_eq!(created.name, "Boulot", "the name is trimmed"); - assert_eq!(registry.open, first, "creating does not open"); - assert!(directory_of(&profile, &created).is_dir()); - assert!(!directory_of(&profile, &created).join(DATABASE).exists()); - } - - #[test] - fn pointing_at_one_that_does_not_exist_says_so() { - let scratch = tempfile::tempdir().unwrap(); - let profile = scratch.path().to_path_buf(); - registry_in(&profile); - - assert!(matches!( - point_at(&profile, "nothing"), - Err(StorageError::LibraryNotFound(_)) - )); - } - - #[test] - fn renaming_touches_the_name_and_nothing_else() { - let scratch = tempfile::tempdir().unwrap(); - let profile = scratch.path().to_path_buf(); - let created = create_in(&profile, "Boulot").unwrap(); - let open = registry_in(&profile).open; - - rename_in(&profile, &created.id, " Archives ").unwrap(); - - let registry = registry_in(&profile); - let renamed = registry.entry(&created.id).unwrap(); - assert_eq!(renamed.name, "Archives"); - assert_eq!(renamed.directory, created.directory); - assert_eq!(registry.open, open); - } - - #[test] - fn renaming_one_that_does_not_exist_says_so() { - let scratch = tempfile::tempdir().unwrap(); - let profile = scratch.path().to_path_buf(); - registry_in(&profile); - - assert!(matches!( - rename_in(&profile, "nothing", "Archives"), - Err(StorageError::LibraryNotFound(_)) - )); + fn a_library_not_listed_is_answered_by_name() { + let profile = profile(); + + for answer in [ + point_at(profile.path(), "missing"), + rename_in(profile.path(), "missing", "x"), + delete_in(profile.path(), "missing"), + ] { + assert!(matches!(answer, Err(StorageError::LibraryNotFound(id)) if id == "missing")); + } } + /// Erased with everything in it; the open one gone, the first is opened instead. #[test] - fn deleting_takes_the_entry_and_the_files() { - let scratch = tempfile::tempdir().unwrap(); - let profile = scratch.path().to_path_buf(); - let created = create_in(&profile, "Boulot").unwrap(); - std::fs::write(directory_of(&profile, &created).join(DATABASE), b"x").unwrap(); + fn a_library_deleted_leaves_the_list_and_the_disk() { + let profile = profile(); + let first = registry_in(profile.path()).libraries[0].clone(); + let second = create_in(profile.path(), "Second").unwrap(); + point_at(profile.path(), &second.id).unwrap(); - delete_in(&profile, &created.id).unwrap(); + delete_in(profile.path(), &second.id).unwrap(); - assert_eq!(registry_in(&profile).libraries.len(), 1); - assert!(!directory_of(&profile, &created).exists()); + let registry = registry_in(profile.path()); + assert_eq!(ids(®istry), [first.id.as_str()]); + assert_eq!(registry.open.as_deref(), Some(first.id.as_str())); + assert!(!profile.path().join(&second.directory).exists()); } + /// The gate would have nothing to offer. #[test] - fn the_last_library_cannot_be_deleted() { - let scratch = tempfile::tempdir().unwrap(); - let profile = scratch.path().to_path_buf(); - let only = registry_in(&profile).libraries[0].clone(); + fn the_last_library_is_never_deleted() { + let profile = profile(); + let only = registry_in(profile.path()).libraries[0].clone(); assert!(matches!( - delete_in(&profile, &only.id), + delete_in(profile.path(), &only.id), Err(StorageError::LastLibrary) )); - assert_eq!(registry_in(&profile).libraries.len(), 1); - } - - #[test] - fn deleting_the_open_one_moves_the_mark_to_what_remains() { - let scratch = tempfile::tempdir().unwrap(); - let profile = scratch.path().to_path_buf(); - let created = create_in(&profile, "Boulot").unwrap(); - point_at(&profile, &created.id).unwrap(); - - delete_in(&profile, &created.id).unwrap(); - - let registry = registry_in(&profile); - assert_eq!(registry.libraries.len(), 1); - assert_eq!( - registry.open.as_deref(), - Some(registry.libraries[0].id.as_str()) - ); - } - - #[test] - fn deleting_one_that_does_not_exist_says_so() { - let scratch = tempfile::tempdir().unwrap(); - let profile = scratch.path().to_path_buf(); - create_in(&profile, "Boulot").unwrap(); - - assert!(matches!( - delete_in(&profile, "nothing"), - Err(StorageError::LibraryNotFound(_)) - )); + assert!(profile.path().join(&only.directory).is_dir()); } } diff --git a/crates/engine/tests/commands/profile.rs b/crates/engine/tests/commands/profile.rs index a81cc2b79..7a18c0b02 100644 --- a/crates/engine/tests/commands/profile.rs +++ b/crates/engine/tests/commands/profile.rs @@ -3,9 +3,11 @@ use engine::error::ErrorCode; use engine::libraries::{ - create_library, delete_library, list_libraries, open_library, rename_library, + create_library, delete_library, list_libraries, open_library, open_library_directory, + rename_library, }; use engine::recovery::{archive_locked_library, set_aside_damaged_library}; +use engine::spaces::list_spaces; use engine::tools::generate_identity; use engine::tools::identity::{Country, IdentityRequest}; use engine::vault::{VaultState, vault_state}; @@ -13,37 +15,86 @@ use engine::vault::{VaultState, vault_state}; use super::{Session, code}; fn names(session: &Session) -> Vec { - session - .call(list_libraries) + let registry = session.call(list_libraries); + registry .libraries .into_iter() .map(|library| library.name) .collect() } +/// Added closed and renamed; opened, it closes the one open, whose commands answer `Locked` +/// and send the interface back to the gate for the other phrase. #[test] -fn a_library_is_added_renamed_opened_and_another_deleted() { +fn a_library_opened_closes_the_one_open_and_the_gate_asks_for_it() { let session = Session::open(); let work = session.call(|e| create_library(e, "Work")).unwrap(); - let old = session.call(|e| create_library(e, "Old")).unwrap(); - assert!(names(&session).contains(&"Work".to_string())); - - let id = work.id.clone(); - session.call(|e| rename_library(e, &id, "Archive")).unwrap(); + session + .call(|e| rename_library(e, &work.id, "Archive")) + .unwrap(); assert!(names(&session).contains(&"Archive".to_string())); + assert_eq!(session.call(vault_state).unwrap(), VaultState::Unlocked); session.call(|e| open_library(e, &work.id)).unwrap(); - assert_eq!(session.call(vault_state).unwrap(), VaultState::Absent); - session.call(|e| delete_library(e, &old.id)).unwrap(); - assert!(!names(&session).contains(&"Old".to_string())); + assert_eq!( + session.call(list_libraries).open.as_deref(), + Some(work.id.as_str()) + ); + assert_eq!(code(session.call(list_spaces)), ErrorCode::Locked); + assert_eq!( + code(session.call(open_library_directory)), + ErrorCode::Locked + ); + assert_eq!(session.call(vault_state).unwrap(), VaultState::Absent); } +/// Deleting files under a live connection takes the process down; another one is deleted, and an +/// id not listed is answered by its code. #[test] -fn the_gate_says_unlocked_while_a_library_is_open() { +fn a_library_is_deleted_unless_it_is_open_and_unlocked() { let session = Session::open(); + let open = session.call(list_libraries).open.unwrap(); + let other = session.call(|e| create_library(e, "Other")).unwrap(); - assert_eq!(session.call(vault_state).unwrap(), VaultState::Unlocked); + assert_eq!( + code(session.call(|e| delete_library(e, &open))), + ErrorCode::LibraryOpen + ); + session.call(|e| delete_library(e, &other.id)).unwrap(); + assert_eq!(names(&session).len(), 1); + assert_eq!( + code(session.call(|e| rename_library(e, "missing", "x"))), + ErrorCode::LibraryNotFound + ); +} + +/// Locked, the open library may go: no connection holds its files. The last one never does. +#[test] +fn the_open_library_is_deleted_once_it_is_locked_but_never_the_last() { + let session = Session::locked(); + let open = session.call(list_libraries).open.unwrap(); + session.call(|e| create_library(e, "Other")).unwrap(); + + session.call(|e| delete_library(e, &open)).unwrap(); + + assert_eq!(names(&session), ["Other"]); + let last = session.call(list_libraries).open.unwrap(); + assert_eq!( + code(session.call(|e| delete_library(e, &last))), + ErrorCode::LastLibrary + ); +} + +/// Its own `preferences.json` sits there. +#[test] +fn the_open_library_s_folder_is_where_its_database_is() { + let scratch = tempfile::tempdir().unwrap(); + let session = Session::on_disk(scratch.path()); + + let directory = session.call(open_library_directory).unwrap(); + + assert_eq!(directory, scratch.path()); } #[test] From 276d0274cd2cef1d53158f6a07aa9ff27fa4139b Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:35:05 +0100 Subject: [PATCH 30/95] Backups: unit tests rewritten for the copies and putting one back (#1752) * Rewrite the tests of the launch copies, putting one back and the backup services Co-Authored-By: Claude Opus 5.5 * A folder in the attachments, a library without one, and putting back what a failed restore moved Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/backup.rs | 53 -- crates/engine/src/backup/copies.rs | 694 +++++++++++------------- crates/engine/tests/commands/backups.rs | 184 +++++-- 3 files changed, 450 insertions(+), 481 deletions(-) diff --git a/crates/engine/src/backup.rs b/crates/engine/src/backup.rs index b5211a1f4..818950ba5 100644 --- a/crates/engine/src/backup.rs +++ b/crates/engine/src/backup.rs @@ -95,56 +95,3 @@ fn restore(db: &Db, id: &str, now: DateTime) -> Result DateTime { + const PHRASE: &str = "a passphrase"; + + fn at(offset_hours: i64) -> DateTime { db::iso8601::parse("2026-07-25T09:00:00.000Z").unwrap() + TimeDelta::hours(offset_hours) } - /// A library with one note in it, and the key file beside it, as a real one is. - pub(crate) fn library(directory: &Path) -> (Library, String) { - let vault = crate::vault::file::create( - directory, - "a passphrase", - crate::vault::key::Cost::FOR_TESTS, - ) - .unwrap(); + fn draft(space_id: &str, title: &str) -> crate::notes::model::NoteDraft { + crate::notes::model::NoteDraft { + space_id: space_id.to_string(), + folder_id: None, + title: title.to_string(), + language: crate::notes::language::Language::Txt, + content: "psql -h prod".to_string(), + source: String::new(), + tags: Vec::new(), + pinned: false, + lifecycle: crate::notes::model::NoteLifecycle::Permanent, + kind: crate::notes::kind::NoteKind::Snippet, + priority: crate::notes::priority::Priority::None, + items: Vec::new(), + } + } + /// A library on disk as a real one is: its key file beside it, one note, one attachment. + fn library(directory: &Path) -> (Library, String) { + let vault = file::create(directory, PHRASE, Cost::FOR_TESTS).unwrap(); let mut connection = db::open(&directory.join(layout::DATABASE), vault).unwrap(); - let space = spaces::create(&mut connection, "Perso").unwrap().id; - let note = notes::create( - &mut connection, - crate::notes::model::NoteDraft { - space_id: space, - folder_id: None, - title: "À sauvegarder".to_string(), - language: crate::notes::language::Language::Txt, - content: "psql -h prod".to_string(), - source: String::new(), - tags: Vec::new(), - pinned: false, - lifecycle: crate::notes::model::NoteLifecycle::Permanent, - kind: crate::notes::kind::NoteKind::Snippet, - priority: crate::notes::priority::Priority::None, - items: Vec::new(), - }, - at(0), - ) - .unwrap() - .id; + let space = spaces::create(&mut connection, "Work").unwrap().id; + let note = notes::create(&mut connection, draft(&space, "Kept"), at(0)) + .unwrap() + .id; + std::fs::create_dir_all(directory.join(ATTACHMENTS)).unwrap(); + std::fs::write(directory.join(ATTACHMENTS).join("a-1.png"), b"png").unwrap(); (connection, note) } - /// A copy that cannot be opened is not a backup. + fn titles_in(directory: &Path, passphrase: &str) -> Vec { + let vault = file::unlock(directory, passphrase).unwrap(); + let mut copy = db::open(&directory.join(layout::DATABASE), vault).unwrap(); + let read = notes::all(&mut copy, None).unwrap(); + read.into_iter().map(|note| note.title).collect() + } + + fn ids(directory: &Path) -> Vec { + list(directory) + .into_iter() + .map(|backup| backup.id) + .collect() + } + + /// A copy that cannot be opened is no backup: its key file travels, its attachments too. #[test] - fn a_copy_opens_as_a_library_and_holds_the_notes() { + fn a_copy_opens_on_its_own_with_the_notes_and_the_attachments() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, note_id) = library(&directory); + let (mut connection, _) = library(scratch.path()); - let target = rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); + let target = rotate(scratch.path(), &mut connection, at(0)) + .unwrap() + .unwrap(); - let reopened = crate::vault::file::unlock(&target, "a passphrase").unwrap(); - let mut copy = db::open(&target.join(layout::DATABASE), reopened).unwrap(); - let written = notes::all(&mut copy, None).unwrap(); + assert_eq!( + target, + scratch.path().join(BACKUPS).join(layout::stamp(at(0))) + ); + assert_eq!(titles_in(&target, PHRASE), ["Kept"]); + assert_eq!( + std::fs::read(target.join(ATTACHMENTS).join("a-1.png")).unwrap(), + b"png" + ); + } + + /// One file under two names: the copy costs no disk, and a purge in the library only + /// unlinks, leaving the copy whole. + #[test] + fn a_copy_links_the_attachments_rather_than_copying_them() { + use std::io::Write; + + let scratch = tempfile::tempdir().unwrap(); + let (mut connection, _) = library(scratch.path()); + let target = rotate(scratch.path(), &mut connection, at(0)) + .unwrap() + .unwrap(); + let live = scratch.path().join(ATTACHMENTS).join("a-1.png"); + let copied = target.join(ATTACHMENTS).join("a-1.png"); + + let mut through_the_library = std::fs::OpenOptions::new() + .append(true) + .open(&live) + .unwrap(); + through_the_library.write_all(b", once").unwrap(); + drop(through_the_library); + std::fs::remove_file(&live).unwrap(); - assert_eq!(written.len(), 1); - assert_eq!(written[0].id, note_id); - assert_eq!(written[0].title, "À sauvegarder"); + assert_eq!(std::fs::read(&copied).unwrap(), b"png, once"); } + /// `attachments/` is flat: a folder found in it is no attachment, and fails nothing. #[test] - fn the_key_file_travels_with_the_database() { + fn a_folder_inside_the_attachments_is_passed_over() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); + let (mut connection, _) = library(scratch.path()); + std::fs::create_dir_all(scratch.path().join(ATTACHMENTS).join("stray")).unwrap(); - let target = rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); + let target = rotate(scratch.path(), &mut connection, at(0)) + .unwrap() + .unwrap(); - assert!(target.join(KEY_FILE).is_file()); - assert!(target.join(layout::DATABASE).is_file()); + assert!(target.join(ATTACHMENTS).join("a-1.png").is_file()); + assert!(!target.join(ATTACHMENTS).join("stray").exists()); } - fn attach(directory: &Path, name: &str, bytes: &[u8]) { - std::fs::create_dir_all(directory.join(ATTACHMENTS)).unwrap(); - std::fs::write(directory.join(ATTACHMENTS).join(name), bytes).unwrap(); + /// A library with no attachment folder yet, and a copy taken before it had one. + #[test] + fn a_library_without_an_attachments_folder_is_copied_and_put_back() { + let scratch = tempfile::tempdir().unwrap(); + let (mut connection, _) = library(scratch.path()); + std::fs::remove_dir_all(scratch.path().join(ATTACHMENTS)).unwrap(); + rotate(scratch.path(), &mut connection, at(0)).unwrap(); + drop(connection); + + replace(scratch.path(), &layout::stamp(at(0)), at(1)).unwrap(); + + assert_eq!(titles_in(scratch.path(), PHRASE), ["Kept"]); } - /// Purged from the library afterwards, an attachment is still whole in the copy: the link - /// is what goes, not the bytes. + /// ⚠️ A failed restore must never leave no library at all: what was set aside goes back, + /// directories included, over whatever half of the copy had landed. Private: nothing + /// public can fail once the attachments have moved, the copy's files being checked first. #[test] - fn the_attachments_travel_with_the_copy_and_outlive_a_purge() { + fn putting_back_undoes_a_half_finished_restore() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - attach(&directory, "a-1.png", b"\x89PNG sealed"); + let directory = scratch.path(); + std::fs::create_dir_all(directory.join(ATTACHMENTS)).unwrap(); + std::fs::write(directory.join(ATTACHMENTS).join("a-1.png"), b"live").unwrap(); + std::fs::write(directory.join(KEY_FILE), b"live key").unwrap(); + let aside = directory.join(REPLACED).join(layout::stamp(at(0))); + std::fs::create_dir_all(&aside).unwrap(); + let mut moved = Vec::new(); + for name in [KEY_FILE, ATTACHMENTS] { + std::fs::rename(directory.join(name), aside.join(name)).unwrap(); + moved.push((directory.join(name), aside.join(name))); + } + std::fs::write(directory.join(KEY_FILE), b"half copied").unwrap(); + std::fs::create_dir_all(directory.join(ATTACHMENTS)).unwrap(); + std::fs::write( + directory.join(ATTACHMENTS).join("from-the-copy.png"), + b"half", + ) + .unwrap(); - let target = rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); - std::fs::remove_file(directory.join(ATTACHMENTS).join("a-1.png")).unwrap(); + put_back(&moved, &aside); assert_eq!( - std::fs::read(target.join(ATTACHMENTS).join("a-1.png")).unwrap(), - b"\x89PNG sealed" + std::fs::read(directory.join(KEY_FILE)).unwrap(), + b"live key" + ); + assert!(directory.join(ATTACHMENTS).join("a-1.png").is_file()); + assert!( + !directory + .join(ATTACHMENTS) + .join("from-the-copy.png") + .exists() ); + assert!(!aside.exists()); } - /// One file under two names, not two files: what is written through one reads through the - /// other. Nothing in the application writes an attachment twice; this shows the copy is free. + /// A half-written copy would be the newest, and hold the next rotation off. #[test] - fn the_copy_shares_the_attachments_rather_than_duplicating_them() { - use std::io::Write; - + fn a_copy_that_cannot_take_the_key_file_leaves_nothing_behind() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - attach(&directory, "a-1.png", b"linked"); + let (mut connection, _) = library(scratch.path()); + let (key, moved) = (scratch.path().join(KEY_FILE), scratch.path().join("moved")); + std::fs::rename(&key, &moved).unwrap(); - let target = rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); - std::fs::OpenOptions::new() - .append(true) - .open(directory.join(ATTACHMENTS).join("a-1.png")) - .unwrap() - .write_all(b", once") - .unwrap(); + let failed = rotate(scratch.path(), &mut connection, at(0)); + std::fs::rename(&moved, &key).unwrap(); + let retried = rotate(scratch.path(), &mut connection, at(1)).unwrap(); + assert!(matches!(failed, Err(StorageError::File(_)))); assert_eq!( - std::fs::read(target.join(ATTACHMENTS).join("a-1.png")).unwrap(), - b"linked, once" + retried, + Some(scratch.path().join(BACKUPS).join(layout::stamp(at(1)))) ); + assert_eq!(list(scratch.path()).len(), 1); } - /// Counting the shared attachments in each copy would make three copies look like three - /// times the disk. + /// Five launches in an hour must not rotate every older copy out. #[test] - fn a_copy_is_listed_at_the_size_of_its_database() { + fn a_copy_is_taken_at_most_once_a_day() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - attach(&directory, "a-1.png", &[0u8; 4096]); + let (mut connection, _) = library(scratch.path()); + rotate(scratch.path(), &mut connection, at(0)).unwrap(); - let target = rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); + let soon = rotate(scratch.path(), &mut connection, at(23)).unwrap(); + let next_day = rotate(scratch.path(), &mut connection, at(24)).unwrap(); - let database = std::fs::metadata(target.join(layout::DATABASE)) - .unwrap() - .len(); - assert_eq!(list(&directory)[0].bytes, database); + assert_eq!(soon, None); + assert!(next_day.is_some()); + assert_eq!(list(scratch.path()).len(), 2); } + /// Enough to reach past the launch that went wrong without becoming a second library. #[test] - fn linking_onto_a_name_already_there_leaves_both_whole() { + fn three_copies_are_kept_newest_first() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - attach(&directory, "a-1.png", b"the bytes"); - let into = directory.join("into"); + let (mut connection, _) = library(scratch.path()); - link_files(&directory.join(ATTACHMENTS), &into).unwrap(); - link_files(&directory.join(ATTACHMENTS), &into).unwrap(); + for day in 0..5 { + rotate(scratch.path(), &mut connection, at(24 * day)).unwrap(); + } - assert_eq!(std::fs::read(into.join("a-1.png")).unwrap(), b"the bytes"); - assert_eq!( - std::fs::read(directory.join(ATTACHMENTS).join("a-1.png")).unwrap(), - b"the bytes" - ); + let kept: Vec = [4, 3, 2] + .iter() + .map(|day| layout::stamp(at(24 * day))) + .collect(); + assert_eq!(ids(scratch.path()), kept); } + /// Whether the key file travelled says whether a restore can open it; the database alone is + /// weighed, the attachments being shared. #[test] - fn a_second_launch_the_same_day_takes_nothing() { + fn a_copy_is_listed_with_its_size_and_whether_it_opens() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); + let (mut connection, _) = library(scratch.path()); + let whole = rotate(scratch.path(), &mut connection, at(0)) + .unwrap() + .unwrap(); + let keyless = rotate(scratch.path(), &mut connection, at(48)) + .unwrap() + .unwrap(); + std::fs::remove_file(keyless.join(KEY_FILE)).unwrap(); + std::fs::create_dir_all(scratch.path().join(BACKUPS).join("not a stamp")).unwrap(); - let again = rotate(&directory, &mut connection, at(3)).unwrap(); + let listed = list(scratch.path()); - assert!(again.is_none()); - assert_eq!(existing(&directory.join(BACKUPS)).len(), 1); + let shown: Vec<(&str, bool)> = listed + .iter() + .map(|backup| (backup.id.as_str(), backup.openable)) + .collect(); + let (whole_id, keyless_id) = (layout::stamp(at(0)), layout::stamp(at(48))); + assert_eq!( + shown, + [(keyless_id.as_str(), false), (whole_id.as_str(), true)] + ); + assert_eq!(listed[1].taken_at, at(0)); + let size = std::fs::metadata(whole.join(layout::DATABASE)) + .unwrap() + .len(); + assert_eq!(listed[1].bytes, size); } + /// Moved aside, never deleted, its key file with it; an attachment added since kept aside. #[test] - fn a_launch_the_next_day_takes_another() { + fn a_copy_put_back_sets_the_live_library_aside_whole() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - rotate(&directory, &mut connection, at(0)).unwrap(); + let library_at = scratch.path(); + let (mut connection, _) = library(library_at); + rotate(library_at, &mut connection, at(0)).unwrap(); + let space = spaces::list(&mut connection).unwrap()[0].id.clone(); + notes::create(&mut connection, draft(&space, "Since"), at(1)).unwrap(); + std::fs::write(library_at.join(ATTACHMENTS).join("a-2.png"), b"new").unwrap(); + drop(connection); + + let aside = replace(library_at, &layout::stamp(at(0)), at(2)).unwrap(); + + assert_eq!(aside, library_at.join(REPLACED).join(layout::stamp(at(2)))); + assert_eq!(titles_in(library_at, PHRASE), ["Kept"]); + let mut set_aside = titles_in(&aside, PHRASE); + set_aside.sort(); + assert_eq!(set_aside, ["Kept", "Since"]); + assert!(aside.join(ATTACHMENTS).join("a-2.png").is_file()); + assert!(!library_at.join(ATTACHMENTS).join("a-2.png").exists()); + assert!(library_at.join(ATTACHMENTS).join("a-1.png").is_file()); + } - rotate(&directory, &mut connection, at(25)) + #[test] + fn a_copy_not_there_or_without_its_key_is_not_put_back() { + let scratch = tempfile::tempdir().unwrap(); + let (mut connection, _) = library(scratch.path()); + let copy = rotate(scratch.path(), &mut connection, at(0)) .unwrap() .unwrap(); + std::fs::remove_file(copy.join(KEY_FILE)).unwrap(); + drop(connection); - assert_eq!(existing(&directory.join(BACKUPS)).len(), 2); + let missing = replace(scratch.path(), "missing", at(1)); + let keyless = replace(scratch.path(), &layout::stamp(at(0)), at(1)); + + assert!(matches!(missing, Err(StorageError::BackupNotFound(id)) if id == "missing")); + assert!(matches!(keyless, Err(StorageError::BackupUnopenable(_)))); + assert!(!scratch.path().join(REPLACED).exists()); + assert_eq!(titles_in(scratch.path(), PHRASE), ["Kept"]); } + /// ⚠️ The id comes from the front end, and `../` still parses as a stamp. #[test] - fn only_the_last_few_are_kept() { + fn a_copy_is_found_by_its_listing_never_by_a_path() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - - for day in 0..6 { - rotate(&directory, &mut connection, at(day * 25)).unwrap(); + let (mut connection, _) = library(scratch.path()); + let copy = rotate(scratch.path(), &mut connection, at(0)) + .unwrap() + .unwrap(); + drop(connection); + let stamp = layout::stamp(at(0)); + let outside = scratch.path().join(&stamp); + std::fs::create_dir_all(&outside).unwrap(); + for name in [layout::DATABASE, KEY_FILE] { + std::fs::copy(copy.join(name), outside.join(name)).unwrap(); } - let kept = existing(&directory.join(BACKUPS)); - assert_eq!(kept.len(), KEEP); - // The newest survive, not the first ones taken. - assert_eq!(taken_at(&kept[0]).unwrap(), at(5 * 25)); + let refused = replace(scratch.path(), &format!("../{stamp}"), at(1)); + + assert!(matches!(refused, Err(StorageError::BackupNotFound(_)))); + assert!(!scratch.path().join(REPLACED).exists()); } - /// Changing the phrase is what somebody does when they believe the old one leaked, and each - /// copy in the same profile holds a key file wrapped under it. + /// ⚠️ A restore that cannot finish must never leave no library at all. #[test] - fn changing_the_passphrase_stops_the_old_one_opening_a_backup() { + fn a_restore_that_cannot_set_the_live_key_aside_leaves_the_library_where_it_was() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - let target = rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); - - let vault = crate::vault::file::change_passphrase( - &directory, - "a passphrase", - "a new one", - Cost::FOR_TESTS, - ) - .unwrap(); + let (mut connection, _) = library(scratch.path()); + rotate(scratch.path(), &mut connection, at(0)).unwrap(); + drop(connection); + let database = std::fs::read(scratch.path().join(layout::DATABASE)).unwrap(); + std::fs::rename(scratch.path().join(KEY_FILE), scratch.path().join("moved")).unwrap(); - // Rewrapping the live file alone revokes nothing. - crate::vault::file::unlock(&target, "a passphrase") - .expect("the copy still opens with the retired phrase before the rewrap"); + let failed = replace(scratch.path(), &layout::stamp(at(0)), at(1)); - let tally = rewrap(&directory, &vault, "a new one", Cost::FOR_TESTS); - - assert_eq!(tally, Rewrapped { done: 1, left: 0 }); + assert!(matches!(failed, Err(StorageError::File(_)))); + assert_eq!( + std::fs::read(scratch.path().join(layout::DATABASE)).unwrap(), + database + ); assert!( - crate::vault::file::unlock(&target, "a passphrase").is_err(), - "the retired passphrase still opens the backup" + !scratch + .path() + .join(REPLACED) + .join(layout::stamp(at(1))) + .exists() ); - // And the copy is not merely shut: it opens under the new one, on the same key. - crate::vault::file::unlock(&target, "a new one").unwrap(); } - /// A copy is rewrapped from the key, not opened with the phrase being retired, so one taken - /// two changes ago is reached as well. + /// ⚠️ What makes a new phrase revoke anything: every retained copy's key file is rewrapped + /// from the key, so one wrapped under an older phrase goes too; a copy without one is + /// passed over. #[test] - fn a_copy_left_over_from_an_older_phrase_is_reached_too() { + fn a_new_phrase_reaches_every_copy_s_key_file() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - let first = rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); - - let vault = crate::vault::file::change_passphrase( - &directory, - "a passphrase", - "the second", - Cost::FOR_TESTS, - ) - .unwrap(); - // No rewrap here: the first copy stays under the very first phrase. - let second = rotate(&directory, &mut connection, at(25)) + let (mut connection, _) = library(scratch.path()); + let first = rotate(scratch.path(), &mut connection, at(0)) + .unwrap() + .unwrap(); + let keyless = rotate(scratch.path(), &mut connection, at(48)) .unwrap() .unwrap(); - crate::vault::file::write_wrapped( - &second.join(KEY_FILE), + std::fs::remove_file(keyless.join(KEY_FILE)).unwrap(); + let vault = file::unlock(scratch.path(), PHRASE).unwrap(); + file::write_wrapped( + &first.join(KEY_FILE), &vault, - "the second", + "an older one", Cost::FOR_TESTS, ) .unwrap(); - let vault = crate::vault::file::change_passphrase( - &directory, - "the second", - "the third", + let tally = rewrap( + scratch.path(), + &vault, + "the next passphrase", Cost::FOR_TESTS, - ) - .unwrap(); - let tally = rewrap(&directory, &vault, "the third", Cost::FOR_TESTS); + ); - assert_eq!(tally.done, 2); - for copy in [&first, &second] { - assert!(crate::vault::file::unlock(copy, "a passphrase").is_err()); - assert!(crate::vault::file::unlock(copy, "the second").is_err()); - crate::vault::file::unlock(copy, "the third").unwrap(); - } + assert_eq!(tally, Rewrapped { done: 1, left: 0 }); + assert!(matches!( + file::unlock(&first, "an older one"), + Err(StorageError::WrongPassphrase) + )); + assert_eq!(titles_in(&first, "the next passphrase"), ["Kept"]); + assert!(!keyless.join(KEY_FILE).exists()); } - /// A copy taken before the library was sealed has no key file to retire. + /// Counted rather than failed: a key file that cannot be rewritten must not block the + /// revocation at the moment it is asked for. #[test] - fn a_copy_with_no_key_file_is_left_alone_rather_than_counted() { + fn a_key_file_that_cannot_be_rewritten_is_counted_as_left() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - let target = rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); - std::fs::remove_file(target.join(KEY_FILE)).unwrap(); - - let vault = crate::vault::file::unlock(&directory, "a passphrase").unwrap(); - let tally = rewrap(&directory, &vault, "a new one", Cost::FOR_TESTS); - - assert_eq!(tally, Rewrapped { done: 0, left: 0 }); - } - - mod restoring { - use super::*; - - /// Reads the one note's title straight out of a library on disk. - fn title_in(directory: &Path, passphrase: &str) -> String { - let vault = crate::vault::file::unlock(directory, passphrase).unwrap(); - let mut connection = db::open(&directory.join(layout::DATABASE), vault).unwrap(); - - notes::all(&mut connection, None).unwrap()[0].title.clone() - } - - fn retitle(connection: &mut Library, id: &str, title: &str) { - notes::update( - connection, - id, - &crate::notes::model::NotePatch { - title: Some(title.to_string()), - ..Default::default() - }, - at(1), - ) + let (mut connection, _) = library(scratch.path()); + let copy = rotate(scratch.path(), &mut connection, at(0)) + .unwrap() .unwrap(); - } - - #[test] - fn the_copy_takes_the_place_of_the_live_library() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, note) = library(&directory); - let copy = rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); - let id = copy.file_name().unwrap().to_str().unwrap().to_string(); - retitle(&mut connection, ¬e, "écrit après la copie"); - drop(connection); - - replace(&directory, &id, at(30)).unwrap(); - - assert_eq!(title_in(&directory, "a passphrase"), "À sauvegarder"); - } - - #[test] - fn the_library_it_replaced_is_still_readable_where_it_was_put() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, note) = library(&directory); - let copy = rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); - let id = copy.file_name().unwrap().to_str().unwrap().to_string(); - retitle(&mut connection, ¬e, "écrit après la copie"); - drop(connection); - - let aside = replace(&directory, &id, at(30)).unwrap(); - - assert!(aside.starts_with(directory.join(REPLACED))); - assert_eq!(title_in(&aside, "a passphrase"), "écrit après la copie"); - } - - /// A database from one wrapping and a key file from another open nothing. - #[test] - fn the_key_file_goes_one_way_and_comes_back_the_other() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - let copy = rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); - let id = copy.file_name().unwrap().to_str().unwrap().to_string(); - drop(connection); - - let aside = replace(&directory, &id, at(30)).unwrap(); - - assert!(directory.join(KEY_FILE).is_file()); - assert!(aside.join(KEY_FILE).is_file()); - } - - /// The live ones go aside with the database: one written since the copy is not lost, - /// and the restored records name only what the copy brought. - #[test] - fn the_attachments_come_back_with_the_copy() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - attach(&directory, "a-1.png", b"as copied"); - let copy = rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); - let id = copy.file_name().unwrap().to_str().unwrap().to_string(); - drop(connection); - std::fs::remove_file(directory.join(ATTACHMENTS).join("a-1.png")).unwrap(); - attach(&directory, "a-2.png", b"added since"); - - let aside = replace(&directory, &id, at(30)).unwrap(); - - assert_eq!( - std::fs::read(directory.join(ATTACHMENTS).join("a-1.png")).unwrap(), - b"as copied" - ); - assert!(!directory.join(ATTACHMENTS).join("a-2.png").exists()); - assert!(aside.join(ATTACHMENTS).join("a-2.png").is_file()); - } - - /// A failed copy leaves both halves as they were, directories included. - #[test] - fn putting_back_undoes_a_half_finished_restore() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - attach(&directory, "a-1.png", b"live"); - std::fs::write(directory.join(KEY_FILE), b"live key").unwrap(); - let aside = directory.join(REPLACED).join("2026-07-25_09-00-00"); - std::fs::create_dir_all(&aside).unwrap(); - let mut moved = Vec::new(); - for name in [KEY_FILE, ATTACHMENTS] { - std::fs::rename(directory.join(name), aside.join(name)).unwrap(); - moved.push((directory.join(name), aside.join(name))); - } - std::fs::write(directory.join(KEY_FILE), b"half copied").unwrap(); - attach(&directory, "from-the-copy.png", b"half"); - - put_back(&moved, &aside); - - assert_eq!( - std::fs::read(directory.join(KEY_FILE)).unwrap(), - b"live key" - ); - assert!(directory.join(ATTACHMENTS).join("a-1.png").is_file()); - assert!( - !directory - .join(ATTACHMENTS) - .join("from-the-copy.png") - .exists() - ); - assert!(!aside.exists()); - } - - #[test] - fn an_id_cannot_name_a_directory_outside_the_copies() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - rotate(&directory, &mut connection, at(0)).unwrap(); - drop(connection); - let outside = directory.join("2026-07-25_09-00-00"); - std::fs::create_dir_all(&outside).unwrap(); - std::fs::write(outside.join(layout::DATABASE), b"not a library").unwrap(); - std::fs::write(outside.join(KEY_FILE), b"{}").unwrap(); - - let refused = replace(&directory, "../2026-07-25_09-00-00", at(30)); - - assert!(refused.is_err()); - assert!( - directory.join(layout::DATABASE).is_file(), - "the library is still there" - ); - } + let vault = file::unlock(scratch.path(), PHRASE).unwrap(); + let refused = Cost { + memory_kib: 0, + passes: 0, + lanes: 0, + }; - #[test] - fn a_copy_with_no_key_file_is_refused_rather_than_swapped_in() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - let copy = rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); - let id = copy.file_name().unwrap().to_str().unwrap().to_string(); - drop(connection); - std::fs::remove_file(copy.join(KEY_FILE)).unwrap(); - - let refused = replace(&directory, &id, at(30)); - - assert!(refused.is_err()); - assert!(directory.join(layout::DATABASE).is_file()); - assert!(!directory.join(REPLACED).exists(), "nothing was set aside"); - } + let tally = rewrap(scratch.path(), &vault, "the next passphrase", refused); - #[test] - fn a_listing_says_when_each_copy_was_taken_and_whether_it_opens() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - rotate(&directory, &mut connection, at(0)).unwrap(); - rotate(&directory, &mut connection, at(25)).unwrap(); - - let copies = list(&directory); - - assert_eq!(copies.len(), 2); - // Newest first, the order the panel wants and the pruning uses. - assert_eq!(copies[0].taken_at, at(25)); - assert!(copies[0].bytes > 0); - assert!(copies.iter().all(|copy| copy.openable)); - } + assert_eq!(tally, Rewrapped { done: 0, left: 1 }); + assert_eq!(titles_in(©, PHRASE), ["Kept"]); } - /// A stray directory must not hold the rotation off by looking like the newest copy. + /// ⚠️ A name already there is the same attachment, often the very same file: copying over + /// it would truncate the source being read. #[test] - fn something_that_is_not_a_copy_is_ignored() { + fn linking_onto_a_name_already_there_leaves_both_whole() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - std::fs::create_dir_all(directory.join(BACKUPS).join("notes de Valentin")).unwrap(); + let (from, into) = (scratch.path().join("from"), scratch.path().join("into")); + std::fs::create_dir_all(&from).unwrap(); + std::fs::write(from.join("a-1.png"), b"the bytes").unwrap(); - let target = rotate(&directory, &mut connection, at(0)).unwrap(); + link_files(&from, &into).unwrap(); + link_files(&from, &into).unwrap(); - assert!(target.is_some()); + assert_eq!(std::fs::read(into.join("a-1.png")).unwrap(), b"the bytes"); + assert_eq!(std::fs::read(from.join("a-1.png")).unwrap(), b"the bytes"); } } diff --git a/crates/engine/tests/commands/backups.rs b/crates/engine/tests/commands/backups.rs index c700c53d3..3e28d34e9 100644 --- a/crates/engine/tests/commands/backups.rs +++ b/crates/engine/tests/commands/backups.rs @@ -1,71 +1,155 @@ -use std::fs; +use std::path::Path; -use engine::backup::{restore_backup, take_restored_aside}; -use engine::db::open; -use engine::vault::file::create; -use engine::vault::key::Cost; +use chrono::{TimeDelta, Utc}; +use diesel::prelude::*; +use engine::backup::{list_backups, restore_backup, take_restored_aside}; +use engine::db::schema::notes as notes_table; +use engine::error::ErrorCode; +use engine::libraries::open_library_directory; +use engine::notes::store::trash::trashed_ids; +use engine::notes::{create_note, delete_note, get_note, list_trash}; +use engine::spaces::list_spaces; +use engine::vault::{VaultState, create_vault, secret, unlock_vault, vault_state}; -use super::Session; +use super::common::snippet; +use super::{Session, code}; -const COPY: &str = "2026-07-25_09-00-00"; +const PHRASE: &str = "correct horse battery staple"; -/// The page a restore reloads asks where the replaced library went, and is told once. -#[test] -fn a_restore_keeps_where_the_library_went_for_the_page_it_reloads() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path(); - let vault = create(directory, "a passphrase", Cost::FOR_TESTS).unwrap(); - let library = open(&directory.join("devnotes.sqlite3"), vault).unwrap(); - // A copy as the launch writes one: the database and its key file, under its stamp. - let copy = directory.join("backups").join(COPY); - fs::create_dir_all(©).unwrap(); - for name in ["devnotes.sqlite3", "vault.json"] { - fs::copy(directory.join(name), copy.join(name)).unwrap(); - } - let session = Session::with(Some(library)); - let space = session.space("Personal"); +/// A library created at the gate, as on a first launch: its key file beside it. +fn created(copies: bool) -> Session { + let session = Session::locked(); + session.engine.keep_launch_copies(copies); session - .call(|e| engine::notes::create_note(e, super::common::snippet(&space))) + .call(|e| create_vault(e, secret(PHRASE.to_owned()))) .unwrap(); - session.wait(engine::index::fill); - assert_eq!(session.engine.indexed(), 1); - let aside = session.call(|e| restore_backup(e, COPY)).unwrap(); + session +} - assert!( - directory - .join(&aside) - .starts_with(directory.join("replaced")) - ); +/// The next launch: the library closed with the process, then unlocked. +fn relaunch(session: &Session) { + *session.engine.db().lock().unwrap() = None; + session + .call(|e| unlock_vault(e, secret(PHRASE.to_owned()))) + .unwrap(); +} + +fn a_note(session: &Session) -> String { + let space = session.space("Copied"); + + session + .call(|e| create_note(e, snippet(&space))) + .unwrap() + .note + .id +} + +fn newest_copy(session: &Session) -> String { + session.call(list_backups).unwrap().remove(0).id +} + +#[test] +fn copies_answer_locked_before_a_library_is_open() { + let session = Session::locked(); + + assert_eq!(code(session.call(list_backups)), ErrorCode::Locked); assert_eq!( - session.engine.indexed(), - 0, - "the index of the library replaced is wiped" + code(session.call(|e| restore_backup(e, "2026-07-25_09-00-00"))), + ErrorCode::Locked ); - assert_eq!(session.call(take_restored_aside), Some(aside)); assert_eq!(session.call(take_restored_aside), None); } /// The person's setting reaches the core as a flag: off, the unlock takes no copy. #[test] fn the_launch_copy_is_taken_only_while_the_setting_wants_it() { - let passphrase = || engine::vault::secret("correct horse battery staple".to_owned()); - let session = Session::locked(); - session.engine.keep_launch_copies(false); + let off = created(false); + let on = created(true); + + assert!(off.call(list_backups).unwrap().is_empty()); + let taken = on.call(list_backups).unwrap(); + assert_eq!(taken.len(), 1); + assert!(taken[0].openable); +} + +/// ⚠️ Taken before the launch sweeps: a copy is worth most holding what retention purges. +#[test] +fn the_launch_copy_holds_what_the_launch_purges_from_the_trash() { + let session = created(false); + let note = a_note(&session); + session.call(|e| delete_note(e, ¬e)).unwrap(); + let long_ago = engine::db::iso8601::format(Utc::now() - TimeDelta::days(40)); + { + let mut db = session.engine.db().lock().unwrap(); + diesel::update(notes_table::table.filter(notes_table::id.eq(¬e))) + .set(notes_table::deleted_at.eq(long_ago)) + .execute(db.as_mut().unwrap().db()) + .unwrap(); + } + session.engine.keep_launch_copies(true); + + relaunch(&session); + + assert!(session.call(|e| list_trash(e, "")).unwrap().is_empty()); + let directory = session.call(open_library_directory).unwrap(); + let copy = directory.join("backups").join(newest_copy(&session)); + let vault = engine::vault::file::unlock(©, PHRASE).unwrap(); + let mut copied = engine::db::open(©.join("devnotes.sqlite3"), vault).unwrap(); + assert_eq!(trashed_ids(&mut copied).unwrap(), [note]); +} + +/// ⚠️ Never fatal: a library that cannot be copied still has to open. +#[test] +fn a_library_whose_copy_cannot_be_written_still_opens() { + let session = created(false); + let directory = session.call(open_library_directory).unwrap(); + std::fs::write(directory.join("backups"), b"not a folder").unwrap(); + session.engine.keep_launch_copies(true); + + relaunch(&session); + + assert_eq!(session.call(vault_state).unwrap(), VaultState::Unlocked); + assert!(session.call(list_backups).unwrap().is_empty()); +} + +/// ⚠️ Closed before a file moves: every command then answers `Locked`, which sends the +/// interface back to the gate for the copy's phrase. The index of the library replaced goes +/// with it, and the page the restore reloads is told once where that library went. +#[test] +fn a_copy_put_back_closes_the_library_and_says_once_where_the_live_one_went() { + let session = created(true); + let directory = session.call(open_library_directory).unwrap(); + let copy = newest_copy(&session); + let since = a_note(&session); + session.wait(engine::index::fill); + assert!(session.engine.indexed() > 0); + let aside = session.call(|e| restore_backup(e, ©)).unwrap(); + + assert!(Path::new(&aside).starts_with(directory.join("replaced"))); + assert_eq!(code(session.call(list_spaces)), ErrorCode::Locked); + assert_eq!(session.engine.indexed(), 0); + assert_eq!(session.call(take_restored_aside), Some(aside)); + assert_eq!(session.call(take_restored_aside), None); session - .call(|e| engine::vault::create_vault(e, passphrase())) + .call(|e| unlock_vault(e, secret(PHRASE.to_owned()))) .unwrap(); - - assert!( - session - .call(engine::backup::list_backups) - .unwrap() - .is_empty() + assert_eq!( + code(session.call(|e| get_note(e, &since))), + ErrorCode::NoteNotFound ); - let other = Session::locked(); - other - .call(|e| engine::vault::create_vault(e, passphrase())) - .unwrap(); - assert_eq!(other.call(engine::backup::list_backups).unwrap().len(), 1); +} + +/// A copy gone since the list was drawn is answered by its code, and the page told nothing. +#[test] +fn a_copy_not_there_is_not_put_back() { + let session = created(true); + let directory = session.call(open_library_directory).unwrap(); + + let answer = session.call(|e| restore_backup(e, "2026-07-25_09-00-00")); + + assert_eq!(code(answer), ErrorCode::BackupNotFound); + assert_eq!(session.call(take_restored_aside), None); + assert!(!directory.join("replaced").exists()); } From 15e58f401ad5ad6d92061a33ad1bea5a364f2934 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:46:35 +0100 Subject: [PATCH 31/95] HTTP variables: unit tests rewritten for scopes and filling (#1753) Co-authored-by: Claude Opus 5.5 --- crates/engine/src/http/variables.rs | 594 +++++++++++++++++++--------- 1 file changed, 403 insertions(+), 191 deletions(-) diff --git a/crates/engine/src/http/variables.rs b/crates/engine/src/http/variables.rs index 3c1e89cf5..fc930840f 100644 --- a/crates/engine/src/http/variables.rs +++ b/crates/engine/src/http/variables.rs @@ -411,6 +411,8 @@ pub fn texts<'a>( #[cfg(test)] mod tests { use super::*; + use crate::http::model::{ContainerSettings, HttpItemKind, KeyPlace}; + use crate::http::settings::{HttpOrigin, inherit}; fn variable(name: &str, value: &str) -> Variable { Variable { @@ -420,6 +422,13 @@ mod tests { } } + fn secret(name: &str, value: &str) -> Variable { + Variable { + kind: VariableKind::Secret, + ..variable(name, value) + } + } + fn layer(scope: VariableScope, from: &str, variables: Vec) -> VariableLayer { VariableLayer { scope, @@ -428,267 +437,470 @@ mod tests { } } - #[test] - fn a_span_is_a_name_in_braces_and_nothing_else() { - let spans = spans("{{base}}/users/{{ id }}/{{$guid}}?q={{}}"); + fn resolver(variables: Vec) -> Resolver { + Resolver::new(&[layer(VariableScope::Request, "", variables)]) + } - assert_eq!( - spans, - [(0..8, "base".to_string()), (24..33, "$guid".to_string())] - ); + fn row(key: &str, value: &str) -> KeyValue { + KeyValue { + key: key.to_string(), + value: value.to_string(), + ..KeyValue::default() + } } - #[test] - fn every_scope_survives_its_stored_spelling() { - for scope in VariableScope::ALL { - assert_eq!(scope.as_str().parse::(), Ok(scope)); + fn off(key: &str, value: &str) -> KeyValue { + KeyValue { + enabled: false, + ..row(key, value) + } + } + + fn part(key: &str, value: &str, enabled: bool) -> FormPart { + FormPart { + enabled, + key: key.to_string(), + value: value.to_string(), + ..FormPart::default() } } + fn origin() -> HttpOrigin { + HttpOrigin { + kind: HttpItemKind::Collection, + id: "c-1".to_string(), + name: "Shop".to_string(), + } + } + + /// What a collection hands down: a header and an auth. + fn inherited(header: KeyValue, auth: RequestAuth) -> Inherited { + let settings = ContainerSettings { + auth, + headers: vec![header], + ..ContainerSettings::default() + }; + inherit(&[(origin(), settings)]) + } + + fn bearer(token: &str) -> RequestAuth { + RequestAuth::Bearer { + token: token.to_string(), + } + } + + /// Braces around anything but a name are text; a dynamic value is a name too. #[test] - fn a_dynamic_variable_is_made_at_each_place_it_is_written_and_named_as_such() { - let resolver = Resolver::new(&[]); - let filled = resolver - .fill("{{$guid}}|{{$guid}}|{{$timestamp}}|{{$isoTimestamp}}|{{$randomInt}}|{{$nope}}"); - let parts: Vec<&str> = filled.split('|').collect(); - assert_eq!(parts[0].len(), 36); - assert_ne!(parts[0], parts[1]); - assert!(parts[2].parse::().is_ok()); - assert!(chrono::DateTime::parse_from_rfc3339(parts[3]).is_ok()); - assert!(parts[4].parse::().is_ok_and(|n| n <= 1000)); - assert_eq!(parts[5], "{{$nope}}"); - - let used = resolver.used(&["{{$timestamp}} {{missing}}"]); - assert_eq!( - used[0].resolved.as_ref().map(|known| known.scope), - Some(VariableScope::Dynamic) - ); - assert_eq!(used[1].resolved, None); + fn a_name_between_double_braces_is_found_where_it_stands() { + let found = |text: &str| -> Vec<(std::ops::Range, String)> { spans(text) }; + + assert_eq!(found("{{host}}/a"), [(0..8, "host".to_string())]); + assert_eq!(found("{{ host }} {{a.b}} {{}}"), []); + assert_eq!(found("{{{{id}}"), [(2..8, "id".to_string())]); + assert_eq!(found("{{id"), []); + assert_eq!(found("x{{$guid}}"), [(1..10, "$guid".to_string())]); + assert_eq!(found("{{$unknown}}"), []); } #[test] - fn a_name_is_what_a_field_holds_and_nothing_else() { - assert_eq!( - names_in("{{baseUrl}}/a/{{id}}?q={{id}}&x={{ spaced }}&y={{a.b}}&{{"), - ["baseUrl", "id"] - ); - assert_eq!(names_in("{{{inner}}}"), ["inner"]); - assert!(names_in("no braces, {single}, {{}}").is_empty()); + fn the_names_a_text_holds_come_in_order_each_once() { + let names = names_in("{{b}}/{{a}}?x={{b}}"); + + assert_eq!(names, ["b", "a"]); } + /// What a header's name is judged by until it is filled. #[test] - fn the_nearest_level_wins_and_says_what_it_hides() { - let resolver = Resolver::new(&[ - layer(VariableScope::Request, "", vec![variable("page", "2")]), + fn a_name_counts_as_one_letter_until_filled() { + assert_eq!(as_letters("X-{{tenant}}-Id {{"), "X-x-Id {{"); + } + + /// The nearest level wins a name, and says which further ones it hides and who sets it. + #[test] + fn the_nearest_level_setting_a_name_wins_and_names_what_it_hides() { + let layers = [ layer( - VariableScope::Folder, - "Factures", - vec![variable("page", "1")], + VariableScope::Request, + "", + vec![variable("host", "request")], ), layer( - VariableScope::Environment, - "Staging", - vec![ - variable("baseUrl", "https://staging"), - variable("page", "9"), - ], + VariableScope::Folder, + "Auth", + vec![variable("host", "folder"), variable("user", "ada")], ), layer( - VariableScope::Globals, - "", - vec![variable("baseUrl", "https://global")], + VariableScope::Environment, + "Prod", + vec![variable("host", "prod")], ), - ]); + layer(VariableScope::Globals, "", vec![variable("region", "eu")]), + ]; - let page = resolver.get("page").unwrap(); + let resolver = Resolver::new(&layers); + + let host = resolver.get("host").unwrap(); assert_eq!( - (page.value.as_str(), page.scope), - ("2", VariableScope::Request) + (host.value.as_str(), host.scope, host.from.as_deref()), + ("request", VariableScope::Request, None) ); - assert_eq!(page.from, None); assert_eq!( - page.shadows, + host.shadows, [VariableScope::Folder, VariableScope::Environment] ); - let base = resolver.get("baseUrl").unwrap(); - assert_eq!(base.from.as_deref(), Some("Staging")); + let user = resolver.get("user").unwrap(); assert_eq!( - resolver.fill("{{baseUrl}}/invoices?page={{page}}&tenant={{tenant}}"), - "https://staging/invoices?page=2&tenant={{tenant}}" + (user.scope, user.from.as_deref()), + (VariableScope::Folder, Some("Auth")) ); + assert_eq!(resolver.get("region").unwrap().from, None); + assert_eq!(resolver.get("missing"), None); + } + + /// A row switched off, without a name, or marked by its table is left out: the next level + /// gives the name its value. + #[test] + fn a_row_switched_off_unnamed_or_faulty_is_left_out() { + let near = vec![ + Variable { + enabled: false, + ..variable("off", "near") + }, + variable(" ", "nameless"), + variable("bad name", "near"), + Variable { + kind: VariableKind::Number, + ..variable("count", "many") + }, + variable("twice", "first"), + variable("twice", "second"), + ]; + let far = vec![variable("off", "far"), variable("count", "3")]; + + let resolver = Resolver::new(&[ + layer(VariableScope::Request, "", near), + layer(VariableScope::Collection, "Shop", far), + ]); + + assert_eq!(resolver.get("off").unwrap().value, "far"); + assert_eq!(resolver.get("count").unwrap().value, "3"); + assert_eq!(resolver.get("bad name"), None); + assert_eq!(resolver.get("twice").unwrap().value, "first"); + assert_eq!(resolver.get("").map(|found| found.value.as_str()), None); } + /// A value naming another is filled with it, whatever level each sits on; one that names + /// itself, or a loop, stops filling and stays for the send to name. #[test] - fn a_row_switched_off_or_marked_is_left_out() { - let mut off = variable("token", "old"); - off.enabled = false; + fn a_value_naming_another_is_filled_and_a_loop_stops() { let resolver = Resolver::new(&[ layer( VariableScope::Request, "", vec![ - off, - variable("bad name", "x"), - variable("a", "1"), - variable("a", "2"), + variable("url", "{{scheme}}://{{host}}"), + variable("me", "{{me}}!"), + ], + ), + layer( + VariableScope::Globals, + "", + vec![ + variable("scheme", "https"), + variable("host", "{{sub}}.shop.test"), + variable("sub", "api"), ], ), - layer(VariableScope::Globals, "", vec![variable("token", "new")]), ]); - assert_eq!(resolver.get("token").unwrap().value, "new"); - assert_eq!(resolver.get("a").unwrap().value, "1"); - assert!(resolver.get("bad name").is_none()); + assert_eq!(resolver.get("url").unwrap().value, "https://api.shop.test"); + assert_eq!( + resolver.get("me").unwrap().value, + format!("{{{{me}}}}{}", "!".repeat(NESTING + 1)) + ); + assert_eq!( + resolver.fill("{{url}}/{{unknown}}"), + "https://api.shop.test/{{unknown}}" + ); + } + + /// The spelling a scope is written in reads back as that scope. + #[test] + fn every_scope_reads_back_from_its_spelling() { + for scope in VariableScope::ALL { + assert_eq!(scope.as_str().parse::(), Ok(scope)); + } } + /// A new value each time it is written, which no level can set. #[test] - fn a_value_naming_another_is_filled_and_one_naming_itself_stops() { - let resolver = Resolver::new(&[layer( - VariableScope::Environment, - "Local", - vec![ - variable("host", "localhost:{{port}}"), - variable("port", "8080"), - variable("baseUrl", "http://{{host}}/api"), - variable("loop", "a{{loop}}"), - ], - )]); - - assert_eq!(resolver.fill("{{baseUrl}}"), "http://localhost:8080/api"); - assert!(resolver.fill("{{loop}}").contains("{{loop}}")); + fn a_dynamic_value_is_made_each_time_it_is_written() { + let resolver = resolver(vec![variable("x", "1")]); + + let guids = resolver.fill("{{$guid}} {{$guid}}"); + let (first, second) = guids.split_once(' ').unwrap(); + let uuid = resolver.fill("{{$randomUUID}}"); + let timestamp = resolver.fill("{{$timestamp}}"); + let iso = resolver.fill("{{$isoTimestamp}}"); + let int = resolver.fill("{{$randomInt}}"); + + assert!(uuid::Uuid::parse_str(first).is_ok() && uuid::Uuid::parse_str(&uuid).is_ok()); + assert_ne!(first, second); + assert!(timestamp.parse::().unwrap() > 1_700_000_000); + assert!(chrono::DateTime::parse_from_rfc3339(&iso).is_ok() && iso.ends_with('Z')); + assert!(int.parse::().unwrap() <= 1000); + assert!(is_dynamic("$guid") && !is_dynamic("guid")); } + /// What the history masks: the secrets in force, filled, and only those with a value. #[test] - fn what_a_request_uses_is_listed_once_in_order_resolved_or_not() { - let resolver = Resolver::new(&[layer( - VariableScope::Globals, - "", - vec![variable("baseUrl", "https://x")], - )]); - - let used = resolver.used(&["{{baseUrl}}/{{id}}", "{{id}} {{baseUrl}}"]); + fn the_secrets_in_force_are_those_with_a_value() { + let resolver = Resolver::new(&[ + layer( + VariableScope::Request, + "", + vec![ + secret("token", "{{prefix}}-42"), + secret("empty", ""), + variable("prefix", "tk"), + ], + ), + layer( + VariableScope::Globals, + "", + vec![secret("token", "hidden by the request")], + ), + ]); + assert_eq!( - used.iter() - .map(|known| known.name.as_str()) - .collect::>(), - ["baseUrl", "id"] + resolver.secrets(), + [("token".to_string(), "tk-42".to_string())] ); + } + + /// What the editor lists under a request: each name once, with what it resolves to. + #[test] + fn the_names_a_request_uses_are_listed_once_with_what_they_resolve_to() { + let resolver = resolver(vec![variable("host", "shop.test")]); + + let used = resolver.used(&["{{host}}/{{id}}", "{{$guid}} {{host}}"]); + + let shown: Vec<(&str, Option)> = used + .iter() + .map(|used| { + ( + used.name.as_str(), + used.resolved.as_ref().map(|found| found.scope), + ) + }) + .collect(); assert_eq!( - used[0].resolved.as_ref().map(|found| found.scope), - Some(VariableScope::Globals) + shown, + [ + ("host", Some(VariableScope::Request)), + ("id", None), + ("$guid", Some(VariableScope::Dynamic)), + ] ); - assert!(used[1].resolved.is_none()); } + /// Written back as its name, as typed and as a query encodes it; the longest first, so a + /// value inside another is not cut out of it; too short a value would be found in every word. #[test] - fn a_document_and_what_it_inherits_are_filled_everywhere_a_name_can_stand() { - use super::super::model::KeyPlace; - use super::super::settings::{HttpOrigin, InheritedHeader, inherit}; - - let resolver = Resolver::new(&[layer( - VariableScope::Environment, - "Staging", - vec![ - variable("host", "api.exemple.fr"), - variable("token", "t0k3n"), - variable("id", "42"), - ], - )]); - let row = |key: &str, value: &str| KeyValue { - key: key.to_string(), - value: value.to_string(), - ..KeyValue::default() + fn a_secret_s_value_is_written_back_as_its_name() { + let secrets = [ + ("short".to_string(), "ab".to_string()), + ("pass".to_string(), "p@ss word".to_string()), + ("key".to_string(), "p@ss word and more".to_string()), + ]; + + let hidden = hide("u=p%40ss+word&k=p@ss word and more&ab", &secrets); + + assert_eq!(hidden, "u={{pass}}&k={{key}}&ab"); + } + + fn ones(text: &str) -> String { + text.replace("{{v}}", "1") + } + + /// Every body fills what it sends: a text, each field, each part, a file's path. + #[test] + fn each_body_is_filled_where_a_name_can_stand() { + let resolver = resolver(vec![variable("v", "1")]); + let bodies = |v: &str| { + [ + RequestBody::Json { + text: v.to_string(), + }, + RequestBody::Text { + text: v.to_string(), + }, + RequestBody::Form { + fields: vec![row(v, v)], + }, + RequestBody::Multipart { + parts: vec![part(v, v, true)], + }, + RequestBody::Binary { + path: v.to_string(), + }, + RequestBody::None, + ] }; - let document = RequestDocument { - url: "https://{{host}}/items/{{id}}".to_string(), - params: vec![row("id", "{{id}}")], - headers: vec![row("X-Item-{{id}}", "{{id}}")], - body: RequestBody::Json { - text: r#"{"id":{{id}}}"#.to_string(), - }, - auth: RequestAuth::ApiKey { - name: "key".to_string(), - value: "{{token}}".to_string(), - place: KeyPlace::Header, - }, - ..RequestDocument::default() + + for (body, expected) in bodies("{{v}}").into_iter().zip(bodies(&ones("{{v}}"))) { + let document = RequestDocument { + body, + ..RequestDocument::default() + }; + + let (sent, _) = resolve(&document, &inherit(&[]), &resolver); + + assert_eq!(sent.body, expected); + } + } + + /// The request's own auth and the one it inherits, each filled. + #[test] + fn each_auth_is_filled_own_or_inherited() { + let resolver = resolver(vec![variable("v", "1")]); + let auths = |v: &str| { + [ + RequestAuth::Basic { + username: v.to_string(), + password: v.to_string(), + }, + bearer(v), + RequestAuth::ApiKey { + name: v.to_string(), + value: v.to_string(), + place: KeyPlace::Query, + }, + RequestAuth::None, + ] }; - let mut inherited = inherit(&[]); - inherited.auth = RequestAuth::Bearer { - token: "{{token}}".to_string(), + + for (auth, expected) in auths("{{v}}").into_iter().zip(auths("1")) { + let document = RequestDocument { + auth: auth.clone(), + ..RequestDocument::default() + }; + + let (sent, handed) = resolve(&document, &inherited(row("H", "h"), auth), &resolver); + + assert_eq!((&sent.auth, &handed.auth), (&expected, &expected)); + } + } + + /// The URL, the parameters, the headers, the GraphQL query and its variables, and the + /// headers the request inherits. + #[test] + fn a_request_is_filled_everywhere_else_a_name_can_stand() { + let resolver = resolver(vec![variable("v", "1")]); + let mut document = RequestDocument { + url: "https://{{v}}".to_string(), + params: vec![row("{{v}}", "{{v}}")], + headers: vec![row("{{v}}", "{{v}}")], + ..RequestDocument::default() }; - inherited.headers.push(InheritedHeader { - header: row("X-Host", "{{host}}"), - from: HttpOrigin { - kind: super::super::model::HttpItemKind::Collection, - id: "c".to_string(), - name: "API".to_string(), - }, - }); + document.graphql.query = "{{v}}".to_string(); + document.graphql.variables = "{{v}}".to_string(); + let handed = inherited(row("X-{{v}}", "{{v}}"), RequestAuth::None); - let (document, inherited) = resolve(&document, &inherited, &resolver); + let (sent, handed) = resolve(&document, &handed, &resolver); - assert_eq!(document.url, "https://api.exemple.fr/items/42"); - assert_eq!(document.params[0].value, "42"); - assert_eq!( - ( - document.headers[0].key.as_str(), - document.headers[0].value.as_str() - ), - ("X-Item-42", "42") - ); + assert_eq!(sent.url, "https://1"); assert_eq!( - document.body, - RequestBody::Json { - text: r#"{"id":42}"#.to_string() - } + (sent.params, sent.headers), + (vec![row("1", "1")], vec![row("1", "1")]) ); - assert!(matches!(&document.auth, RequestAuth::ApiKey { value, .. } if value == "t0k3n")); assert_eq!( - inherited.auth, - RequestAuth::Bearer { - token: "t0k3n".to_string() - } + (sent.graphql.query.as_str(), sent.graphql.variables.as_str()), + ("1", "1") ); - assert_eq!(inherited.headers[0].header.value, "api.exemple.fr"); + assert_eq!(handed.headers[0].header, row("X-1", "1")); } + /// What the editor looks for names in: what is sent, and nothing that is not. #[test] - fn a_secret_value_is_written_back_as_its_name_wherever_it_shows() { - let secrets = vec![ - ("token".to_string(), "t0k3n".to_string()), - ("long".to_string(), "t0k3n-and-more".to_string()), - ("spaced".to_string(), "a b&c".to_string()), - ("short".to_string(), "ab".to_string()), - ]; + fn a_request_s_texts_are_those_it_sends() { + let handed = inherited(row("Inh", "i"), bearer("inherited")); + let mut document = RequestDocument { + url: "u".to_string(), + headers: vec![row("Own", "o"), off("Off", "x"), row(" ", "unnamed")], + body: RequestBody::Json { + text: "body".to_string(), + }, + ..RequestDocument::default() + }; + document.graphql.query = "query".to_string(); + document.graphql.variables = "vars".to_string(); + let http = texts(RequestKind::Http, &document, &handed); + let graphql = texts(RequestKind::Graphql, &document, &handed); + let websocket = texts(RequestKind::Websocket, &document, &handed); + + assert_eq!(http, ["u", "Inh", "i", "Own", "o", "inherited", "body"]); assert_eq!( - hide("Bearer t0k3n, again t0k3n-and-more", &secrets), - "Bearer {{token}}, again {{long}}" - ); - assert_eq!( - hide("https://x/?q=a+b%26c", &secrets), - "https://x/?q={{spaced}}" + graphql, + ["u", "Inh", "i", "Own", "o", "inherited", "query", "vars"] ); - assert_eq!(hide("ab cd", &secrets), "ab cd"); - assert_eq!(hide("nothing here", &[]), "nothing here"); + assert_eq!(websocket, ["u", "Inh", "i", "Own", "o", "inherited"]); } + /// Each body and each auth gives the texts it sends: a field or a part switched off none. #[test] - fn the_secrets_in_force_are_named_with_their_values() { - let mut secret = variable("token", "t0k3n"); - secret.kind = VariableKind::Secret; - let mut empty = variable("unset", ""); - empty.kind = VariableKind::Secret; - let resolver = Resolver::new(&[layer( - VariableScope::Globals, - "", - vec![secret, empty, variable("plain", "x")], - )]); + fn each_body_and_auth_gives_the_texts_it_sends() { + let none = inherit(&[]); + let cases: [(RequestBody, RequestAuth, &[&str]); 6] = [ + ( + RequestBody::Text { + text: "t".to_string(), + }, + RequestAuth::None, + &["t"], + ), + ( + RequestBody::Form { + fields: vec![row("k", "v"), off("x", "y")], + }, + RequestAuth::Basic { + username: "u".to_string(), + password: "p".to_string(), + }, + &["u", "p", "k", "v"], + ), + ( + RequestBody::Multipart { + parts: vec![part("k", "v", true), part("x", "y", false)], + }, + RequestAuth::ApiKey { + name: "n".to_string(), + value: "a".to_string(), + place: KeyPlace::Header, + }, + &["n", "a", "k", "v"], + ), + ( + RequestBody::Binary { + path: "f".to_string(), + }, + bearer("b"), + &["b", "f"], + ), + (RequestBody::None, RequestAuth::Inherit, &[]), + (RequestBody::None, RequestAuth::None, &[]), + ]; + for (body, auth, expected) in cases { + let document = RequestDocument { + body, + auth, + ..RequestDocument::default() + }; - assert_eq!( - resolver.secrets(), - [("token".to_string(), "t0k3n".to_string())] - ); + let found = texts(RequestKind::Http, &document, &none); + + assert_eq!(&found[1..], expected, "{:?}", document.body); + } } } From ccfa978877194aa6f8efdbf546926cdf716eb1a2 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:01:24 +0100 Subject: [PATCH 32/95] Recovery: unit tests rewritten for setting a library aside (#1755) * Rewrite the tests of setting a library aside, durable writes and the names on disk Co-Authored-By: Claude Opus 5.5 * The recovery services' tests leave the profile tests Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/durable.rs | 59 ++--- crates/engine/src/layout.rs | 50 ++++- crates/engine/src/recovery.rs | 273 +++++++++-------------- crates/engine/tests/commands/main.rs | 1 + crates/engine/tests/commands/profile.rs | 19 +- crates/engine/tests/commands/recovery.rs | 78 +++++++ 6 files changed, 254 insertions(+), 226 deletions(-) create mode 100644 crates/engine/tests/commands/recovery.rs diff --git a/crates/engine/src/durable.rs b/crates/engine/src/durable.rs index bf889978a..6a71b6e9a 100644 --- a/crates/engine/src/durable.rs +++ b/crates/engine/src/durable.rs @@ -59,7 +59,7 @@ fn sync_folder(path: &Path) -> io::Result<()> { mod tests { use super::*; - fn names(folder: &Path) -> Vec { + fn names_in(folder: &Path) -> Vec { let mut names: Vec = std::fs::read_dir(folder) .unwrap() .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) @@ -68,43 +68,48 @@ mod tests { names } + /// The new bytes in the old file's place, and nothing staged left beside it. #[test] - fn a_file_is_replaced_whole_and_nothing_is_left_beside_it() { - let folder = tempfile::tempdir().unwrap(); - let path = folder.path().join("vault.json"); + fn a_file_written_takes_the_old_one_s_place_whole() { + let scratch = tempfile::tempdir().unwrap(); + let path = scratch.path().join("libraries.json"); std::fs::write(&path, b"old").unwrap(); write(&path, b"new").unwrap(); assert_eq!(std::fs::read(&path).unwrap(), b"new"); - assert_eq!(names(folder.path()), ["vault.json"]); + assert_eq!(names_in(scratch.path()), ["libraries.json"]); } #[test] - fn a_failed_rename_leaves_no_staged_file() { - let folder = tempfile::tempdir().unwrap(); - let taken = folder.path().join("registry.json"); - std::fs::create_dir(&taken).unwrap(); - std::fs::write(taken.join("inside"), b"x").unwrap(); - let source = folder.path().join("source"); - std::fs::write(&source, b"copied").unwrap(); - - assert!(write(&taken, b"new").is_err()); - assert!(copy(&source, &taken).is_err()); - - assert_eq!(names(folder.path()), ["registry.json", "source"]); - } + fn a_file_copied_takes_the_old_one_s_place_and_leaves_its_source() { + let scratch = tempfile::tempdir().unwrap(); + let (from, to) = (scratch.path().join("from"), scratch.path().join("to")); + std::fs::write(&from, b"bytes").unwrap(); + std::fs::write(&to, b"old").unwrap(); - #[test] - fn a_copy_takes_the_place_of_the_file() { - let folder = tempfile::tempdir().unwrap(); - let source = folder.path().join("library.db"); - let target = folder.path().join("restored.db"); - std::fs::write(&source, b"pages").unwrap(); + copy(&from, &to).unwrap(); - copy(&source, &target).unwrap(); + assert_eq!(std::fs::read(&to).unwrap(), b"bytes"); + assert_eq!(std::fs::read(&from).unwrap(), b"bytes"); + assert_eq!(names_in(scratch.path()), ["from", "to"]); + } - assert_eq!(std::fs::read(&target).unwrap(), b"pages"); - assert_eq!(names(folder.path()), ["library.db", "restored.db"]); + /// A staged file left behind is a stray copy of what was being written — a key file, an + /// export — beside the person's own files. + #[test] + fn nothing_staged_is_left_when_a_write_or_a_copy_fails() { + let scratch = tempfile::tempdir().unwrap(); + let occupied = scratch.path().join("occupied"); + std::fs::create_dir_all(occupied.join("inside")).unwrap(); + let source = scratch.path().join("source"); + std::fs::write(&source, b"bytes").unwrap(); + + let written = write(&occupied, b"bytes"); + let copied = copy(&source, &occupied); + let from_nothing = copy(&scratch.path().join("missing"), &scratch.path().join("to")); + + assert!(written.is_err() && copied.is_err() && from_nothing.is_err()); + assert_eq!(names_in(scratch.path()), ["occupied", "source"]); } } diff --git a/crates/engine/src/layout.rs b/crates/engine/src/layout.rs index 45c1a666e..fdfae3b9f 100644 --- a/crates/engine/src/layout.rs +++ b/crates/engine/src/layout.rs @@ -79,20 +79,52 @@ pub(crate) fn parse_stamp(name: &str) -> Option> { mod tests { use super::*; + /// ⚠️ Each name is where an installed copy looks: spelled out here, a rename fails a test + /// before it sends anyone's application looking for files under a new name. #[test] - fn the_sidecars_are_named_after_the_database() { - assert_eq!( - DATABASE_SIDECARS, - ["devnotes.sqlite3-wal", "devnotes.sqlite3-shm"] - ); + fn every_name_on_disk_is_spelled_as_installed_copies_wrote_it() { + let names = [ + (DATABASE, "devnotes.sqlite3"), + (DATABASE_SIDECARS[0], "devnotes.sqlite3-wal"), + (DATABASE_SIDECARS[1], "devnotes.sqlite3-shm"), + (KEY_FILE, "vault.json"), + (ATTACHMENTS, "attachments"), + (BACKUPS, "backups"), + (DAMAGED, "damaged"), + (ARCHIVED, "archived"), + (REPLACED, "replaced"), + (PREFERENCES, "preferences.json"), + (REGISTRY, "libraries.json"), + (LIBRARIES, "libraries"), + (PLAINTEXT_COPIES, "open"), + ]; + + for (name, installed) in names { + assert_eq!(name, installed); + } } + /// A copy or a library set aside is named by it: no colon, which a Windows path refuses, + /// and read back to the second. #[test] - fn a_stamp_reads_back_as_the_instant_it_was_written_from() { - let at = crate::db::iso8601::parse("2026-07-25T09:12:34.000Z").unwrap(); + fn a_stamp_names_a_folder_on_every_system_and_reads_back() { + let at = crate::db::iso8601::parse("2026-07-25T09:05:07.000Z").unwrap(); - assert_eq!(stamp(at), "2026-07-25_09-12-34"); + assert_eq!(stamp(at), "2026-07-25_09-05-07"); assert_eq!(parse_stamp(&stamp(at)), Some(at)); - assert_eq!(parse_stamp("not a stamp"), None); + } + + /// A folder that is not a stamp is never taken for a copy. + #[test] + fn a_name_that_is_not_a_stamp_reads_as_none() { + for name in [ + "notes", + "2026-07-25", + "2026-07-25 09:05:07", + "../2026-07-25_09-05-07", + "", + ] { + assert_eq!(parse_stamp(name), None, "{name}"); + } } } diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index 754391300..01f56a2c5 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -130,210 +130,137 @@ pub fn archive_locked_library(engine: &Engine) -> Result { #[cfg(test)] mod tests { use super::*; - use crate::db; + use crate::notes::model::{NoteDraft, NoteLifecycle}; + use crate::notes::store as notes; + use crate::spaces::store as spaces; + use crate::vault::file; + use crate::vault::key::Cost; - #[test] - fn nothing_is_set_aside_under_an_open_library() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - std::fs::write(directory.join(DATABASE), b"a library").unwrap(); - let db: Db = std::sync::Mutex::new(Some(db::open_in_memory().unwrap())); + const PHRASE: &str = "a passphrase"; - let refused = set_aside_closed(&directory, &db, Reason::Forgotten); - - assert!(refused.is_err()); - assert!(directory.join(DATABASE).exists()); + fn now() -> DateTime { + crate::db::iso8601::parse("2026-07-25T09:00:00.000Z").unwrap() } - #[test] - fn a_closed_library_is_set_aside_and_the_answer_says_where() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - std::fs::write(directory.join(DATABASE), b"a sealed library").unwrap(); - std::fs::write(directory.join(KEY_FILE), b"its key").unwrap(); - let db: Db = std::sync::Mutex::new(None); - - let target = set_aside_closed(&directory, &db, Reason::Forgotten).unwrap(); - - assert!(Path::new(&target).join(DATABASE).exists()); - assert!(!directory.join(DATABASE).exists()); - } - - fn at() -> DateTime { - db::iso8601::parse("2026-07-25T09:00:00.000Z").unwrap() - } - - /// A library as one really sits on disk: a database, its key file, and a picture. - fn library(directory: &Path) -> String { - let vault = crate::vault::file::create( - directory, - "a passphrase", - crate::vault::key::Cost::FOR_TESTS, - ) - .unwrap(); - - let mut connection = db::open(&directory.join(DATABASE), vault).unwrap(); - let space = crate::spaces::store::create(&mut connection, "Perso") - .unwrap() - .id; - + /// A closed library as a real one is: one note, its key file, one attachment. + fn library(directory: &Path) { + let vault = file::create(directory, PHRASE, Cost::FOR_TESTS).unwrap(); + let mut connection = crate::db::open(&directory.join(DATABASE), vault).unwrap(); + let space = spaces::create(&mut connection, "Work").unwrap().id; + let draft = NoteDraft { + space_id: space, + folder_id: None, + title: "Kept".to_string(), + language: crate::notes::language::Language::Txt, + content: "psql -h prod".to_string(), + source: String::new(), + tags: Vec::new(), + pinned: false, + lifecycle: NoteLifecycle::Permanent, + kind: crate::notes::kind::NoteKind::Snippet, + priority: crate::notes::priority::Priority::None, + items: Vec::new(), + }; + notes::create(&mut connection, draft, now()).unwrap(); std::fs::create_dir_all(directory.join(ATTACHMENTS)).unwrap(); - std::fs::write(directory.join(ATTACHMENTS).join("a-1.png"), b"\x89PNG").unwrap(); - - space + std::fs::write(directory.join(ATTACHMENTS).join("a-1.png"), b"png").unwrap(); } + /// ⚠️ The key file is the reason's to decide, and the two answers are opposite: a damaged + /// file leaves it for the fresh library its phrase still opens, a forgotten phrase takes + /// it, the only thing that phrase would open again. The attachments go either way: a fresh + /// library would sweep them as orphans. Nothing of the old database stays for the fresh + /// one to read: its sidecars travel, or the rescue has already read them in. #[test] - fn the_database_leaves_and_the_directory_is_ready_for_a_new_one() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - library(&directory); - - let target = set_aside(&directory, Reason::Damaged, at()).unwrap(); - - assert!(!directory.join(DATABASE).exists()); - assert!(target.join(DATABASE).is_file()); - } - - /// Or the next launch's orphan sweep deletes the pictures of the notes just set aside. - #[test] - fn the_attachments_go_with_the_database_they_belong_to() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - library(&directory); - - let target = set_aside(&directory, Reason::Damaged, at()).unwrap(); - - assert!(!directory.join(ATTACHMENTS).exists()); - assert!(target.join(ATTACHMENTS).join("a-1.png").is_file()); + fn a_library_is_set_aside_under_its_reason_with_the_key_file_its_reason_decides() { + for (reason, folder, key_travels) in [ + (Reason::Damaged, DAMAGED, false), + (Reason::Forgotten, ARCHIVED, true), + ] { + let scratch = tempfile::tempdir().unwrap(); + let directory = scratch.path(); + library(directory); + for sidecar in DATABASE_SIDECARS { + std::fs::write(directory.join(sidecar), b"").unwrap(); + } + + let target = set_aside(directory, reason, now()).unwrap(); + + assert_eq!(target, directory.join(folder).join(layout::stamp(now()))); + for name in [DATABASE, ATTACHMENTS] { + assert!(target.join(name).exists(), "{reason:?}: {name} stayed"); + } + for name in DATABASE_SIDECARS.iter().chain(&[DATABASE, ATTACHMENTS]) { + assert!( + !directory.join(name).exists(), + "{reason:?}: {name} left behind" + ); + } + assert_eq!(target.join(KEY_FILE).exists(), key_travels, "{reason:?}"); + assert_eq!( + directory.join(KEY_FILE).exists(), + !key_travels, + "{reason:?}" + ); + } } - /// The rescued copy needs that exact key. + /// Damaged, what SQLite can still read is copied out beside the original, and opens under + /// the phrase that stays; a forgotten phrase rescues nothing, the file being sealed. #[test] - fn the_key_file_stays_where_it_was() { + fn a_damaged_library_leaves_a_rescued_copy_that_opens_under_its_key() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - library(&directory); + library(scratch.path()); + let forgotten = tempfile::tempdir().unwrap(); + library(forgotten.path()); - set_aside(&directory, Reason::Damaged, at()).unwrap(); + let damaged = set_aside(scratch.path(), Reason::Damaged, now()).unwrap(); + let archived = set_aside(forgotten.path(), Reason::Forgotten, now()).unwrap(); - assert!(directory.join(KEY_FILE).is_file()); + let vault = file::unlock(scratch.path(), PHRASE).unwrap(); + let mut rescued = crate::db::open(&damaged.join(RESCUED), vault).unwrap(); + assert_eq!(notes::count_live(&mut rescued).unwrap(), 1); + assert!(!archived.join(RESCUED).exists()); } + /// The notes leave sealed under the forgotten phrase, with the one key file it opens. #[test] - fn what_could_be_read_is_rescued_beside_it() { + fn a_library_archived_opens_on_the_day_its_phrase_comes_back() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let space = library(&directory); - - let target = set_aside(&directory, Reason::Damaged, at()).unwrap(); + library(scratch.path()); - let vault = crate::vault::file::unlock(&directory, "a passphrase").unwrap(); - let mut rescued = db::open(&target.join(RESCUED), vault).unwrap(); - let spaces = crate::spaces::store::list(&mut rescued).unwrap(); + let archived = set_aside(scratch.path(), Reason::Forgotten, now()).unwrap(); - assert_eq!(spaces.len(), 1); - assert_eq!(spaces[0].id, space); + let vault = file::unlock(&archived, PHRASE).unwrap(); + let mut found = crate::db::open(&archived.join(DATABASE), vault).unwrap(); + assert_eq!(notes::count_live(&mut found).unwrap(), 1); } + /// Best effort: a file SQLite cannot read at all is still set aside. #[test] - fn a_fresh_library_opens_in_its_place() { + fn a_file_nothing_can_be_rescued_from_is_set_aside_all_the_same() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - library(&directory); - set_aside(&directory, Reason::Damaged, at()).unwrap(); + std::fs::write(scratch.path().join(DATABASE), b"not a database").unwrap(); - let vault = crate::vault::file::unlock(&directory, "a passphrase").unwrap(); - let mut fresh = db::open(&directory.join(DATABASE), vault).unwrap(); + let target = set_aside(scratch.path(), Reason::Damaged, now()).unwrap(); - assert!(crate::spaces::store::list(&mut fresh).unwrap().is_empty()); + assert_eq!( + std::fs::read(target.join(DATABASE)).unwrap(), + b"not a database" + ); + assert!(!target.join(RESCUED).exists()); + assert!(!scratch.path().join(DATABASE).exists()); } #[test] - fn setting_aside_nothing_says_so_rather_than_pretending() { + fn a_folder_without_a_database_has_nothing_to_set_aside() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); + std::fs::write(scratch.path().join(KEY_FILE), b"{}").unwrap(); - assert!(set_aside(&directory, Reason::Damaged, at()).is_err()); - } - mod a_forgotten_passphrase { - use super::*; - - /// The phrase would only ever open this file again. - #[test] - fn the_key_file_goes_with_the_library_it_seals() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - library(&directory); + let refused = set_aside(scratch.path(), Reason::Forgotten, now()); - let target = set_aside(&directory, Reason::Forgotten, at()).unwrap(); - - assert!(target.join(KEY_FILE).is_file()); - assert!(!directory.join(KEY_FILE).exists()); - } - - /// With no key file left, the gate asks for a new phrase. - #[test] - fn what_is_left_behind_is_a_directory_with_no_library_in_it() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - library(&directory); - - set_aside(&directory, Reason::Forgotten, at()).unwrap(); - - assert!(!directory.join(DATABASE).exists()); - assert!(!directory.join(KEY_FILE).exists()); - } - - #[test] - fn the_archived_copy_still_opens_on_the_day_the_phrase_comes_back() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let space = library(&directory); - - let target = set_aside(&directory, Reason::Forgotten, at()).unwrap(); - - let vault = crate::vault::file::unlock(&target, "a passphrase").unwrap(); - let mut archived = db::open(&target.join(DATABASE), vault).unwrap(); - let spaces = crate::spaces::store::list(&mut archived).unwrap(); - - assert_eq!(spaces.len(), 1); - assert_eq!(spaces[0].id, space); - } - - /// Sealed: SQLite hands over nothing without the key. - #[test] - fn nothing_is_rescued_beside_it() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - library(&directory); - - let target = set_aside(&directory, Reason::Forgotten, at()).unwrap(); - - assert!(!target.join(RESCUED).exists()); - } - - #[test] - fn it_is_filed_apart_from_a_damaged_one() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - library(&directory); - - let target = set_aside(&directory, Reason::Forgotten, at()).unwrap(); - - assert!(target.starts_with(directory.join(ARCHIVED))); - assert!(!directory.join(DAMAGED).exists()); - } - - #[test] - fn the_attachments_go_with_it_too() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - library(&directory); - - let target = set_aside(&directory, Reason::Forgotten, at()).unwrap(); - - assert!(target.join(ATTACHMENTS).join("a-1.png").is_file()); - } + assert!(matches!(refused, Err(StorageError::NothingToSetAside(_)))); + assert!(!scratch.path().join(ARCHIVED).exists()); + assert!(scratch.path().join(KEY_FILE).is_file()); } } diff --git a/crates/engine/tests/commands/main.rs b/crates/engine/tests/commands/main.rs index 328de16dd..7016769f0 100644 --- a/crates/engine/tests/commands/main.rs +++ b/crates/engine/tests/commands/main.rs @@ -30,6 +30,7 @@ mod http_send; mod index; mod notes; mod profile; +mod recovery; mod spaces; mod transfer; mod websocket; diff --git a/crates/engine/tests/commands/profile.rs b/crates/engine/tests/commands/profile.rs index 7a18c0b02..b09f5ad6a 100644 --- a/crates/engine/tests/commands/profile.rs +++ b/crates/engine/tests/commands/profile.rs @@ -1,12 +1,11 @@ -//! What reaches the profile the engine was given: the registry of libraries, the gate's state, -//! the recovery commands; and the identity tool, which reads nothing there. +//! What reaches the profile the engine was given: the registry of libraries and the gate's +//! state; and the identity tool, which reads nothing there. use engine::error::ErrorCode; use engine::libraries::{ create_library, delete_library, list_libraries, open_library, open_library_directory, rename_library, }; -use engine::recovery::{archive_locked_library, set_aside_damaged_library}; use engine::spaces::list_spaces; use engine::tools::generate_identity; use engine::tools::identity::{Country, IdentityRequest}; @@ -97,20 +96,6 @@ fn the_open_library_s_folder_is_where_its_database_is() { assert_eq!(directory, scratch.path()); } -#[test] -fn an_open_library_is_never_set_aside() { - let session = Session::open(); - - assert!(matches!( - code(session.call(set_aside_damaged_library)), - ErrorCode::LibraryOpen - )); - assert!(matches!( - code(session.call(archive_locked_library)), - ErrorCode::LibraryOpen - )); -} - /// The lists are compiled in: a profile with no folder of lists beside it, as the standalone /// executable runs, draws a person in every country. #[test] diff --git a/crates/engine/tests/commands/recovery.rs b/crates/engine/tests/commands/recovery.rs new file mode 100644 index 000000000..9f390f445 --- /dev/null +++ b/crates/engine/tests/commands/recovery.rs @@ -0,0 +1,78 @@ +use std::path::{Path, PathBuf}; + +use engine::error::ErrorCode; +use engine::libraries::open_library_directory; +use engine::recovery::{archive_locked_library, set_aside_damaged_library}; +use engine::vault::{VaultState, create_vault, secret, unlock_vault, vault_state}; + +use super::{Session, code}; + +const PHRASE: &str = "correct horse battery staple"; + +/// A library created at the gate, then closed with the process: where it lives. +fn closed_library(session: &Session) -> PathBuf { + session.engine.keep_launch_copies(false); + session + .call(|e| create_vault(e, secret(PHRASE.to_owned()))) + .unwrap(); + let directory = session.call(open_library_directory).unwrap(); + *session.engine.db().lock().unwrap() = None; + + directory +} + +/// ⚠️ Moving a database under a live connection loses it. +#[test] +fn an_open_library_is_never_set_aside() { + let session = Session::open(); + + assert_eq!( + code(session.call(set_aside_damaged_library)), + ErrorCode::LibraryOpen + ); + assert_eq!( + code(session.call(archive_locked_library)), + ErrorCode::LibraryOpen + ); +} + +/// Damaged, the phrase still works: the gate asks for it, and opens a fresh library under it. +#[test] +fn a_damaged_library_set_aside_leaves_the_gate_asking_for_the_same_phrase() { + let session = Session::locked(); + let directory = closed_library(&session); + + let aside = session.call(set_aside_damaged_library).unwrap(); + + assert!(Path::new(&aside).starts_with(directory.join("damaged"))); + assert_eq!(session.call(vault_state).unwrap(), VaultState::Locked); + session + .call(|e| unlock_vault(e, secret(PHRASE.to_owned()))) + .unwrap(); +} + +/// Forgotten, the key file leaves with the notes: the gate starts a fresh library on a new +/// phrase. +#[test] +fn a_forgotten_library_archived_leaves_the_gate_asking_for_a_new_phrase() { + let session = Session::locked(); + let directory = closed_library(&session); + + let aside = session.call(archive_locked_library).unwrap(); + + assert!(Path::new(&aside).starts_with(directory.join("archived"))); + assert_eq!(session.call(vault_state).unwrap(), VaultState::Absent); + session + .call(|e| create_vault(e, secret("another long passphrase".to_owned()))) + .unwrap(); +} + +#[test] +fn a_library_never_created_has_nothing_to_set_aside() { + let session = Session::locked(); + + assert_eq!( + code(session.call(set_aside_damaged_library)), + ErrorCode::NothingToSetAside + ); +} From ff69c27ba2f60c5e0c704f8b33dd248cb045b728 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:53:06 +0100 Subject: [PATCH 33/95] HTTP requests: unit tests rewritten for bodies, headers and settings (#1754) * Rewrite the tests of HTTP requests: methods, bodies, headers, the query, inheritance and transport Co-Authored-By: Claude Opus 5.5 * A collection's cookie setting reaches a request that sets none Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/http/model.rs | 370 +++++++++++++++------------- crates/engine/src/http/query.rs | 103 ++++---- crates/engine/src/http/settings.rs | 297 ++++++++++++++-------- crates/engine/src/http/transport.rs | 73 ++++-- 4 files changed, 508 insertions(+), 335 deletions(-) diff --git a/crates/engine/src/http/model.rs b/crates/engine/src/http/model.rs index 721f863d1..449145959 100644 --- a/crates/engine/src/http/model.rs +++ b/crates/engine/src/http/model.rs @@ -483,17 +483,33 @@ pub fn validated_name(raw: &str) -> Result { mod tests { use super::*; - #[test] - fn a_file_part_takes_the_type_of_its_extension() { - assert_eq!(part_type("image-test.PNG"), "image/png"); - assert_eq!(part_type("index.html"), "text/html"); - assert_eq!(part_type("data.json"), "application/json"); - assert_eq!(part_type("archive.tar.gz"), "application/gzip"); - assert_eq!(part_type("Makefile"), "application/octet-stream"); + fn row(key: &str, value: &str) -> KeyValue { + KeyValue { + key: key.to_string(), + value: value.to_string(), + ..KeyValue::default() + } + } + + fn part(key: &str, value: &str, file: bool, enabled: bool) -> FormPart { + FormPart { + enabled, + key: key.to_string(), + value: value.to_string(), + file, + ..FormPart::default() + } + } + + fn json(text: &str) -> RequestBody { + RequestBody::Json { + text: text.to_string(), + } } + /// Stored as written: a method or a kind reads back from its spelling. #[test] - fn every_method_and_kind_survives_its_stored_spelling() { + fn every_method_and_kind_reads_back_from_its_spelling() { for method in HttpMethod::ALL { assert_eq!(method.as_str().parse::(), Ok(method)); } @@ -502,44 +518,134 @@ mod tests { } } - /// Key `X-Recette: 1`, value `rsgfdregr`: accepted, then every request failed on its URL. + /// `GET` and `HEAD` seldom carry a body; what changes nothing is what a protected + /// environment lets leave without asking. #[test] - fn a_header_name_is_a_token_and_a_value_holds_no_control_character() { - for name in ["X-Recette", "accept", "X_a.b~c!#$%&'*+^`|", " Trimmed "] { - assert_eq!(header_fault(name, "v"), None, "{name}"); - } - for name in [ - "X-Recette: 1", - "X Recette", - "Clé", - "", - "a\tb", - "a(b)", - "a\"b", - "a/b", - "a@b", + fn each_method_says_whether_it_carries_a_body_and_changes_anything() { + use HttpMethod::{Delete, Get, Head, Options, Patch, Post, Put}; + for (method, seldom_a_body, changes_nothing) in [ + (Get, true, true), + (Head, true, true), + (Options, false, true), + (Post, false, false), + (Put, false, false), + (Patch, false, false), + (Delete, false, false), ] { - assert_eq!(header_fault(name, "v"), Some(HeaderFault::Name), "{name}"); + assert_eq!(method.seldom_carries_a_body(), seldom_a_body, "{method:?}"); + assert_eq!(method.changes_nothing(), changes_nothing, "{method:?}"); } - for value in [ - "", - "application/json; charset=utf-8", - "Équipe/1", - "a\tb", - " padded ", + } + + /// The files a send reads: a binary body's, and each file part that leaves. + #[test] + fn a_body_names_the_files_the_send_reads() { + let multipart = RequestBody::Multipart { + parts: vec![ + part("avatar", "/a.png", true, true), + part("off", "/off.png", true, false), + part(" ", "/unnamed.png", true, true), + part("name", "Ada", false, true), + ], + }; + let binary = RequestBody::Binary { + path: "/dump.bin".to_string(), + }; + + assert_eq!(multipart.files(), ["/a.png"]); + assert_eq!(binary.files(), ["/dump.bin"]); + assert!(json("{}").files().is_empty()); + } + + /// A kind chosen and left empty sends none. + #[test] + fn a_body_carries_something_only_once_filled() { + let named = || vec![row("q", "1")]; + let off = || { + vec![KeyValue { + enabled: false, + ..row("q", "1") + }] + }; + for (body, carries) in [ + (RequestBody::None, false), + (json(""), false), + (json("{}"), true), + ( + RequestBody::Text { + text: "t".to_string(), + }, + true, + ), + (RequestBody::Form { fields: named() }, true), + (RequestBody::Form { fields: off() }, false), + ( + RequestBody::Form { + fields: vec![row(" ", "1")], + }, + false, + ), + ( + RequestBody::Multipart { + parts: vec![part("a", "", false, true)], + }, + true, + ), + ( + RequestBody::Multipart { + parts: vec![part("a", "", false, false)], + }, + false, + ), + ( + RequestBody::Binary { + path: " ".to_string(), + }, + false, + ), + ( + RequestBody::Binary { + path: "/f".to_string(), + }, + true, + ), ] { - assert_eq!(header_fault("X-A", value), None, "{value:?}"); + assert_eq!(body.carries_something(), carries, "{body:?}"); } - for value in ["a\nb", "a\r\nX-Injected: 1", "bell\u{7}", "del\u{7f}"] { - assert_eq!( - header_fault("X-A", value), - Some(HeaderFault::Value), - "{value:?}" - ); + } + + /// Sent as typed whatever the method; the editor only says it. + #[test] + fn a_body_is_unusual_only_when_filled_on_a_get_or_a_head() { + assert!(json("{}").is_unusual_on(HttpMethod::Get)); + assert!(json("{}").is_unusual_on(HttpMethod::Head)); + assert!(!json("{}").is_unusual_on(HttpMethod::Post)); + assert!(!json("").is_unusual_on(HttpMethod::Get)); + } + + /// A name is an HTTP token — no space, no colon, no accent —, a `{{name}}` standing for a + /// letter; a value holds no line break nor control character but a tab. + #[test] + fn a_header_is_sent_only_with_a_token_for_a_name_and_a_value_without_a_break() { + for (name, value, fault) in [ + ("X-Request-Id", "abc", None), + (" Accept ", "a\tb", None), + ("X-{{tenant}}-Id", "x", None), + ("!#$%&'*+-.^_`|~", "x", None), + ("", "x", Some(HeaderFault::Name)), + ("X Id", "x", Some(HeaderFault::Name)), + ("Accept: json", "", Some(HeaderFault::Name)), + ("Clé", "x", Some(HeaderFault::Name)), + ("{{user.name}}", "x", Some(HeaderFault::Name)), + ("X-Id", "a\nb", Some(HeaderFault::Value)), + ("X-Id", "a\u{7}b", Some(HeaderFault::Value)), + ] { + assert_eq!(header_fault(name, value), fault, "{name:?}: {value:?}"); } } - /// The rule is what the client can build: it must not refuse more, nor let through more. + /// Key `X-Recette: 1` was accepted, then every request failed on it: the rule is what the + /// client can build, refusing no more and letting through no more. #[test] fn the_rule_agrees_with_what_the_client_builds() { use reqwest::header::{HeaderName, HeaderValue}; @@ -576,151 +682,85 @@ mod tests { } } + /// Every field defaults: one added later needs no migration, and a document written by an + /// older version still opens. #[test] - fn a_variable_in_a_header_stands_for_a_letter_until_it_is_filled() { - assert_eq!(header_fault("X-{{tenant}}-Id", "{{token}}"), None); - assert_eq!(header_fault("{{name}}", ""), None); - // Not a variable: a dotted path is text, as everywhere else. - assert_eq!(header_fault("{{user.name}}", ""), Some(HeaderFault::Name)); - assert_eq!(header_fault("X {{tenant}}", ""), Some(HeaderFault::Name)); - } - - #[test] - fn a_row_switched_off_or_without_a_name_is_not_judged() { - let row = |enabled: bool, key: &str, value: &str| KeyValue { - enabled, - key: key.to_string(), - value: value.to_string(), - ..KeyValue::default() - }; + fn a_document_written_before_a_field_existed_still_opens() { + let document: RequestDocument = + serde_json::from_str(r#"{"url":"https://exemple.fr"}"#).unwrap(); + assert_eq!(document.url, "https://exemple.fr"); + assert_eq!(document.description, ""); assert_eq!( - header_faults(&[ - row(true, "Accept", "*/*"), - row(true, "X Recette", "1"), - row(false, "X Recette", "1"), - row(true, " ", "orphan"), - row(true, "X-A", "a\nb"), - ]), - vec![ - None, - Some(HeaderFault::Name), - None, - None, - Some(HeaderFault::Value) - ] + serde_json::from_str::(r#"{"later":1}"#).unwrap(), + RequestDocument::default() ); } + /// Not sent, not judged. #[test] - fn header_lines_are_read_as_rows_at_their_first_colon() { - let read = |text: &str| -> Vec<(String, String)> { - headers_from_text(text) - .into_iter() - .map(|row| { - assert!(row.enabled); - (row.key, row.value) - }) - .collect() - }; - let pair = |key: &str, value: &str| (key.to_string(), value.to_string()); + fn a_header_switched_off_or_unnamed_is_not_judged() { + let rows = [ + row("X Id", "x"), + KeyValue { + enabled: false, + ..row("X Id", "x") + }, + row(" ", "a\nb"), + ]; - assert_eq!(read("X-Recette: 1"), vec![pair("X-Recette", "1")]); - assert_eq!(read("X-Recette:"), vec![pair("X-Recette", "")]); - assert_eq!( - read("Referer: https://exemple.fr:8443/a"), - vec![pair("Referer", "https://exemple.fr:8443/a")] - ); - // As a browser's network tab copies them: a request line, pseudo-headers, blank lines. - assert_eq!( - read( - "GET /events HTTP/2\r\n:authority: api.exemple.fr\r\naccept: */*\r\n\r\n x-client : web \n" - ), - vec![pair("accept", "*/*"), pair("x-client", "web")] - ); - assert_eq!(read("no colon here"), Vec::new()); + assert_eq!(header_faults(&rows), [Some(HeaderFault::Name), None, None]); } - /// A `POST` switched to `GET` kept its body and sent it, and nothing said so. + /// A line copied from a network tab: what follows the first colon is the value; a line + /// without one is no header, and a pseudo-header is the client's to write. #[test] - fn a_body_is_unusual_on_a_get_and_a_head_and_on_no_other_method() { - let json = RequestBody::Json { - text: "{\"a\":1}".to_string(), - }; - let warned: Vec = HttpMethod::ALL - .into_iter() - .filter(|method| json.is_unusual_on(*method)) - .collect(); - assert_eq!(warned, vec![HttpMethod::Get, HttpMethod::Head]); + fn header_lines_become_rows_split_at_their_first_colon() { + let rows = headers_from_text( + "Accept: application/json\n Referer : https://shop.test/a \nno colon\n:authority: shop.test\n", + ); - for method in HttpMethod::ALL { - assert!(!RequestBody::None.is_unusual_on(method)); - } + assert_eq!( + rows, + [ + row("Accept", "application/json"), + row("Referer", "https://shop.test/a"), + ] + ); } + /// The web's own files by their extension, whatever its case; what an attachment knows + /// otherwise; a stream of bytes for the rest. #[test] - fn a_kind_chosen_and_left_empty_is_no_body() { - let row = |enabled: bool, key: &str| KeyValue { - enabled, - key: key.to_string(), - ..KeyValue::default() - }; - let part = |enabled: bool, key: &str| FormPart { - enabled, - key: key.to_string(), - ..FormPart::default() - }; - let empty = [ - RequestBody::None, - RequestBody::Json { - text: String::new(), - }, - RequestBody::Text { - text: String::new(), - }, - RequestBody::Form { - fields: vec![row(false, "q"), row(true, " ")], - }, - RequestBody::Multipart { - parts: vec![part(false, "file"), part(true, "")], - }, - RequestBody::Binary { - path: " ".to_string(), - }, - ]; - for body in &empty { - assert!(!body.carries_something(), "{body:?}"); - } - - let filled = [ - RequestBody::Text { - text: " ".to_string(), - }, - RequestBody::Form { - fields: vec![row(true, "q")], - }, - RequestBody::Multipart { - parts: vec![part(true, "file")], - }, - RequestBody::Binary { - path: "C:/tmp/a.bin".to_string(), - }, - ]; - for body in &filled { - assert!(body.is_unusual_on(HttpMethod::Get), "{body:?}"); + fn a_file_part_is_typed_by_its_extension() { + for (name, typed) in [ + ("index.HTML", "text/html"), + ("page.htm", "text/html"), + ("feed.xml", "application/xml"), + ("site.css", "text/css"), + ("app.mjs", "text/javascript"), + ("app.js", "text/javascript"), + ("ci.yml", "application/yaml"), + ("ci.yaml", "application/yaml"), + ("photo.avif", "image/avif"), + ("favicon.ico", "image/vnd.microsoft.icon"), + ("song.mp3", "audio/mpeg"), + ("ring.wav", "audio/wav"), + ("clip.mp4", "video/mp4"), + ("clip.webm", "video/webm"), + ("dump.gz", "application/gzip"), + ("dump.tar", "application/x-tar"), + ("photo.png", "image/png"), + ("data.unknown", "application/octet-stream"), + ("Makefile", "application/octet-stream"), + ] { + assert_eq!(part_type(name), typed, "{name}"); } } #[test] - fn a_document_written_before_a_field_existed_still_opens() { - let document: RequestDocument = - serde_json::from_str(r#"{"url":"https://exemple.fr"}"#).unwrap(); - - assert_eq!(document.url, "https://exemple.fr"); - assert_eq!(document.description, ""); - assert_eq!( - serde_json::from_str::(r#"{"later":1}"#).unwrap(), - RequestDocument::default() - ); + fn a_collection_folder_or_request_is_named_readably() { + assert_eq!(validated_name(" Orders ").unwrap(), "Orders"); + assert!(validated_name(" ").is_err()); } } diff --git a/crates/engine/src/http/query.rs b/crates/engine/src/http/query.rs index c3f1e55ea..f728fdca2 100644 --- a/crates/engine/src/http/query.rs +++ b/crates/engine/src/http/query.rs @@ -97,79 +97,96 @@ fn url_with_params(url: &str, params: &[KeyValue]) -> String { mod tests { use super::*; - fn row(enabled: bool, key: &str, value: &str, description: &str) -> KeyValue { + fn row(key: &str, value: &str) -> KeyValue { KeyValue { - enabled, key: key.to_string(), value: value.to_string(), + ..KeyValue::default() + } + } + + fn described(key: &str, value: &str, description: &str) -> KeyValue { + KeyValue { description: description.to_string(), + ..row(key, value) + } + } + + fn off(key: &str, value: &str) -> KeyValue { + KeyValue { + enabled: false, + ..row(key, value) } } + fn from_url(url: &str, params: &[KeyValue]) -> Vec { + let synced = sync(url, params, QuerySide::Url); + assert_eq!(synced.url, url, "the URL edited is kept as typed"); + synced.params + } + + fn from_params(url: &str, params: &[KeyValue]) -> String { + let synced = sync(url, params, QuerySide::Params); + assert_eq!(synced.params, params, "the table edited is kept as typed"); + synced.url + } + + /// Nothing decoded: `{{page}}` and `%20` read back as typed; a pair without `=` has an empty + /// value, an empty pair is none, and the fragment ends the query. #[test] - fn a_typed_query_fills_the_table_as_written() { - let synced = sync( - "{{baseUrl}}/customers/{{customerId}}/invoices?page=1&limit=50&q=a%20b&flag#top", + fn the_url_s_pairs_become_rows_as_typed() { + let rows = from_url( + "https://shop.test/a?q=a%20b&&page={{page}}&flag#top?x=1", &[], - QuerySide::Url, ); assert_eq!( - synced.params, - vec![ - row(true, "page", "1", ""), - row(true, "limit", "50", ""), - row(true, "q", "a%20b", ""), - row(true, "flag", "", ""), - ] + rows, + [row("q", "a%20b"), row("page", "{{page}}"), row("flag", "")] ); } + /// The pairs take the enabled rows' places in order; a row switched off is not in the URL + /// and stays where it was; a description follows its key; rows the URL no longer holds go. #[test] - fn a_disabled_row_stays_put_and_a_description_follows_its_key() { - let previous = [ - row(true, "page", "1", "Page, à partir de 1"), - row(false, "status", "paid", "Filtrer par statut"), - row(true, "limit", "50", "100 au plus"), + fn the_url_s_pairs_replace_the_enabled_rows_in_order() { + let table = [ + described("q", "old", "the search"), + off("debug", "1"), + described("page", "1", "which page"), + row("gone", "x"), ]; - let synced = sync("/invoices?page=2&size=50", &previous, QuerySide::Url); + let rows = from_url("https://shop.test/a?q=new&sort=asc", &table); assert_eq!( - synced.params, - vec![ - row(true, "page", "2", "Page, à partir de 1"), - row(false, "status", "paid", "Filtrer par statut"), - row(true, "size", "50", ""), + rows, + [ + described("q", "new", "the search"), + off("debug", "1"), + row("sort", "asc"), ] ); - assert_eq!( - sync("/invoices", &previous, QuerySide::Url).params, - vec![previous[1].clone()] - ); + assert_eq!(from_url("https://shop.test/a", &table), [off("debug", "1")]); } + /// The enabled rows with a key, in order; none, no `?`; the fragment stays at the end. #[test] - fn the_table_rewrites_the_query_keeping_the_path_and_the_fragment() { - let params = [ - row(true, "page", "{{page}}", ""), - row(false, "status", "paid", ""), - row(true, "", "orphan", ""), - row(true, "limit", "50", ""), + fn the_rows_rewrite_the_url_s_query() { + let table = [ + row("q", "{{term}}"), + off("debug", "1"), + row("", "lost"), + row("page", "2"), ]; assert_eq!( - sync("{{baseUrl}}/invoices?old=1#top", ¶ms, QuerySide::Params).url, - "{{baseUrl}}/invoices?page={{page}}&limit=50#top" + from_params("https://shop.test/a?old=1#top", &table), + "https://shop.test/a?q={{term}}&page=2#top" ); assert_eq!( - sync( - "/invoices?old=1", - &[row(false, "a", "1", "")], - QuerySide::Params - ) - .url, - "/invoices" + from_params("https://shop.test/a?old=1#top", &[off("debug", "1")]), + "https://shop.test/a#top" ); } } diff --git a/crates/engine/src/http/settings.rs b/crates/engine/src/http/settings.rs index 7b765d455..15345555a 100644 --- a/crates/engine/src/http/settings.rs +++ b/crates/engine/src/http/settings.rs @@ -145,6 +145,7 @@ pub fn implied_content_type(body: &RequestBody) -> Option<&'static str> { #[cfg(test)] mod tests { use super::*; + use crate::http::environments::Variable; fn origin(kind: HttpItemKind, name: &str) -> HttpOrigin { HttpOrigin { @@ -154,76 +155,81 @@ mod tests { } } - fn header(key: &str, value: &str, enabled: bool) -> KeyValue { + fn collection() -> HttpOrigin { + origin(HttpItemKind::Collection, "Shop") + } + + fn folder() -> HttpOrigin { + origin(HttpItemKind::Folder, "Orders") + } + + fn row(key: &str, value: &str) -> KeyValue { KeyValue { - enabled, key: key.to_string(), value: value.to_string(), - description: String::new(), + ..KeyValue::default() } } - #[test] - fn the_nearest_auth_set_wins_and_none_set_is_no_auth() { - let bearer = RequestAuth::Bearer { - token: "{{accessToken}}".to_string(), - }; - let levels = vec![ - ( - origin(HttpItemKind::Collection, "API Paiements"), - ContainerSettings { - auth: bearer.clone(), - headers: Vec::new(), - ..ContainerSettings::default() - }, - ), - ( - origin(HttpItemKind::Folder, "Factures"), - ContainerSettings::default(), - ), - ]; + fn off(key: &str) -> KeyValue { + KeyValue { + enabled: false, + ..row(key, "") + } + } - let inherited = inherit(&levels); - assert_eq!(inherited.auth, bearer); - assert_eq!( - inherited.auth_from.map(|from| from.name), - Some("API Paiements".to_string()) - ); + fn bearer(token: &str) -> RequestAuth { + RequestAuth::Bearer { + token: token.to_string(), + } + } - let nothing = inherit(&[( - origin(HttpItemKind::Collection, "Vide"), - ContainerSettings::default(), - )]); + fn with_auth(auth: RequestAuth) -> ContainerSettings { + ContainerSettings { + auth, + ..ContainerSettings::default() + } + } + + /// The nearest level that sets one wins, and is named; `Inherit` all the way up is none. + #[test] + fn the_nearest_auth_set_is_inherited_and_named() { + let both = inherit(&[ + (collection(), with_auth(bearer("c"))), + (folder(), with_auth(bearer("f"))), + ]); + let up = inherit(&[ + (collection(), with_auth(bearer("c"))), + (folder(), with_auth(RequestAuth::Inherit)), + ]); + let nothing = inherit(&[(collection(), with_auth(RequestAuth::Inherit))]); + + assert_eq!((both.auth, both.auth_from), (bearer("f"), Some(folder()))); + assert_eq!((up.auth, up.auth_from), (bearer("c"), Some(collection()))); assert_eq!((nothing.auth, nothing.auth_from), (RequestAuth::None, None)); } + /// Enabled and named, one a name, case aside: a folder's overrides its collection's in its + /// place, and says it comes from the folder. #[test] - fn a_folder_header_overrides_its_collection_one_whatever_its_case() { - let levels = vec![ - ( - origin(HttpItemKind::Collection, "API"), - ContainerSettings { - auth: RequestAuth::Inherit, - headers: vec![ - header("Accept", "application/json", true), - header("X-Trace", "1", false), - header("X-Client", "web", true), - ], - ..ContainerSettings::default() - }, - ), - ( - origin(HttpItemKind::Folder, "Factures"), - ContainerSettings { - auth: RequestAuth::Inherit, - headers: vec![header("accept", "text/csv", true)], - ..ContainerSettings::default() - }, - ), - ]; + fn a_folder_s_header_overrides_its_collection_s_of_the_same_name() { + let above = ContainerSettings { + headers: vec![ + row("Accept", "text/plain"), + row("X-Shop", "1"), + off("X-Off"), + row(" ", "unnamed"), + ], + ..ContainerSettings::default() + }; + let near = ContainerSettings { + headers: vec![row("accept", "application/json"), row("X-Orders", "2")], + ..ContainerSettings::default() + }; + + let inherited = inherit(&[(collection(), above), (folder(), near)]); - let inherited = inherit(&levels); - let seen: Vec<(&str, &str, &str)> = inherited + let shown: Vec<(&str, &str, &str)> = inherited .headers .iter() .map(|known| { @@ -235,75 +241,154 @@ mod tests { }) .collect(); assert_eq!( - seen, - vec![ - ("accept", "text/csv", "Factures"), - ("X-Client", "web", "API") + shown, + [ + ("accept", "application/json", "Orders"), + ("X-Shop", "1", "Shop"), + ("X-Orders", "2", "Orders"), ] ); } - /// What a timeout's sentence names: the nearest level that set the value, not the first. + /// Field by field, the nearest set wins; a failure names who set the timeout or the + /// redirects it ran into. #[test] - fn a_limit_is_set_by_the_nearest_level_that_sets_it_or_by_nobody() { - let sets = |timeout_ms, max_redirects| ContainerSettings { + fn the_transport_is_resolved_field_by_field_and_its_limits_named() { + let above = ContainerSettings { transport: TransportSettings { - timeout_ms, - max_redirects, + timeout_ms: Some(5_000), + max_redirects: Some(3), ..TransportSettings::default() }, ..ContainerSettings::default() }; - let api = origin(HttpItemKind::Collection, "API"); - let auth = origin(HttpItemKind::Folder, "Auth"); - let levels = vec![ - (api.clone(), sets(Some(5_000), Some(3))), - (auth.clone(), sets(Some(2_000), None)), - ]; - - let inherited = inherit(&levels); - - assert_eq!(inherited.limits.timeout, SetBy::Above(auth)); - assert_eq!(inherited.limits.redirects, SetBy::Above(api)); - assert_eq!(inherit(&[]).limits, Limits::default()); + let near = ContainerSettings { + transport: TransportSettings { + timeout_ms: Some(2_000), + verify_tls: Some(false), + ..TransportSettings::default() + }, + ..ContainerSettings::default() + }; + + let inherited = inherit(&[(collection(), above), (folder(), near)]); + let bare = inherit(&[(collection(), ContainerSettings::default())]); + + assert_eq!( + ( + inherited.transport.timeout_ms, + inherited.transport.max_redirects + ), + (2_000, 3) + ); + assert!(!inherited.transport.verify_tls); + assert_eq!(inherited.limits.timeout, SetBy::Above(folder())); + assert_eq!(inherited.limits.redirects, SetBy::Above(collection())); + assert_eq!(bare.limits, Limits::default()); } - /// Off anywhere above, and no level sets another: none is sent, not the application's. + /// A level holding a `User-Agent` row switched off: the application's own is not sent. #[test] - fn a_user_agent_row_switched_off_at_any_level_is_remembered() { - let holds = |rows: Vec| ContainerSettings { - headers: rows, + fn a_user_agent_switched_off_above_keeps_the_application_s_off() { + let above = ContainerSettings { + headers: vec![off(" user-agent ")], ..ContainerSettings::default() }; - let api = origin(HttpItemKind::Collection, "API"); - let auth = origin(HttpItemKind::Folder, "Auth"); - let off = inherit(&[ - (api.clone(), holds(vec![header(" user-agent ", "x", false)])), - (auth.clone(), holds(Vec::new())), - ]); - assert!(off.user_agent_off); - assert!(off.headers.is_empty()); - - let on = inherit(&[ - (api, holds(vec![header("User-Agent", "Équipe/1", true)])), - (auth, holds(vec![header("X-Debug", "1", false)])), - ]); - assert!(!on.user_agent_off); + assert!( + inherit(&[ + (collection(), above), + (folder(), ContainerSettings::default()) + ]) + .user_agent_off + ); + assert!(!inherit(&[(collection(), ContainerSettings::default())]).user_agent_off); } + /// The variables the nearest first, as layers named after who holds them; the scripts from + /// the collection down, the order they run in before the send. #[test] - fn a_body_implies_its_content_type() { - assert_eq!(implied_content_type(&RequestBody::None), None); - assert_eq!( - implied_content_type(&RequestBody::Json { - text: "{}".to_string() - }), - Some("application/json") - ); + fn variables_come_nearest_first_and_scripts_from_the_collection_down() { + let settings = |name: &str| ContainerSettings { + variables: vec![Variable { + name: name.to_string(), + ..Variable::default() + }], + scripts: RequestScripts { + before: name.to_string(), + ..RequestScripts::default() + }, + ..ContainerSettings::default() + }; + + let inherited = inherit(&[(collection(), settings("c")), (folder(), settings("f"))]); + + let layers: Vec<(VariableScope, &str, &str)> = inherited + .variables + .iter() + .map(|layer| { + ( + layer.scope, + layer.from.as_str(), + layer.variables[0].name.as_str(), + ) + }) + .collect(); assert_eq!( - implied_content_type(&RequestBody::Form { fields: Vec::new() }), - Some("application/x-www-form-urlencoded") + layers, + [ + (VariableScope::Folder, "Orders", "f"), + (VariableScope::Collection, "Shop", "c") + ] ); + let scripts: Vec<(&str, &str)> = inherited + .scripts + .iter() + .map(|level| (level.from.name.as_str(), level.scripts.before.as_str())) + .collect(); + assert_eq!(scripts, [("Shop", "c"), ("Orders", "f")]); + } + + /// Unless the request sets one by hand. + #[test] + fn a_body_implies_its_content_type() { + for (body, implied) in [ + (RequestBody::None, None), + ( + RequestBody::Json { + text: String::new(), + }, + Some("application/json"), + ), + ( + RequestBody::Text { + text: String::new(), + }, + Some("text/plain"), + ), + ( + RequestBody::Form { fields: Vec::new() }, + Some("application/x-www-form-urlencoded"), + ), + ( + RequestBody::Multipart { parts: Vec::new() }, + Some("multipart/form-data"), + ), + ( + RequestBody::Binary { + path: String::new(), + }, + Some("application/octet-stream"), + ), + ] { + assert_eq!(implied_content_type(&body), implied, "{body:?}"); + } + } + + #[test] + fn a_row_switches_a_header_off_only_when_written_and_off() { + assert!(switches_off(&[off(" Accept ")], "accept")); + assert!(!switches_off(&[row("Accept", "x")], "accept")); + assert!(!switches_off(&[off("Other")], "accept")); } } diff --git a/crates/engine/src/http/transport.rs b/crates/engine/src/http/transport.rs index c38427aba..d26a3c28b 100644 --- a/crates/engine/src/http/transport.rs +++ b/crates/engine/src/http/transport.rs @@ -110,44 +110,75 @@ pub fn resolve<'a>(levels: impl IntoIterator) -> T mod tests { use super::*; + /// Nothing set: thirty seconds, redirects followed up to ten, TLS checked, cookies kept. #[test] - fn the_nearest_setting_wins_field_by_field_over_the_defaults() { + fn a_request_nobody_configured_travels_with_the_defaults() { + let transport = resolve(&[TransportSettings::default()]); + + assert_eq!( + transport, + Transport { + timeout_ms: 30_000, + follow_redirects: true, + max_redirects: 10, + verify_tls: true, + use_cookies: true, + } + ); + } + + /// From the collection down, each field the nearest set. + #[test] + fn each_field_is_taken_from_the_nearest_level_setting_it() { let collection = TransportSettings { timeout_ms: Some(5_000), - verify_tls: Some(false), - ..TransportSettings::default() - }; - let folder = TransportSettings { - timeout_ms: Some(2_000), - max_redirects: Some(3), + follow_redirects: Some(false), + max_redirects: Some(2), + use_cookies: Some(false), ..TransportSettings::default() }; let request = TransportSettings { - use_cookies: Some(false), - timeout_ms: Some(10), + timeout_ms: Some(1_000), + verify_tls: Some(false), ..TransportSettings::default() }; + let transport = resolve([&collection, &request]); + assert_eq!( - resolve([&collection, &folder, &request]), + transport, Transport { - timeout_ms: 100, - follow_redirects: true, - max_redirects: 3, + timeout_ms: 1_000, + follow_redirects: false, + max_redirects: 2, verify_tls: false, use_cookies: false, } ); - assert_eq!(resolve([]), Transport::default()); } + /// Under a tenth of a second is a slip of the keyboard, not a choice. + #[test] + fn a_timeout_too_short_to_mean_it_is_raised() { + let settings = TransportSettings { + timeout_ms: Some(5), + ..TransportSettings::default() + }; + + assert_eq!(resolve([&settings]).timeout_ms, 100); + } + + /// The largest unit that says it whole. #[test] - fn a_delay_is_said_in_the_largest_unit_that_holds_it_whole() { - assert_eq!(readable_delay(1_000), (1, "s")); - assert_eq!(readable_delay(30_000), (30, "s")); - assert_eq!(readable_delay(120_000), (2, "min")); - assert_eq!(readable_delay(90_000), (90, "s")); - assert_eq!(readable_delay(1_500), (1_500, "ms")); - assert_eq!(readable_delay(100), (100, "ms")); + fn a_delay_reads_in_the_largest_unit_that_says_it_whole() { + for (millis, readable) in [ + (120_000, (2, "min")), + (90_000, (90, "s")), + (30_000, (30, "s")), + (1_500, (1_500, "ms")), + (0, (0, "ms")), + ] { + assert_eq!(readable_delay(millis), readable, "{millis}"); + } } } From e08f9b22bbad6b0f7aeb0778d4573309d2204f4f Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:53:11 +0100 Subject: [PATCH 34/95] HTTP environments: unit tests rewritten for sets and globals (#1756) * Rewrite the tests of HTTP environments: their rules, the globals and the services Co-Authored-By: Claude Opus 5.5 * A set whose document does not read fails the list Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/http/environments.rs | 174 ++++++++--- .../tests/commands/http_environments.rs | 288 +++++++++++++----- 2 files changed, 351 insertions(+), 111 deletions(-) diff --git a/crates/engine/src/http/environments.rs b/crates/engine/src/http/environments.rs index 3db32c859..c1f3fa143 100644 --- a/crates/engine/src/http/environments.rs +++ b/crates/engine/src/http/environments.rs @@ -190,56 +190,77 @@ pub fn variable_faults(variables: &[Variable]) -> Vec> { mod tests { use super::*; - fn variable(name: &str, value: &str, kind: VariableKind) -> Variable { + fn variable(name: &str, value: &str) -> Variable { Variable { name: name.to_string(), value: value.to_string(), - kind, ..Variable::default() } } - #[test] - fn every_kind_survives_its_stored_spelling() { - for kind in VariableKind::ALL { - assert_eq!(kind.as_str().parse::(), Ok(kind)); + fn number(name: &str, value: &str) -> Variable { + Variable { + kind: VariableKind::Number, + ..variable(name, value) } } - #[test] - fn a_name_holds_what_a_placeholder_holds() { - for name in ["baseUrl", "access_token", "api-key", "v2"] { - assert!(is_variable_name(name), "{name}"); + fn secret(name: &str) -> Variable { + Variable { + kind: VariableKind::Secret, + ..variable(name, "s") } - for name in ["", "base url", "user.name", "clé", "{{x}}"] { - assert!(!is_variable_name(name), "{name}"); + } + + /// What a `{{…}}` can hold: letters, digits, `_` and `-`, as a snippet's field. + #[test] + fn a_variable_name_holds_letters_digits_underscores_and_dashes() { + for (name, valid) in [ + ("base_url", true), + ("api-v2", true), + ("ID9", true), + ("", false), + ("a.b", false), + ("a b", false), + ("clé", false), + ("$guid", false), + ] { + assert_eq!(is_variable_name(name), valid, "{name:?}"); } } + /// Kept as typed and marked: a name no `{{…}}` can hold, a number that does not read as + /// one, a name already set above it — the first one being used. A row switched off or + /// still without a name is not judged. #[test] - fn a_table_marks_a_bad_name_a_second_one_and_a_number_that_is_not() { - let mut off = variable("token", "x", VariableKind::Text); - off.enabled = false; + fn a_row_is_marked_by_what_keeps_it_from_resolving() { + let rows = [ + variable("host", "x"), + variable("bad name", "x"), + number("count", "12.5"), + number("empty", ""), + number("many", "many"), + number("endless", "inf"), + variable(" host ", "again"), + Variable { + enabled: false, + ..variable("bad name", "x") + }, + variable(" ", "unnamed"), + ]; + + let faults = variable_faults(&rows); + assert_eq!( - variable_faults(&[ - variable("baseUrl", "https://exemple.fr", VariableKind::Text), - variable("base url", "", VariableKind::Text), - variable("baseUrl", "other", VariableKind::Text), - variable("pageSize", "50", VariableKind::Number), - variable("ratio", "-1.5e3", VariableKind::Number), - variable("limit", "fifty", VariableKind::Number), - variable("unset", " ", VariableKind::Number), - variable(" ", "orphan", VariableKind::Text), - off, - ]), - vec![ + faults, + [ None, Some(VariableFault::Name), - Some(VariableFault::Duplicate), None, None, Some(VariableFault::Number), - None, + Some(VariableFault::Number), + Some(VariableFault::Duplicate), None, None, ] @@ -247,29 +268,94 @@ mod tests { } #[test] - fn a_patch_changes_what_it_names_and_nothing_else() { - let before = EnvironmentDocument { + fn a_set_counts_its_named_variables_and_its_secrets() { + let counts = variable_counts(&[ + variable("a", "1"), + secret("b"), + secret(" "), + variable("", "x"), + ]); + + assert_eq!( + counts, + VariableCounts { + count: 2, + secrets: 1 + } + ); + } + + /// What reads without changing anything goes unasked; a socket asks before it opens, + /// whatever it then says. + #[test] + fn a_protected_environment_asks_before_anything_that_could_change_something() { + for method in HttpMethod::ALL { + assert_eq!( + asks_before_sending(RequestKind::Http, method), + !method.changes_nothing(), + "{method:?}" + ); + assert_eq!( + asks_before_sending(RequestKind::Graphql, method), + !method.changes_nothing(), + "{method:?}" + ); + assert!( + asks_before_sending(RequestKind::Websocket, method), + "{method:?}" + ); + } + } + + /// A field left out is untouched; the name comes validated, apart from the patch. + #[test] + fn a_patch_changes_only_the_fields_it_sets() { + let document = EnvironmentDocument { name: "Staging".to_string(), colour: FolderColour::Amber, protected: false, - variables: vec![variable("a", "1", VariableKind::Text)], + variables: vec![variable("host", "staging")], }; - let after = before.clone().patched( - &EnvironmentPatch { - protected: Some(true), - ..EnvironmentPatch::default() - }, - None, + let patch = EnvironmentPatch { + protected: Some(true), + ..EnvironmentPatch::default() + }; + let full = EnvironmentPatch { + name: Some("ignored".to_string()), + colour: Some(FolderColour::Red), + protected: Some(true), + variables: Some(vec![variable("host", "prod")]), + }; + + let protected = document.clone().patched(&patch, None); + let renamed = document.clone().patched(&full, Some("Production")); + + assert_eq!( + protected, + EnvironmentDocument { + protected: true, + ..document + } ); assert_eq!( - after, + renamed, EnvironmentDocument { + name: "Production".to_string(), + colour: FolderColour::Red, protected: true, - ..before + variables: vec![variable("host", "prod")], } ); } + #[test] + fn an_environment_is_named_readably() { + assert_eq!(validated_name(" Prod ").unwrap(), "Prod"); + assert!(validated_name("").is_err()); + } + + /// Every field defaults: a set written by an older version still opens, and a row without + /// its switch is on. #[test] fn a_document_written_before_a_field_existed_still_opens() { let document: EnvironmentDocument = serde_json::from_str(r#"{"name":"Local"}"#).unwrap(); @@ -280,4 +366,12 @@ mod tests { assert!(row.enabled); assert_eq!(row.kind, VariableKind::Text); } + + /// Stored as written: a kind reads back from its spelling. + #[test] + fn every_variable_kind_reads_back_from_its_spelling() { + for kind in VariableKind::ALL { + assert_eq!(kind.as_str().parse::(), Ok(kind)); + } + } } diff --git a/crates/engine/tests/commands/http_environments.rs b/crates/engine/tests/commands/http_environments.rs index f9c9eac74..efe4ca246 100644 --- a/crates/engine/tests/commands/http_environments.rs +++ b/crates/engine/tests/commands/http_environments.rs @@ -1,6 +1,5 @@ -//! The environments' commands: a name checked before the lock, a name held once, a set gone -//! said by its code, and each variable's fault by its rank. - +use diesel::prelude::*; +use engine::db::schema::http_environments as table; use engine::error::ErrorCode; use engine::folders::model::FolderColour; use engine::http::environments::{EnvironmentPatch, Variable, VariableFault, VariableKind}; @@ -11,112 +10,259 @@ use engine::http::{ use super::{Session, code}; -fn variable(name: &str, value: &str, kind: VariableKind) -> Variable { +fn variable(name: &str, value: &str) -> Variable { Variable { name: name.to_string(), value: value.to_string(), - kind, ..Variable::default() } } +fn secret(name: &str, value: &str) -> Variable { + Variable { + kind: VariableKind::Secret, + ..variable(name, value) + } +} + +fn names(session: &Session) -> Vec { + let sets = session.call(http_environments).unwrap(); + sets.environments + .into_iter() + .map(|environment| environment.name) + .collect() +} + +fn create(session: &Session, name: &str) -> String { + session + .call(|e| create_http_environment(e, name)) + .unwrap() + .id +} + #[test] -fn environments_are_made_written_copied_and_deleted_through_their_commands() { - let session = Session::open(); - let local = session - .call(|e| create_http_environment(e, " Local ")) - .unwrap(); - assert_eq!(local.name, "Local"); +fn environments_answer_locked_before_a_library_is_open() { + let session = Session::locked(); - let patch = EnvironmentPatch { - name: Some("Dev".to_string()), - colour: Some(FolderColour::Green), - protected: Some(true), - variables: Some(vec![variable("token", "t0k3n", VariableKind::Secret)]), - }; - let saved = session - .call(|e| save_http_environment(e, &local.id, &patch)) - .unwrap(); + assert_eq!(code(session.call(http_environments)), ErrorCode::Locked); assert_eq!( - (saved.name.as_str(), saved.colour, saved.protected), - ("Dev", FolderColour::Green, true) + code(session.call(|e| create_http_environment(e, "Prod"))), + ErrorCode::Locked ); +} - let globals = vec![variable("tenant", "acme", VariableKind::Text)]; - let kept = session.call(|e| save_http_globals(e, &globals)).unwrap(); - assert_eq!(kept, globals); +/// Trimmed, last, unprotected and empty, in the next of the five colours: two made one after the other +/// differ, and a sixth comes round to the first. +#[test] +fn an_environment_is_made_last_in_the_next_colour() { + let session = Session::open(); - let copy = session - .call(|e| duplicate_http_environment(e, &local.id, "Dev (copie)")) - .unwrap(); - assert_eq!(copy.variables, saved.variables); + let made: Vec<_> = ["Dev", "Staging", "Prod", "Demo", "Local", " Sixth "] + .iter() + .map(|name| session.call(|e| create_http_environment(e, name)).unwrap()) + .collect(); - session - .call(|e| delete_http_environment(e, &local.id)) - .unwrap(); - let all = session.call(http_environments).unwrap(); - assert_eq!(all.globals, globals); assert_eq!( - all.environments - .iter() - .map(|environment| environment.name.as_str()) - .collect::>(), - ["Dev (copie)"] + names(&session), + ["Dev", "Staging", "Prod", "Demo", "Local", "Sixth"] ); + let colours: Vec = made.iter().map(|environment| environment.colour).collect(); + assert_eq!(colours, [0, 1, 2, 3, 4, 0].map(FolderColour::nth)); + assert!(!made[0].protected && made[0].variables.is_empty()); } +/// Case aside, as everywhere names are compared in Rust; a set may still correct its own case. +/// A blank name is refused before anything is read. #[test] -fn a_blank_name_a_name_held_twice_and_a_set_gone_each_answer_their_code() { +fn an_environment_s_name_is_its_own() { let session = Session::open(); + let prod = create(&session, "Prod"); + create(&session, "Staging"); + let rename = |name: &str| EnvironmentPatch { + name: Some(name.to_string()), + ..EnvironmentPatch::default() + }; + assert_eq!( - code(session.call(|e| create_http_environment(e, " "))), - ErrorCode::InvalidInput - ); - let local = session - .call(|e| create_http_environment(e, "Local")) - .unwrap(); - assert_eq!( - code(session.call(|e| create_http_environment(e, "LOCAL"))), + code(session.call(|e| create_http_environment(e, "prod"))), ErrorCode::DuplicateEnvironmentName ); - let renaming = EnvironmentPatch { - name: Some(" ".to_string()), - ..EnvironmentPatch::default() - }; assert_eq!( - code(session.call(|e| save_http_environment(e, &local.id, &renaming))), - ErrorCode::InvalidInput + code(session.call(|e| save_http_environment(e, &prod, &rename("STAGING")))), + ErrorCode::DuplicateEnvironmentName ); + session + .call(|e| save_http_environment(e, &prod, &rename(" PROD "))) + .unwrap(); + assert_eq!(names(&session), ["PROD", "Staging"]); assert_eq!( - code(session.call(|e| duplicate_http_environment(e, &local.id, ""))), + code(session.call(|e| create_http_environment(e, " "))), ErrorCode::InvalidInput ); +} + +/// A field left out is untouched; what is saved reads back. +#[test] +fn an_environment_saved_keeps_the_fields_left_out() { + let session = Session::open(); + let prod = create(&session, "Prod"); + let variables = EnvironmentPatch { + variables: Some(vec![ + variable("host", "shop.test"), + secret("token", "t0k3n"), + ]), + ..EnvironmentPatch::default() + }; + let protect = EnvironmentPatch { + protected: Some(true), + colour: Some(FolderColour::Red), + ..EnvironmentPatch::default() + }; + + session + .call(|e| save_http_environment(e, &prod, &variables)) + .unwrap(); + let saved = session + .call(|e| save_http_environment(e, &prod, &protect)) + .unwrap(); + + let listed = session + .call(http_environments) + .unwrap() + .environments + .remove(0); + assert_eq!(saved, listed); assert_eq!( - code(session.call(|e| delete_http_environment(e, "gone"))), - ErrorCode::HttpEnvironmentNotFound + (listed.name.as_str(), listed.protected, listed.colour), + ("Prod", true, FolderColour::Red) ); assert_eq!( - code(session.call(|e| save_http_environment(e, "gone", &EnvironmentPatch::default()))), - ErrorCode::HttpEnvironmentNotFound + listed.variables, + [variable("host", "shop.test"), secret("token", "t0k3n")] ); } +/// Written whole, the row made the first time; never listed as an environment. #[test] -fn the_variables_are_judged_row_by_row() { - let faults = check_http_variables(&[ - variable("baseUrl", "https://exemple.fr", VariableKind::Text), - variable("base url", "", VariableKind::Text), - variable("pageSize", "fifty", VariableKind::Number), - ]) - .unwrap(); +fn the_globals_are_written_whole_apart_from_the_environments() { + let session = Session::open(); + assert!(session.call(http_environments).unwrap().globals.is_empty()); + + session + .call(|e| save_http_globals(e, &[variable("a", "1"), variable("b", "2")])) + .unwrap(); + session + .call(|e| save_http_globals(e, &[variable("c", "3")])) + .unwrap(); + + let sets = session.call(http_environments).unwrap(); + assert_eq!(sets.globals, [variable("c", "3")]); + assert!(sets.environments.is_empty()); +} + +/// Right after its original, secrets included, under the name the interface gives it. +#[test] +fn an_environment_is_copied_right_after_its_original_with_its_secrets() { + let session = Session::open(); + let prod = create(&session, "Prod"); + create(&session, "Staging"); + let with_secret = EnvironmentPatch { + variables: Some(vec![secret("token", "t0k3n")]), + ..EnvironmentPatch::default() + }; + session + .call(|e| save_http_environment(e, &prod, &with_secret)) + .unwrap(); + + let copy = session + .call(|e| duplicate_http_environment(e, &prod, "Prod (copy)")) + .unwrap(); + + assert_eq!(names(&session), ["Prod", "Prod (copy)", "Staging"]); + assert_eq!(copy.variables, [secret("token", "t0k3n")]); assert_eq!( - faults, - [None, Some(VariableFault::Name), Some(VariableFault::Number)] + code(session.call(|e| duplicate_http_environment(e, &prod, "staging"))), + ErrorCode::DuplicateEnvironmentName ); } #[test] -fn nothing_answers_before_the_library_is_unlocked() { - let session = Session::locked(); - assert_eq!(code(session.call(http_environments)), ErrorCode::Locked); +fn an_environment_is_deleted_and_one_not_there_is_named() { + let session = Session::open(); + let prod = create(&session, "Prod"); + create(&session, "Staging"); + + session.call(|e| delete_http_environment(e, &prod)).unwrap(); + + assert_eq!(names(&session), ["Staging"]); + for answer in [ + session.call(|e| delete_http_environment(e, &prod)), + session + .call(|e| save_http_environment(e, &prod, &EnvironmentPatch::default())) + .map(|_| ()), + session + .call(|e| duplicate_http_environment(e, &prod, "Again")) + .map(|_| ()), + ] { + assert_eq!(code(answer), ErrorCode::HttpEnvironmentNotFound); + } +} + +/// Sealed whole: neither a name nor a secret's value is in the database in the clear. +#[test] +fn an_environment_is_sealed_whole() { + let session = Session::open(); + let prod = create(&session, "Production"); + let with_secret = EnvironmentPatch { + variables: Some(vec![secret("token", "t0k3n-in-clear")]), + ..EnvironmentPatch::default() + }; + session + .call(|e| save_http_environment(e, &prod, &with_secret)) + .unwrap(); + session + .call(|e| save_http_globals(e, &[secret("global", "g10bal-in-clear")])) + .unwrap(); + + let mut db = session.engine.db().lock().unwrap(); + let stored: Vec = table::table + .select(table::document) + .load(db.as_mut().unwrap().db()) + .unwrap(); + assert_eq!(stored.len(), 2); + for document in stored { + for clear in ["Production", "t0k3n-in-clear", "g10bal-in-clear", "token"] { + assert!(!document.contains(clear), "{clear} in the clear"); + } + } +} + +/// The table marks each row by the model's rule. +#[test] +fn the_variables_are_checked_by_the_model_s_rule() { + let session = Session::open(); + + let faults = session + .call(|_| check_http_variables(&[variable("ok", "1"), variable("bad name", "x")])) + .unwrap(); + + assert_eq!(faults, [None, Some(VariableFault::Name)]); +} + +/// A set whose sealed document does not read fails the list rather than vanishing from it. +#[test] +fn a_set_that_does_not_read_fails_the_list() { + let session = Session::open(); + create(&session, "Prod"); + { + let mut db = session.engine.db().lock().unwrap(); + let library = db.as_mut().unwrap(); + let garbage = library.vault().seal("not json").unwrap(); + diesel::update(table::table) + .set(table::document.eq(garbage)) + .execute(library.db()) + .unwrap(); + } + + assert_eq!(code(session.call(http_environments)), ErrorCode::Storage); } From bc1e31b601a066aa48afc72306c0f1111bf99d5f Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:53:26 +0100 Subject: [PATCH 35/95] HTTP answers: unit tests rewritten for reading and extracting (#1757) * Rewrite the tests of reading an HTTP answer, extracting a value and finding a request Co-Authored-By: Claude Opus 5.5 * A header that is no cookie, a quote escaped mid-string and an empty key, each held Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/http/extract.rs | 122 ++++++++++++++++----------- crates/engine/src/http/response.rs | 127 +++++++++++++++++++++-------- crates/engine/src/http/search.rs | 104 ++++++++++------------- 3 files changed, 210 insertions(+), 143 deletions(-) diff --git a/crates/engine/src/http/extract.rs b/crates/engine/src/http/extract.rs index a802e2e01..f81814295 100644 --- a/crates/engine/src/http/extract.rs +++ b/crates/engine/src/http/extract.rs @@ -147,72 +147,96 @@ pub fn looks_secret(path: &str) -> bool { mod tests { use super::*; + const ANSWER: &str = r#"{"access_token":"t0k3n","items":[{"id":7},{"id":8}],"a key":"spaced","it's":"quoted","back\\slash":"b","nested":{"ok":true}}"#; + + /// A text as it is, anything else as JSON; a key with a space or a quote reached between + /// quotes. #[test] - fn a_name_is_proposed_from_the_last_key_in_camel_case() { - assert_eq!(variable_name_of("body.access_token"), "accessToken"); - assert_eq!(variable_name_of("body.data['user-id']"), "userId"); - assert_eq!(variable_name_of("body.items[0]"), "value"); - assert_eq!(variable_name_of("body.Id"), "id"); - assert_eq!(variable_name_of("body['2fa']"), "value2fa"); + fn a_value_is_read_at_its_path() { + for (path, value) in [ + ("body.access_token", "t0k3n"), + (" body.items[1].id ", "8"), + ("body['a key']", "spaced"), + ("body['it\\'s']", "quoted"), + ("body['back\\\\slash']", "b"), + ("body.nested", "{\"ok\":true}"), + ("body.nested.ok", "true"), + ] { + assert_eq!(extract(ANSWER, path).as_deref(), Some(value), "{path}"); + } + assert_eq!(extract("[1,2]", "body").as_deref(), Some("[1,2]")); } + /// The variable is then left as it was. #[test] - fn a_key_that_reads_as_a_secret_is_proposed_as_one() { + fn a_path_leading_nowhere_or_an_answer_not_json_reads_nothing() { for path in [ - "body.access_token", - "body.password", - "body.apiKey", - "body.api_key", - "body['x-key']", - "body.key", + "body.missing", + "body.items[5].id", + "body.items.id", + "access_token", + "body.", + "body..x", + "body[one]", + "body[0", + "body['open", + "body['a key'", ] { - assert!(looks_secret(path), "{path}"); - } - for path in ["body.keyboard", "body.monkey", "body.id", "body.items[0]"] { - assert!(!looks_secret(path), "{path}"); + assert_eq!(extract(ANSWER, path), None, "{path}"); } + assert_eq!(extract("not json", "body"), None); + assert_eq!(extract(r#"{"":{"x":1}}"#, "body..x"), None); } + /// What the response's explorer writes, as a rule reads it. #[test] - fn the_explorer_s_path_becomes_a_rule_s() { + fn the_explorer_s_path_reads_from_the_body() { assert_eq!(body_path("$.data.token"), "body.data.token"); assert_eq!(body_path("$['a key']"), "body['a key']"); - assert_eq!(body_path("body.id"), "body.id"); + assert_eq!(body_path("body.x"), "body.x"); } - const LOGIN: &str = r#"{"access_token":"eyJ.a.b","expires_in":3600,"scope":null, - "user":{"roles":["admin","billing"],"a key":{"it's":true}}}"#; - + /// Its key in camelCase; a name that would not start with a letter is prefixed; an index or + /// a bare body proposes `value`. #[test] - fn reads_a_value_down_its_path_a_text_as_it_is_the_rest_as_json() { - assert_eq!( - extract(LOGIN, "body.access_token").as_deref(), - Some("eyJ.a.b") - ); - assert_eq!(extract(LOGIN, "body.expires_in").as_deref(), Some("3600")); - assert_eq!(extract(LOGIN, "body.scope").as_deref(), Some("null")); - assert_eq!( - extract(LOGIN, "body.user.roles[1]").as_deref(), - Some("billing") - ); - assert_eq!( - extract(LOGIN, "body.user.roles").as_deref(), - Some(r#"["admin","billing"]"#) - ); - assert_eq!( - extract(LOGIN, r"body.user['a key']['it\'s']").as_deref(), - Some("true") - ); - assert_eq!(extract("[1,2]", "body[0]").as_deref(), Some("1")); + fn a_value_is_proposed_a_name_from_its_key() { + for (path, name) in [ + ("body.access_token", "accessToken"), + ("body['x-request-id']", "xRequestId"), + ("body['a key']", "aKey"), + ("body.Token", "token"), + ("body.userID", "userID"), + ("body['2fa']", "value2fa"), + ("body['__']", "value"), + ("body.items[0]", "value"), + ("body", "value"), + ] { + assert_eq!(variable_name_of(path), name, "{path}"); + } } + /// A key that reads as a token, a password or a key; `key` as a word, not inside one. #[test] - fn a_path_that_no_longer_reads_gives_nothing() { - assert_eq!(extract(LOGIN, "body.refresh_token"), None); - assert_eq!(extract(LOGIN, "body.user.roles[7]"), None); - assert_eq!(extract(LOGIN, "body..x"), None); - assert_eq!(extract(LOGIN, "headers.x"), None); - assert_eq!(extract(LOGIN, "body['open"), None); - assert_eq!(extract("", "body.x"), None); + fn a_key_reading_as_a_secret_is_proposed_as_one() { + for (path, secret) in [ + ("body.access_token", true), + ("body.Password", true), + ("body.pwd", true), + ("body.client_secret", true), + ("body.sessionId", true), + ("body['Set-Cookie']", true), + ("body.key", true), + ("body.api_key", true), + ("body['api-key']", true), + ("body.apiKey", true), + ("body.monkey", false), + ("body.keyboard", false), + ("body.APIKey", false), + ("body.id", false), + ("body.items[0]", false), + ("not a path", false), + ] { + assert_eq!(looks_secret(path), secret, "{path}"); + } } } diff --git a/crates/engine/src/http/response.rs b/crates/engine/src/http/response.rs index 35d7b785b..ff54832ac 100644 --- a/crates/engine/src/http/response.rs +++ b/crates/engine/src/http/response.rs @@ -178,57 +178,62 @@ mod tests { } } + /// Read off its type, whatever its case and parameters; with none, a body that parses as + /// JSON is JSON. A type that says otherwise wins over a body that looks like JSON. #[test] - fn json_is_laid_out_with_its_numbers_and_strings_as_they_came() { - assert_eq!( - pretty_json(r#"{"id":12345678901234567890,"n":1.10,"s":"a, {b}: \"c\"","e":[],"o":{ },"l":[1,{"k":null}]}"#) - .unwrap(), - "{\n \"id\": 12345678901234567890,\n \"n\": 1.10,\n \"s\": \"a, {b}: \\\"c\\\"\",\n \"e\": [],\n \"o\": {},\n \"l\": [\n 1,\n {\n \"k\": null\n }\n ]\n}" - ); - assert_eq!(pretty_json(" 42 ").as_deref(), Some("42")); - assert_eq!(pretty_json("{\"a\":"), None); - } - - #[test] - fn the_language_follows_the_type_or_failing_one_the_text() { - assert_eq!( - language(Some("application/problem+json; charset=utf-8"), ""), - Language::Json - ); - assert_eq!(language(Some("text/html"), ""), Language::Html); - assert_eq!(language(Some("application/xhtml+xml"), ""), Language::Html); - assert_eq!(language(Some("application/rss+xml"), ""), Language::Xml); - assert_eq!(language(Some("text/javascript"), ""), Language::Js); - assert_eq!(language(Some("text/plain"), "{\"a\":1}"), Language::Txt); - assert_eq!(language(None, " [1, 2]"), Language::Json); - assert_eq!(language(None, "hello"), Language::Txt); + fn an_answer_is_coloured_in_the_language_its_type_names() { + for (kind, body, expected) in [ + (Some("application/json; charset=utf-8"), "", Language::Json), + (Some("application/problem+json"), "", Language::Json), + (Some("TEXT/HTML"), "", Language::Html), + (Some("application/xhtml+xml"), "", Language::Html), + (Some("image/svg+xml"), "", Language::Xml), + (Some("application/javascript"), "", Language::Js), + (Some("text/ecmascript"), "", Language::Js), + (Some("text/css"), "", Language::Css), + (Some("application/x-yaml"), "", Language::Yml), + (Some("application/graphql"), "", Language::Graphql), + (Some("text/plain"), "{\"a\":1}", Language::Txt), + (None, " [1, 2]", Language::Json), + (None, "{\"a\":1}", Language::Json), + (None, "{not json", Language::Txt), + (None, "\"just a string\"", Language::Txt), + (Some(" ; charset=utf-8"), "{}", Language::Json), + ] { + assert_eq!(language(kind, body), expected, "{kind:?} {body:?}"); + } } + /// Every `Set-Cookie`, in order, its attributes named; a quoted value read without its + /// quotes; a line that names no cookie left out. #[test] - fn a_set_cookie_is_read_with_its_attributes_and_the_other_headers_are_not() { - let found = cookies(&[ - header("content-type", "text/plain"), + fn each_set_cookie_is_read_with_its_attributes() { + let headers = [ + header("Content-Type", "text/plain"), + header("X-Not-A-Cookie", "a=b"), header( "set-cookie", - "session=\"abc=1\"; Path=/; Domain=example.com; Expires=Wed, 21 Oct 2026 07:28:00 GMT; Max-Age=3600; HttpOnly; Secure; SameSite=Lax", + "sid=\"abc=1\"; Domain=shop.test; Path=/; HttpOnly; Secure; SameSite=Lax", ), header("Set-Cookie", "theme=dark"), - header("set-cookie", "=nameless"), - ]); + header("Set-Cookie", "no equals sign"), + header("Set-Cookie", " =nameless"), + ]; + + let cookies = cookies(&headers); assert_eq!( - found, - vec![ + cookies, + [ Cookie { - name: "session".to_string(), + name: "sid".to_string(), value: "abc=1".to_string(), - domain: Some("example.com".to_string()), + domain: Some("shop.test".to_string()), path: Some("/".to_string()), - expires: Some("Max-Age=3600".to_string()), http_only: true, secure: true, same_site: Some("Lax".to_string()), - from: None, + ..Cookie::default() }, Cookie { name: "theme".to_string(), @@ -238,4 +243,56 @@ mod tests { ] ); } + + /// As a browser reads them, whichever comes first. + #[test] + fn max_age_wins_over_expires() { + for line in [ + "a=1; Expires=Wed, 21 Oct 2026 07:28:00 GMT; Max-Age=60", + "a=1; Max-Age=60; Expires=Wed, 21 Oct 2026 07:28:00 GMT", + ] { + let read = cookies(&[header("Set-Cookie", line)]); + + assert_eq!(read[0].expires.as_deref(), Some("Max-Age=60"), "{line}"); + } + let expires = cookies(&[header( + "Set-Cookie", + "a=1; expires=Wed, 21 Oct 2026 07:28:00 GMT", + )]); + assert_eq!( + expires[0].expires.as_deref(), + Some("Wed, 21 Oct 2026 07:28:00 GMT") + ); + } + + /// Two spaces a level; an empty object or array stays on its line; what a string holds is + /// left alone. + #[test] + fn json_is_laid_out_two_spaces_a_level() { + let pretty = pretty_json( + r#"{"a":[1,{"b":"x, y: {z}"}],"empty":{ },"none":[ ],"q":"say \"hi, you: {x}\" now"}"#, + ) + .unwrap(); + + assert_eq!( + pretty, + "{\n \"a\": [\n 1,\n {\n \"b\": \"x, y: {z}\"\n }\n ],\n \"empty\": {},\n \"none\": [],\n \"q\": \"say \\\"hi, you: {x}\\\" now\"\n}" + ); + } + + /// Its tokens copied as they came: re-serialising would round a number past `f64` and write + /// `1.10` as `1.1`. + #[test] + fn json_laid_out_keeps_its_numbers_as_written() { + let pretty = pretty_json("[12345678901234567890, 1.10, -0e5]").unwrap(); + + assert_eq!(pretty, "[\n 12345678901234567890,\n 1.10,\n -0e5\n]"); + } + + #[test] + fn what_is_not_json_is_not_laid_out_and_a_lone_value_is_bare() { + assert_eq!(pretty_json("{\"a\":"), None); + assert_eq!(pretty_json("plain text"), None); + assert_eq!(pretty_json(" 42 ").as_deref(), Some("42")); + } } diff --git a/crates/engine/src/http/search.rs b/crates/engine/src/http/search.rs index 2fd253e1a..0fc1c8d39 100644 --- a/crates/engine/src/http/search.rs +++ b/crates/engine/src/http/search.rs @@ -80,17 +80,22 @@ pub fn rank(candidates: Vec, search: &str) -> Vec { mod tests { use super::*; - fn candidate(name: &str, url: &str, place: &[&str], minutes: i64) -> Candidate { + fn at(hours: i64) -> DateTime { + crate::db::iso8601::parse("2026-07-25T09:00:00.000Z").unwrap() + + chrono::TimeDelta::hours(hours) + } + + fn candidate(name: &str, url: &str, place: &[&str], edited: i64) -> Candidate { Candidate { hit: RequestHit { - id: name.to_string(), + id: name.to_lowercase(), name: name.to_string(), kind: RequestKind::Http, method: HttpMethod::Get, url: url.to_string(), place: place.iter().map(ToString::to_string).collect(), }, - updated_at: DateTime::UNIX_EPOCH + chrono::Duration::minutes(minutes), + updated_at: at(edited), } } @@ -98,76 +103,57 @@ mod tests { hits.iter().map(|hit| hit.name.as_str()).collect() } - fn library() -> Vec { - vec![ - candidate( - "Lister les factures", - "{{baseUrl}}/invoices", - &["API Paiements", "Factures"], - 1, - ), - candidate( - "Facture par id", - "{{baseUrl}}/invoices/{{id}}", - &["API Paiements", "Factures"], - 2, - ), - candidate( - "Login", - "{{baseUrl}}/auth/login", - &["API Paiements", "Auth"], - 3, - ), - candidate( - "Créer une facture", - "{{baseUrl}}/invoices", - &["API Paiements", "Factures"], - 4, - ), - candidate( - "Santé", - "https://status.exemple.fr/health", - &["Supervision"], - 5, - ), - ] - } - + /// Its name before its URL before its place, a start before a word's start before a + /// middle, case and accents aside; what holds nothing typed is left out. #[test] - fn a_name_starting_with_the_search_comes_before_a_word_of_one() { - let hits = rank(library(), "fact"); + fn a_request_is_ranked_by_where_what_was_typed_stands() { + let candidates = vec![ + candidate("Shop orders", "{{base}}/list", &["Shop"], 0), + candidate("Ordered items", "/items", &["Shop"], 0), + candidate("List all", "/orders", &["Shop"], 0), + candidate("Reorder", "/re", &["Shop"], 0), + candidate("Health", "/health", &["Shop", "Commandes Order"], 0), + candidate("Unrelated", "/x", &["Shop"], 0), + ]; + + let hits = rank(candidates, " ÓRDER "); assert_eq!( names(&hits), - ["Facture par id", "Créer une facture", "Lister les factures"] + [ + "Ordered items", + "Shop orders", + "Reorder", + "List all", + "Health" + ] ); } + /// A tie goes to the one edited last, then to its name. #[test] - fn the_url_and_the_place_answer_after_the_name_accents_and_case_aside() { - assert_eq!(names(&rank(library(), "AUTH/LOG")), ["Login"]); - assert_eq!(names(&rank(library(), "supervision")), ["Santé"]); - assert_eq!(names(&rank(library(), "sante")), ["Santé"]); - } - - #[test] - fn nothing_typed_lists_the_requests_edited_last() { - let hits = rank(library(), " "); + fn a_tie_goes_to_the_request_edited_last_then_to_its_name() { + let candidates = vec![ + candidate("Login b", "/", &[], 1), + candidate("Login a", "/", &[], 1), + candidate("Login new", "/", &[], 5), + ]; - assert_eq!(names(&hits)[..2], ["Santé", "Créer une facture"]); - } + let hits = rank(candidates, "login"); - #[test] - fn a_search_answering_nothing_answers_nothing() { - assert!(rank(library(), "graphql").is_empty()); + assert_eq!(names(&hits), ["Login new", "Login a", "Login b"]); } + /// Nothing typed lists the requests edited last, as many as fit beside the rest. #[test] - fn no_more_than_the_palette_shows() { - let many = (0..20) - .map(|index| candidate(&format!("GET {index}"), "/", &["C"], index)) + fn nothing_typed_lists_the_requests_edited_last_up_to_the_most_shown() { + let candidates: Vec = (0..10) + .map(|hour| candidate(&format!("Request {hour}"), "/", &[], hour)) .collect(); - assert_eq!(rank(many, "get").len(), MAX_HITS); + let hits = rank(candidates, " "); + + assert_eq!(hits.len(), MAX_HITS); + assert_eq!(names(&hits)[..2], ["Request 9", "Request 8"]); } } From c5f41180a410c740bc132cb7c03fed380b78ffbc Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:53:31 +0100 Subject: [PATCH 36/95] HTTP cookies: unit tests rewritten for the jar (#1758) * Rewrite the tests of the HTTP cookie jar: setting, dates, matching, the store and the services Co-Authored-By: Claude Opus 5.5 * A second expiry that does not read, the listing by domain and a cookie that does not read, each held Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/http/cookies.rs | 479 +++++++++++-------- crates/engine/src/http/cookies/store.rs | 211 ++++++-- crates/engine/tests/commands/http_cookies.rs | 74 +++ crates/engine/tests/commands/main.rs | 1 + 4 files changed, 523 insertions(+), 242 deletions(-) create mode 100644 crates/engine/tests/commands/http_cookies.rs diff --git a/crates/engine/src/http/cookies.rs b/crates/engine/src/http/cookies.rs index 10d7b8d6e..1e1a5072e 100644 --- a/crates/engine/src/http/cookies.rs +++ b/crates/engine/src/http/cookies.rs @@ -292,7 +292,11 @@ mod tests { use super::*; fn now() -> DateTime { - "2026-10-07T12:00:00Z".parse().unwrap() + crate::db::iso8601::parse("2026-07-25T09:00:00.000Z").unwrap() + } + + fn url(text: &str) -> Url { + Url::parse(text).unwrap() } fn set_cookie(value: &str) -> KeyValue { @@ -303,253 +307,350 @@ mod tests { } } - fn set(change: Change) -> JarCookie { - match change { - Change::Set(cookie) => cookie, - Change::Remove(cookie) => panic!("removed {cookie:?}"), + /// The one change a `Set-Cookie` line makes, answered by `at`. + fn one(line: &str, at: &str) -> Option { + received(&[set_cookie(line)], &url(at), now()).pop() + } + + fn set(line: &str, at: &str) -> JarCookie { + match one(line, at) { + Some(Change::Set(cookie)) => cookie, + other => panic!("{line} at {at}: {other:?}"), + } + } + + fn cookie(name: &str, domain: &str, path: &str) -> JarCookie { + JarCookie { + name: name.to_string(), + value: name.to_uppercase(), + domain: domain.to_string(), + host_only: false, + path: path.to_string(), + expires: None, + secure: false, + http_only: false, + same_site: None, + created: Some(now()), } } + fn sent(jar: &[JarCookie], at: &str) -> Vec { + matching(jar, &url(at), now()) + .iter() + .map(|cookie| cookie.name.clone()) + .collect() + } + + /// Without attributes: for the host that set it alone, lowercased, under the directory of + /// the request's path, lasting the session; a quoted value without its quotes. #[test] - fn a_cookie_takes_its_host_and_path_unless_it_names_a_domain_above() { - let url = Url::parse("https://api.exemple.fr/v1/users").unwrap(); - let changes = received( - &[ - set_cookie("session=abc; HttpOnly; Secure"), - set_cookie("theme=dark; Domain=.EXEMPLE.fr; Path=/; Max-Age=3600; SameSite=Lax"), - set_cookie("evil=1; Domain=other.fr"), - set_cookie("old=1; Expires=Wed, 01 Oct 2025 07:28:00 GMT"), - ], - &url, - now(), - ); + fn a_cookie_without_attributes_is_the_host_s_for_its_directory() { + let cookie = set("sid=\"abc=1\"", "https://API.Shop.test/v1/users?x=1"); - assert_eq!(changes.len(), 3); - let session = set(changes[0].clone()); assert_eq!( - ( - session.domain.as_str(), - session.host_only, - session.path.as_str() - ), - ("api.exemple.fr", true, "/v1") + (cookie.name.as_str(), cookie.value.as_str()), + ("sid", "abc=1") ); - assert!(session.secure && session.http_only && session.expires.is_none()); - let theme = set(changes[1].clone()); assert_eq!( - (theme.domain.as_str(), theme.host_only), - ("exemple.fr", false) + (cookie.domain.as_str(), cookie.host_only), + ("api.shop.test", true) ); - assert_eq!(theme.expires, Some(now() + TimeDelta::hours(1))); - assert!(matches!(&changes[2], Change::Remove(cookie) if cookie.name == "old")); + assert_eq!((cookie.path.as_str(), cookie.expires), ("/v1", None)); + assert_eq!(set("a=1", "https://shop.test/users").path, "/"); + assert_eq!(set("a=1", "https://shop.test").path, "/"); + } + + /// Only `Set-Cookie`, case aside, in their order, a line naming no cookie left out; created + /// a microsecond apart, so two of one path length go back in the order they were set. + #[test] + fn an_answer_s_cookies_are_read_in_their_order() { + let headers = [ + set_cookie("first=1; HttpOnly; SameSite=Strict"), + KeyValue { + key: "Content-Type".to_string(), + value: "a=b".to_string(), + ..KeyValue::default() + }, + KeyValue { + key: "set-cookie".to_string(), + ..set_cookie("second=2; SameSite=") + }, + set_cookie("no equals sign"), + set_cookie(" =nameless"), + ]; - let plain = Url::parse("http://api.exemple.fr/").unwrap(); - assert!(received(&[set_cookie("csrf=1; Secure")], &plain, now()).is_empty()); + let changes = received(&headers, &url("https://shop.test/"), now()); + + let read: Vec = changes + .into_iter() + .map(|change| match change { + Change::Set(cookie) => cookie, + Change::Remove(cookie) => panic!("{cookie:?}"), + }) + .collect(); + let names: Vec<&str> = read.iter().map(|cookie| cookie.name.as_str()).collect(); + assert_eq!(names, ["first", "second"]); + assert_eq!( + (read[0].created, read[1].created), + (Some(now()), Some(now() + TimeDelta::microseconds(1))) + ); + assert!(read[0].http_only && !read[1].http_only); + assert_eq!( + (read[0].same_site.as_deref(), read[1].same_site.as_deref()), + (Some("Strict"), None) + ); } - /// #705: `x.co.uk` set a cookie for `co.uk`, sent to every `.co.uk` site; `127.0.0.1` one - /// for `0.0.1`. + /// A server sets a cookie for itself or a domain above it, never for another, an address, + /// or a suffix under which unrelated sites register; naming itself is host-only. #[test] - fn a_public_suffix_and_an_address_take_no_domain_above_them() { - let names = |url: &str, lines: &[&str]| -> Vec<(String, String, bool)> { - let url = Url::parse(url).unwrap(); - let headers: Vec = lines.iter().map(|line| set_cookie(line)).collect(); - received(&headers, &url, now()) - .into_iter() - .map(|change| { - let cookie = set(change); - (cookie.name, cookie.domain, cookie.host_only) - }) - .collect() - }; - let cookie = |name: &str, domain: &str, host_only: bool| { - (name.to_string(), domain.to_string(), host_only) - }; + fn a_domain_is_taken_only_at_or_above_the_host_and_below_a_public_suffix() { + let above = set("a=1; Domain=.Shop.TEST", "https://api.shop.test/"); + let itself = set("a=1; Domain=api.shop.test", "https://api.shop.test/"); + let empty = set("a=1; Domain=", "https://api.shop.test/"); + let registered = set("a=1; Domain=exemple.co.uk", "https://api.exemple.co.uk/"); assert_eq!( - names( - "https://x.co.uk/", - &["suffix=1; Domain=co.uk", "itself=1; Domain=x.co.uk"] - ), - [cookie("itself", "x.co.uk", true)] + (above.domain.as_str(), above.host_only), + ("shop.test", false) ); assert_eq!( - names( - "https://api.exemple.co.uk/", - &[ - "registered=1; Domain=exemple.co.uk", - "pages=1; Domain=github.io" - ] - ), - [cookie("registered", "exemple.co.uk", false)] + (itself.domain.as_str(), itself.host_only), + ("api.shop.test", true) ); - assert!(names("https://ada.github.io/", &["all=1; Domain=github.io"]).is_empty()); + assert!(empty.host_only); assert_eq!( - names( - "http://127.0.0.1:8080/", - &["above=1; Domain=0.0.1", "named=1; Domain=127.0.0.1"] - ), - [cookie("named", "127.0.0.1", true)] + (registered.domain.as_str(), registered.host_only), + ("exemple.co.uk", false) ); + for (line, at) in [ + ("a=1; Domain=other.test", "https://shop.test/"), + ("a=1; Domain=api.shop.test", "https://shop.test/"), + ("a=1; Domain=hop.test", "https://shop.test/"), + ("a=1; Domain=co.uk", "https://shop.co.uk/"), + ("a=1; Domain=github.io", "https://me.github.io/"), + ("a=1; Domain=test", "https://shop.test/"), + ("a=1; Domain=0.1", "http://127.0.0.1/"), + ] { + assert_eq!(one(line, at), None, "{line} at {at}"); + } + assert!(set("a=1; Domain=127.0.0.1", "http://127.0.0.1/").host_only); + } + + /// A path that does not start with `/` is ignored for the default one. + #[test] + fn a_path_is_taken_only_when_it_starts_with_a_slash() { + assert_eq!(set("a=1; Path=/api", "https://shop.test/v1/x").path, "/api"); + assert_eq!(set("a=1; Path=api", "https://shop.test/v1/x").path, "/v1"); } - /// Headers are decoded lossily: a date may hold anything. + /// As browsers do: a plain connection cannot set what only a secure one may read. #[test] - fn an_expiry_in_accented_letters_is_no_date() { - assert_eq!(cookie_date("éé"), None); - assert_eq!(cookie_date("21 éé 2026"), None); + fn a_secure_cookie_is_set_only_over_a_secure_connection() { + assert!(set("a=1; Secure", "https://shop.test/").secure); + assert!(set("a=1; Secure", "wss://shop.test/").secure); + assert_eq!(one("a=1; Secure", "http://shop.test/"), None); + assert_eq!(one("a=1; Secure", "ws://shop.test/"), None); } - /// #705: RFC 850 and asctime were read as no date at all, and the cookie lived the session. + /// `Max-Age` counts from now and wins over `Expires`, whichever comes first; zero or less, + /// or an expiry past, removes; a `Max-Age` that is no number, or a second `Expires` that + /// does not read, is ignored. #[test] - fn an_expiry_is_read_in_every_format_servers_write() { - let at = |text: &str| cookie_date(text).map(|date| date.to_rfc3339()); - let expected = Some("2026-10-21T07:28:00+00:00".to_string()); - - assert_eq!(at("Wed, 21 Oct 2026 07:28:00 GMT"), expected); - assert_eq!(at("Wednesday, 21-Oct-26 07:28:00 GMT"), expected); - assert_eq!(at("Wed Oct 21 07:28:00 2026"), expected); - assert_eq!(at("21-Oct-2026 07:28:00 GMT"), expected); + fn an_expiry_counts_from_now_or_removes_the_cookie() { + let in_a_minute = Some(now() + TimeDelta::seconds(60)); + + assert_eq!( + set( + "a=1; Max-Age=60; Expires=Wed, 21 Oct 2026 07:28:00 GMT", + "https://shop.test/" + ) + .expires, + in_a_minute + ); assert_eq!( - at("Thu, 01-Jan-70 00:00:01 GMT"), - Some("1970-01-01T00:00:01+00:00".to_string()) + set( + "a=1; Expires=Wed, 21 Oct 2026 07:28:00 GMT; Max-Age=60", + "https://shop.test/" + ) + .expires, + in_a_minute ); + assert_eq!(set("a=1; Max-Age=soon", "https://shop.test/").expires, None); + let october = crate::db::iso8601::parse("2026-10-21T07:28:00.000Z").ok(); assert_eq!( - at("Sun, 01-Jan-69 00:00:01 GMT"), - Some("2069-01-01T00:00:01+00:00".to_string()) + set( + "a=1; Expires=Wed, 21 Oct 2026 07:28:00 GMT; Expires=garbage", + "https://shop.test/" + ) + .expires, + october ); - for unreadable in [ - "", - "tomorrow", - "Wed, 32 Oct 2026 07:28:00 GMT", - "21 Oct 2026", + for line in [ + "a=1; Max-Age=0", + "a=1; Max-Age=-5", + "a=1; Expires=Thu, 01 Jan 2026 00:00:00 GMT", ] { - assert_eq!(at(unreadable), None, "{unreadable}"); + assert!( + matches!(one(line, "https://shop.test/"), Some(Change::Remove(_))), + "{line}" + ); } + } - let url = Url::parse("https://exemple.fr/").unwrap(); - let change = received( - &[set_cookie("a=1; Expires=Wednesday, 21-Oct-26 07:28:00 GMT")], - &url, - now(), - ); - assert_eq!( - set(change[0].clone()).expires.map(|date| date.to_rfc3339()), - expected - ); + /// Dates as servers write them, read token by token, a two-digit year taken to 1970–2069; + /// one that does not read — accented letters included, which once broke the reading — lasts + /// the session. + #[test] + fn an_expiry_is_read_in_every_form_servers_write() { + let october = crate::db::iso8601::parse("2026-10-21T07:28:00.000Z").ok(); + for (date, expected) in [ + ("Wed, 21 Oct 2026 07:28:00 GMT", october), + ("Wednesday, 21-Oct-26 07:28:00 GMT", october), + ("Wed Oct 21 07:28:00 2026", october), + ("21 october 2026 7:28:0", october), + ( + "Sun, 01-Jan-69 00:00:01 GMT", + crate::db::iso8601::parse("2069-01-01T00:00:01.000Z").ok(), + ), + ("mér., 21 oct. 2026 07:28:00", october), + ("Wed, 21 Oct 2026 25:00:00 GMT", None), + ("Wed, 31 Feb 2026 07:28:00 GMT", None), + ("Wed, 21 Oct 1600 07:28:00 GMT", None), + ("Wed, 21 Oct 207 07:28:00 GMT", None), + ("éèà", None), + ("tomorrow", None), + ("21 Oct 2026", None), + ("21 éé 2026 07:28:00", None), + ] { + let read = set(&format!("a=1; Expires={date}"), "https://shop.test/"); + + assert_eq!(read.expires, expected, "{date}"); + } + assert!(matches!( + one( + "a=1; Expires=Thu, 01-Jan-70 00:00:01 GMT", + "https://shop.test/" + ), + Some(Change::Remove(_)) + )); } - /// #705: two paths of one length came out in the order the jar was read, a random id's. + /// The same name, domain and path is the same cookie: replaced, keeping its first creation; + /// a removal takes it away; another path is another cookie. #[test] - fn of_two_paths_of_one_length_the_older_cookie_goes_first_and_a_replacement_keeps_its_age() { - let url = Url::parse("https://exemple.fr/").unwrap(); - let mut jar = Vec::new(); - apply( - &mut jar, - &received(&[set_cookie("first=1; Path=/")], &url, now()), - ); + fn a_change_replaces_or_removes_the_same_cookie() { + let mut jar = vec![ + cookie("a", "shop.test", "/"), + cookie("a", "shop.test", "/api"), + ]; + let newer = JarCookie { + value: "new".to_string(), + created: Some(now() + TimeDelta::hours(1)), + ..cookie("a", "shop.test", "/") + }; + apply( &mut jar, - &received( - &[ - set_cookie("second=1; Path=/"), - set_cookie("third=1; Path=/"), - ], - &url, - now() + TimeDelta::seconds(1), - ), + &[ + Change::Set(newer), + Change::Set(cookie("b", "shop.test", "/")), + ], ); - // Read back in another order, as the store may. - jar.reverse(); + assert_eq!(jar.len(), 3); + let replaced = jar + .iter() + .find(|known| known.path == "/" && known.name == "a") + .unwrap(); assert_eq!( - header_for(&jar, &url, now()).as_deref(), - Some("first=1; second=1; third=1") + (replaced.value.as_str(), replaced.created), + ("new", Some(now())) ); apply( &mut jar, - &received( - &[set_cookie("first=2; Path=/")], - &url, - now() + TimeDelta::seconds(2), - ), - ); - assert_eq!( - header_for(&jar, &url, now()).as_deref(), - Some("first=2; second=1; third=1") + &[Change::Remove(cookie("a", "shop.test", "/api"))], ); + let left: Vec<(&str, &str)> = jar + .iter() + .map(|known| (known.name.as_str(), known.path.as_str())) + .collect(); + assert_eq!(left, [("a", "/"), ("b", "/")]); } + /// A host-only cookie to its host alone; a domain cookie to the domain and below it, never + /// to a name that merely ends like it. #[test] - fn a_jar_in_memory_takes_a_cookie_replaces_it_and_lets_it_go() { - let url = Url::parse("http://api.exemple.fr/login").unwrap(); - let mut jar = Vec::new(); - let line = |jar: &[JarCookie]| header_for(jar, &url, now()); + fn a_cookie_is_sent_to_its_host_or_below_its_domain() { + let jar = [ + JarCookie { + host_only: true, + ..cookie("host", "shop.test", "/") + }, + cookie("domain", "shop.test", "/"), + ]; - apply( - &mut jar, - &received(&[set_cookie("session=abc; Path=/")], &url, now()), - ); - assert_eq!(line(&jar).as_deref(), Some("session=abc")); + assert_eq!(sent(&jar, "https://shop.test/"), ["host", "domain"]); + assert_eq!(sent(&jar, "https://API.shop.test/"), ["domain"]); + assert!(sent(&jar, "https://evilshop.test/").is_empty()); + assert!(sent(&jar, "data:text/plain,x").is_empty()); + } - apply( - &mut jar, - &received( - &[ - set_cookie("session=def; Path=/"), - set_cookie("theme=dark; Path=/"), - ], - &url, - now(), - ), - ); - assert_eq!(line(&jar).as_deref(), Some("session=def; theme=dark")); + /// A path and what lies under it, never a name that merely starts like it. + #[test] + fn a_cookie_is_sent_under_its_path() { + let jar = [ + cookie("api", "shop.test", "/api"), + cookie("slash", "shop.test", "/v1/"), + ]; - apply( - &mut jar, - &received(&[set_cookie("session=; Path=/; Max-Age=0")], &url, now()), - ); - assert_eq!(line(&jar).as_deref(), Some("theme=dark")); + assert_eq!(sent(&jar, "https://shop.test/api"), ["api"]); + assert_eq!(sent(&jar, "https://shop.test/api/users"), ["api"]); + assert!(sent(&jar, "https://shop.test/apix").is_empty()); + assert_eq!(sent(&jar, "https://shop.test/v1/x"), ["slash"]); + assert!(sent(&jar, "https://shop.test/v1").is_empty()); } + /// Neither an expired cookie nor, over a plain connection, a secure one. #[test] - fn a_request_carries_what_matches_its_host_path_and_scheme_the_longest_paths_first() { - let cookie = - |name: &str, domain: &str, host_only: bool, path: &str, secure: bool| JarCookie { - name: name.to_string(), - value: "v".to_string(), - domain: domain.to_string(), - host_only, - path: path.to_string(), - expires: None, - secure, - http_only: false, - same_site: None, - created: None, - }; - let jar = vec![ - cookie("root", "exemple.fr", false, "/", false), - cookie("api", "api.exemple.fr", true, "/v1", false), - cookie("secure", "exemple.fr", false, "/", true), - cookie("elsewhere", "other.fr", false, "/", false), - cookie("sibling", "exemple.fr", true, "/", false), + fn an_expired_or_secure_cookie_is_held_back() { + let jar = [ + JarCookie { + expires: Some(now()), + ..cookie("expired", "shop.test", "/") + }, JarCookie { - expires: Some(now() - TimeDelta::seconds(1)), - ..cookie("gone", "exemple.fr", false, "/", false) + expires: Some(now() + TimeDelta::seconds(1)), + ..cookie("later", "shop.test", "/") + }, + JarCookie { + secure: true, + ..cookie("secure", "shop.test", "/") }, ]; - let plain = Url::parse("http://api.exemple.fr/v1/users").unwrap(); - assert_eq!( - header_for(&jar, &plain, now()).as_deref(), - Some("api=v; root=v") - ); - let secure = Url::parse("https://api.exemple.fr/v10").unwrap(); + assert_eq!(sent(&jar, "http://shop.test/"), ["later"]); + assert_eq!(sent(&jar, "https://shop.test/"), ["later", "secure"]); + assert_eq!(sent(&jar, "wss://shop.test/"), ["later", "secure"]); + } + + /// The longest paths first and, of two paths of one length, the older first; one header, + /// or none. + #[test] + fn the_cookie_header_sends_the_longest_paths_first_then_the_oldest() { + let jar = [ + JarCookie { + created: Some(now() + TimeDelta::seconds(2)), + ..cookie("young", "shop.test", "/") + }, + cookie("old", "shop.test", "/"), + cookie("deep", "shop.test", "/api"), + ]; + assert_eq!( - header_for(&jar, &secure, now()).as_deref(), - Some("root=v; secure=v") + header_for(&jar, &url("https://shop.test/api/x"), now()).as_deref(), + Some("deep=DEEP; old=OLD; young=YOUNG") ); - let other = Url::parse("https://nowhere.fr/").unwrap(); - assert_eq!(header_for(&jar, &other, now()), None); + assert_eq!(header_for(&jar, &url("https://other.test/"), now()), None); } } diff --git a/crates/engine/src/http/cookies/store.rs b/crates/engine/src/http/cookies/store.rs index de5407a8b..04cad0e50 100644 --- a/crates/engine/src/http/cookies/store.rs +++ b/crates/engine/src/http/cookies/store.rs @@ -171,83 +171,188 @@ mod tests { use super::*; use chrono::TimeDelta; - fn cookie(name: &str, domain: &str, value: &str) -> JarCookie { + fn now() -> DateTime { + iso8601::parse("2026-07-25T09:00:00.000Z").unwrap() + } + + fn cookie(name: &str, domain: &str, path: &str) -> JarCookie { JarCookie { name: name.to_string(), - value: value.to_string(), + value: format!("{name}-value"), domain: domain.to_string(), - host_only: false, - path: "/".to_string(), + host_only: true, + path: path.to_string(), expires: None, secure: false, http_only: false, same_site: None, - created: None, + created: Some(now()), } } - #[test] - fn a_cookie_set_again_replaces_itself_and_one_expired_goes() { + fn lasting(name: &str, seconds: i64) -> JarCookie { + JarCookie { + expires: Some(now() + TimeDelta::seconds(seconds)), + ..cookie(name, "shop.test", "/") + } + } + + fn names(jar: &[JarCookie]) -> Vec<&str> { + let mut names: Vec<&str> = jar.iter().map(|cookie| cookie.name.as_str()).collect(); + names.sort_unstable(); + names + } + + /// Written an hour ago: what expires by now is still in the table. + fn library_with(cookies: &[JarCookie]) -> Library { let mut library = crate::db::open_in_memory().unwrap(); - let now: DateTime = "2026-10-07T12:00:00Z".parse().unwrap(); - apply( - &mut library, - &[ - Change::Set(cookie("session", "a.fr", "1")), - Change::Set(cookie("theme", "a.fr", "dark")), - Change::Set(JarCookie { - expires: Some(now + TimeDelta::seconds(10)), - ..cookie("brief", "b.fr", "x") - }), - ], - now, - ) - .unwrap(); + let changes: Vec = cookies.iter().cloned().map(Change::Set).collect(); + apply(&mut library, &changes, now() - TimeDelta::hours(1)).unwrap(); + library + } + + /// The same cookie is replaced, keeping its place among those of its path; a removal takes + /// it away; what has expired by now goes as the changes are written. + #[test] + fn an_answer_s_changes_replace_remove_and_sweep_the_jar() { + let mut library = library_with(&[ + cookie("a", "shop.test", "/"), + lasting("short", 10), + cookie("b", "shop.test", "/"), + ]); + let newer = JarCookie { + value: "new".to_string(), + created: Some(now() + TimeDelta::hours(1)), + ..cookie("a", "shop.test", "/") + }; + + let later = now() + TimeDelta::seconds(10); apply( &mut library, &[ - Change::Set(cookie("session", "a.fr", "2")), - Change::Remove(cookie("theme", "a.fr", "")), + Change::Set(newer), + Change::Remove(cookie("b", "shop.test", "/")), ], - now + TimeDelta::seconds(20), + later, ) .unwrap(); - let domains = by_domain(&mut library).unwrap(); - assert_eq!(domains.len(), 1); - assert_eq!(domains[0].cookies.len(), 1); - assert_eq!(domains[0].cookies[0].cookie.value, "2"); - assert_eq!(jar(&mut library, now).unwrap().len(), 1); + let jar = jar(&mut library, now()).unwrap(); + assert_eq!(names(&jar), ["a"]); + assert_eq!( + (jar[0].value.as_str(), jar[0].created), + ("new", Some(now())) + ); + assert_eq!(count(&mut library).unwrap(), 1); + } + + /// What has expired is never sent, even before a write sweeps it. + #[test] + fn the_jar_read_leaves_out_what_has_expired() { + let mut library = library_with(&[ + lasting("expired", 0), + lasting("later", 1), + cookie("session", "shop.test", "/"), + ]); + + let jar = jar(&mut library, now()).unwrap(); + + assert_eq!(names(&jar), ["later", "session"]); + } + + /// No change writes nothing, and sweeps nothing either. + #[test] + fn no_change_writes_nothing() { + let mut library = library_with(&[lasting("expired", 0)]); + + apply(&mut library, &[], now() + TimeDelta::hours(1)).unwrap(); - apply(&mut library, &[Change::Set(cookie("x", "b.fr", "1"))], now).unwrap(); - assert_eq!(delete_domain(&mut library, "a.fr").unwrap(), 1); - let id = by_domain(&mut library).unwrap()[0].cookies[0].id.clone(); - assert_eq!(delete(&mut library, &id).unwrap(), 1); + assert_eq!(count(&mut library).unwrap(), 1); + } + + /// What the manager lists: by domain, then name, then path. + #[test] + fn the_jar_is_listed_by_domain_then_name() { + let mut library = library_with(&[ + cookie("a", "b.test", "/"), + cookie("b", "a.test", "/x"), + cookie("b", "a.test", "/"), + cookie("a", "a.test", "/"), + ]); + + let listed = by_domain(&mut library).unwrap(); + + let shown: Vec<(&str, Vec<(&str, &str)>)> = listed + .iter() + .map(|domain| { + let cookies = domain + .cookies + .iter() + .map(|stored| (stored.cookie.name.as_str(), stored.cookie.path.as_str())) + .collect(); + (domain.domain.as_str(), cookies) + }) + .collect(); + assert_eq!( + shown, + [ + ("a.test", vec![("a", "/"), ("b", "/"), ("b", "/x")]), + ("b.test", vec![("a", "/")]), + ] + ); + } + + /// One cookie, a domain's, or all of them, each answering how many went. + #[test] + fn cookies_are_deleted_one_a_domain_or_all_at_once() { + let mut library = library_with(&[ + cookie("a", "a.test", "/"), + cookie("b", "a.test", "/"), + cookie("c", "b.test", "/"), + cookie("d", "c.test", "/"), + ]); + let one = by_domain(&mut library).unwrap()[2].cookies[0].id.clone(); + + assert_eq!(delete(&mut library, &one).unwrap(), 1); + assert_eq!(delete(&mut library, &one).unwrap(), 0); + assert_eq!(delete_domain(&mut library, "a.test").unwrap(), 2); + assert_eq!(count(&mut library).unwrap(), 1); + assert_eq!(clear(&mut library).unwrap(), 1); assert_eq!(count(&mut library).unwrap(), 0); } - /// As the jar held in memory does: a cookie set again keeps its place among those sent. + /// A cookie that does not read fails the jar rather than vanishing from it. #[test] - fn a_cookie_set_again_keeps_when_it_was_first_made() { - let mut library = crate::db::open_in_memory().unwrap(); - let now: DateTime = "2026-10-07T12:00:00Z".parse().unwrap(); - let at = |seconds| Some(now + TimeDelta::seconds(seconds)); - let first = JarCookie { - created: at(0), - ..cookie("session", "a.fr", "1") - }; - let again = JarCookie { - created: at(5), - ..cookie("session", "a.fr", "2") - }; - apply(&mut library, &[Change::Set(first.clone())], now).unwrap(); - apply(&mut library, &[Change::Set(again.clone())], now).unwrap(); + fn a_cookie_that_does_not_read_is_named_as_such() { + let mut library = library_with(&[cookie("a", "shop.test", "/")]); + let garbage = library.vault().seal("not json").unwrap(); + diesel::update(http_cookies::table) + .set(http_cookies::cookie.eq(garbage)) + .execute(library.db()) + .unwrap(); - let mut held = vec![first]; - crate::http::cookies::apply(&mut held, &[Change::Set(again)]); - let stored = jar(&mut library, now).unwrap(); + assert!(matches!( + jar(&mut library, now()), + Err(StorageError::CorruptRow { + field: "cookie", + .. + }) + )); + } + + /// Sealed whole: neither a name nor a value, nor its domain, is in the database in the clear. + #[test] + fn a_cookie_is_sealed_whole() { + let mut library = library_with(&[cookie("session_id", "bank.test", "/")]); - assert_eq!(stored[0].created, held[0].created); - assert_eq!(stored[0].created, at(0)); + let stored: Vec = http_cookies::table + .select(http_cookies::cookie) + .load(library.db()) + .unwrap(); + + assert_eq!(stored.len(), 1); + for clear in ["session_id", "bank.test"] { + assert!(!stored[0].contains(clear), "{clear} in the clear"); + } } } diff --git a/crates/engine/tests/commands/http_cookies.rs b/crates/engine/tests/commands/http_cookies.rs new file mode 100644 index 000000000..12bc6af41 --- /dev/null +++ b/crates/engine/tests/commands/http_cookies.rs @@ -0,0 +1,74 @@ +use chrono::Utc; +use engine::error::ErrorCode; +use engine::http::cookies::{Change, JarCookie, store}; +use engine::http::{ + clear_http_cookies, count_http_cookies, delete_http_cookie, delete_http_cookie_domain, + http_cookies, +}; + +use super::{Session, code}; + +fn cookie(name: &str, domain: &str) -> JarCookie { + JarCookie { + name: name.to_string(), + value: "v".to_string(), + domain: domain.to_string(), + host_only: true, + path: "/".to_string(), + expires: None, + secure: false, + http_only: false, + same_site: None, + created: None, + } +} + +/// A jar as answers leave it. +fn with_jar(cookies: &[JarCookie]) -> Session { + let session = Session::open(); + let changes: Vec = cookies.iter().cloned().map(Change::Set).collect(); + let mut db = session.engine.db().lock().unwrap(); + store::apply(db.as_mut().unwrap(), &changes, Utc::now()).unwrap(); + drop(db); + + session +} + +#[test] +fn the_jar_answers_locked_before_a_library_is_open() { + let session = Session::locked(); + + assert_eq!(code(session.call(http_cookies)), ErrorCode::Locked); + assert_eq!(code(session.call(count_http_cookies)), ErrorCode::Locked); + assert_eq!(code(session.call(clear_http_cookies)), ErrorCode::Locked); +} + +/// The manager lists the jar by domain, and empties it a cookie, a domain or all at once, +/// each answering how many went. +#[test] +fn the_manager_lists_the_jar_and_empties_it() { + let session = with_jar(&[ + cookie("a", "a.test"), + cookie("b", "a.test"), + cookie("c", "b.test"), + cookie("d", "c.test"), + ]); + let domains = session.call(http_cookies).unwrap(); + let listed: Vec<&str> = domains + .iter() + .map(|domain| domain.domain.as_str()) + .collect(); + assert_eq!(listed, ["a.test", "b.test", "c.test"]); + let one = domains[1].cookies[0].id.clone(); + + assert_eq!(session.call(|e| delete_http_cookie(e, &one)).unwrap(), 1); + assert_eq!( + session + .call(|e| delete_http_cookie_domain(e, "a.test")) + .unwrap(), + 2 + ); + assert_eq!(session.call(count_http_cookies).unwrap(), 1); + assert_eq!(session.call(clear_http_cookies).unwrap(), 1); + assert!(session.call(http_cookies).unwrap().is_empty()); +} diff --git a/crates/engine/tests/commands/main.rs b/crates/engine/tests/commands/main.rs index 7016769f0..0f00e251f 100644 --- a/crates/engine/tests/commands/main.rs +++ b/crates/engine/tests/commands/main.rs @@ -23,6 +23,7 @@ mod backups; mod concurrency; mod folders; mod http; +mod http_cookies; mod http_environments; mod http_runner; mod http_scripts; From 8556a49910dea0ec1cbb10f0556d91b543a10259 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 17:01:02 +0100 Subject: [PATCH 37/95] GraphQL: unit tests rewritten for queries, variables and answers (#1760) Co-authored-by: Claude Opus 5.5 --- crates/engine/src/http/graphql.rs | 321 +++++++++++++++--------------- 1 file changed, 162 insertions(+), 159 deletions(-) diff --git a/crates/engine/src/http/graphql.rs b/crates/engine/src/http/graphql.rs index ada327de8..840a66d12 100644 --- a/crates/engine/src/http/graphql.rs +++ b/crates/engine/src/http/graphql.rs @@ -475,204 +475,207 @@ pub fn result(body: &str) -> Option { mod tests { use super::*; + fn document(query: &str, variables: &str, operation: Option<&str>) -> GraphqlDocument { + GraphqlDocument { + query: query.to_string(), + variables: variables.to_string(), + operation_name: operation.map(ToString::to_string), + as_get: false, + } + } + + fn problem(query: &str) -> Option<(QueryFault, u32, u32)> { + describe(&document(query, "", None)) + .query_problem + .map(|problem| (problem.fault, problem.line, problem.column)) + } + + /// Named ones, in the order written, read past strings, comments and selections; an + /// anonymous one or the shorthand has no name to list. #[test] - fn the_named_operations_are_read_past_strings_comments_and_selections() { + fn the_operations_of_a_document_are_read_in_order() { let query = r#" # query Commented { x } - query Invoices($first: Int) { invoices(first: $first, note: "mutation Fake") { id } } - mutation Pay { pay { id } } - { anonymous } - subscription - Ticks { tick } + query Orders($first: Int) { orders(note: "mutation Fake { }") { id } } + fragment Fields on Order { id } + mutation Pay { pay } + subscription Ticks { tick } + query { anonymous } + { shorthand } "#; - assert_eq!(operations(query), ["Invoices", "Pay", "Ticks"]); - assert!(operations("{ me { id } }").is_empty()); - assert_eq!(scan(query).problem, None); - // A block string runs over lines, quotes and braces included. - let described = r#" - """ - Says "hello" { and more - """ - query Greeting { hello(note: "a \" b") } - "#; - assert_eq!(operations(described), ["Greeting"]); - assert_eq!(scan(described).problem, None); + assert_eq!(operations(query), ["Orders", "Pay", "Ticks"]); } - fn document(query: &str, variables: &str) -> GraphqlDocument { - GraphqlDocument { - query: query.to_string(), - variables: variables.to_string(), - ..GraphqlDocument::default() + /// Said where it is typed — the sign at fault, by line and column from 1 — and the first + /// one only; what is left open at the end is the innermost. + #[test] + fn a_sign_the_query_leaves_unpaired_is_said_where_it_stands() { + for (query, expected) in [ + ("{ a { b }", Some((QueryFault::UnclosedBrace, 1, 1))), + ( + "query Q {\n a(x: 1 {\n}", + Some((QueryFault::UnclosedParenthesis, 2, 4)), + ), + ("{ a(x: \"open) }", Some((QueryFault::UnclosedString, 1, 8))), + ("{ a }\n}", Some((QueryFault::StrayBrace, 2, 1))), + ("{ a(x: 1}) }", Some((QueryFault::StrayBrace, 1, 9))), + ("{ a ) }", Some((QueryFault::StrayParenthesis, 1, 5))), + ("{ a(x: \"\"\"one\ntwo \\\"\"\" three\"\"\") }", None), + ( + "{ a(x: \"\"\"never closed) }", + Some((QueryFault::UnclosedString, 1, 8)), + ), + ( + "{ a(x: \"quote \\\" inside\") } # } stray in a comment", + None, + ), + ("{ a(x: \"\") }", None), + ] { + assert_eq!(problem(query), expected, "{query:?}"); } } - /// A query missing a brace was sent without a word, and answered by a 400. + /// What the operation sent declares without a default and the variables give no value; the + /// keys given that it does not declare. #[test] - fn a_brace_a_parenthesis_or_a_string_left_open_is_said_with_its_place() { - let problem = |query: &str| { - scan(query) - .problem - .map(|found| (found.fault, found.line, found.column)) - }; + fn the_variables_say_what_the_operation_lacks_and_what_it_does_not_take() { + let query = + "query Orders($first: Int = 10, $after: String, $status: Status!) { orders { id } }"; + let answer = describe(&document(query, r#"{"status": "PAID", "extra": 1}"#, None)); + + assert_eq!(answer.operations, ["Orders"]); + assert_eq!(answer.missing, ["after"]); + assert_eq!(answer.unknown, ["extra"]); assert_eq!( - problem("query {\n viewer {\n login\n }\n"), - Some((QueryFault::UnclosedBrace, 1, 7)) - ); - // The innermost one, nearest to where the typing stopped. - assert_eq!( - problem("{ viewer {\n repos(first: 3 {"), - Some((QueryFault::UnclosedBrace, 2, 18)) - ); - assert_eq!( - problem("{ user(id: 1 }"), - Some((QueryFault::StrayBrace, 1, 14)) - ); - assert_eq!( - problem("{ user(id: 1) ) }"), - Some((QueryFault::StrayParenthesis, 1, 15)) - ); - assert_eq!(problem("{ user }\n}"), Some((QueryFault::StrayBrace, 2, 1))); - assert_eq!( - problem("{ search(text: \"open) { id }\n}"), - Some((QueryFault::UnclosedString, 1, 16)) - ); - assert_eq!( - problem("{ a }\n\"\"\"never closed"), - Some((QueryFault::UnclosedString, 2, 1)) - ); - assert_eq!( - problem("{ user(id: 1"), - Some((QueryFault::UnclosedParenthesis, 1, 7)) + (answer.variables_problem, answer.query_problem), + (None, None) ); - // A sign in a comment or in a string pairs with nothing. - assert_eq!(problem("{ a(note: \"}\") } # }"), None); - assert_eq!(problem(""), None); } - /// The variables were typed after the query, in its box: nothing said what goes where. + /// The operation named, or the first as the server takes it; a variable used in a selection + /// or an argument is no declaration. #[test] - fn the_variables_an_operation_declares_are_compared_with_those_given() { - let query = r" - query Country($code: ID!, $first: Int = 10, $after: String) { - country(code: $code) { cities(first: $first, after: $after) { name } } - } - mutation Rename($id: ID!, $name: String!) { rename(id: $id, name: $name) { id } } - "; - let said = |variables: &str, operation: Option<&str>| { - let answer = describe(&GraphqlDocument { - operation_name: operation.map(str::to_string), - ..document(query, variables) - }); - (answer.missing, answer.unknown) - }; - let names = |names: &[&str]| names.iter().map(ToString::to_string).collect::>(); + fn the_variables_are_judged_against_the_operation_sent() { + let query = "query A($a: Int) { x(v: $inside) }\nquery B($b: Int) { y }"; - // Without a default and without a value; the first operation when none is named. - assert_eq!(said("", None), (names(&["code", "after"]), names(&[]))); - assert_eq!( - said(r#"{ "code": "FR", "page": 2 }"#, None), - (names(&["after"]), names(&["page"])) - ); - assert_eq!( - said(r#"{"id": 1}"#, Some("Rename")), - (names(&["name"]), names(&[])) - ); + let named = describe(&document(query, "{}", Some("B"))); + let first = describe(&document(query, "{}", None)); + let unknown_name = describe(&document(query, "{}", Some("Nope"))); + let blank_name = describe(&document(query, "{}", Some(""))); + + assert_eq!(named.missing, ["b"]); + for answer in [first, unknown_name, blank_name] { + assert_eq!(answer.missing, ["a"]); + } + } + + /// Variables that are no object as typed are said for what they are, not as values lacking; + /// none typed is none given. + #[test] + fn variables_that_do_not_read_are_said_as_such() { + let query = "query Q($id: ID!) { node(id: $id) { id } }"; + + let broken = describe(&document(query, "{\"id\": ", None)); + let array = describe(&document(query, "[1]", None)); + let empty = describe(&document(query, " ", None)); + + assert!(broken.variables_problem.is_some()); + assert!(broken.missing.is_empty() && array.missing.is_empty()); + assert_eq!(array.variables_problem, None); assert_eq!( - said(r#"{"id": 1}"#, Some("Gone")), - (names(&["code", "after"]), names(&["id"])) + (empty.variables_problem, empty.missing), + (None, vec!["id".to_string()]) ); - // Not an object as typed: said as that, not as a list of what is missing. - assert_eq!(said("{\"code\":", None), (names(&[]), names(&[]))); - assert_eq!(said("[1]", None), (names(&[]), names(&[]))); - - // The shorthand and a fragment declare nothing; no operation, nothing is compared. - let shorthand = describe(&document( - "fragment F on User { id } { me { ...F } }", - r#"{"a": 1}"#, + } + + /// A `null` for each value lacking, written at the end of the object as typed — nothing + /// else of it touched, its numbers least of all — or a new object. + #[test] + fn the_values_lacking_are_added_as_null_at_the_end_of_the_object() { + let query = "query Q($a: Int, $b: String, $c: Int = 1) { x }"; + + let typed = with_missing(&document( + query, + "{\n \"big\": 12345678901234567890\n}", + None, )); + let blank = with_missing(&document(query, "", None)); + let empty = with_missing(&document(query, " { } ", None)); + let whole = with_missing(&document(query, "{\"a\": 1, \"b\": \"x\"}", None)); + assert_eq!( - (shorthand.missing, shorthand.unknown), - (names(&[]), names(&["a"])) + typed, + "{\n \"big\": 12345678901234567890,\n \"a\": null,\n \"b\": null\n}" ); - let empty = describe(&document("", r#"{"a": 1}"#)); - assert_eq!((empty.missing, empty.unknown), (names(&[]), names(&[]))); - // A `$variable` used in a selection is not one declared. - let used = describe(&document("query ($a: Int) { x(a: $a, b: $b) }", "")); - assert_eq!(used.missing, names(&["a"])); + assert_eq!(blank, "{\n \"a\": null,\n \"b\": null\n}"); + assert_eq!(empty, blank); + assert_eq!(whole, "{\"a\": 1, \"b\": \"x\"}"); } + /// Copied as typed, not re-serialised; none typed sends none; anything but an object is + /// refused. #[test] - fn what_is_missing_is_added_as_null_at_the_end_of_the_object_as_typed() { - let query = "query Country($code: ID!, $after: String) { country(code: $code) { name } }"; - let added = |variables: &str| with_missing(&document(query, variables)); - - assert_eq!(added(""), "{\n \"code\": null,\n \"after\": null\n}"); - assert_eq!(added("{ }"), "{\n \"code\": null,\n \"after\": null\n}"); + fn the_variables_sent_are_the_object_as_typed() { assert_eq!( - added("{\n \"n\": 12345678901234567890,\n \"code\": \"FR\"\n}\n"), - "{\n \"n\": 12345678901234567890,\n \"code\": \"FR\",\n \"after\": null\n}" + variables(&document("", " {\"n\": 1.10} ", None)), + Ok(Some("{\"n\": 1.10}")) ); - // Nothing missing, or nothing that reads: left as it is. - let whole = r#"{"code": "FR", "after": null}"#; - assert_eq!(added(whole), whole); - assert_eq!(added("{\"code\":"), "{\"code\":"); + assert_eq!(variables(&document("", " ", None)), Ok(None)); + assert!(variables(&document("", "[1]", None)).is_err()); + assert!(variables(&document("", "{\"a\":", None)).is_err()); } + /// The query quoted, the variables as typed, the operation when one is named. #[test] - fn the_body_carries_the_variables_as_typed_and_the_operation_chosen() { - let document = GraphqlDocument { - query: "query A { a }".to_string(), - variables: " {\"id\": 12345678901234567890} ".to_string(), - operation_name: Some("A".to_string()), - as_get: false, - }; + fn a_post_s_body_carries_the_query_its_variables_and_its_operation() { + let named = document("query Q { \"x\" }", "", Some("Q")); + let unnamed = document("{ x }", "", Some("")); - let variables = variables(&document).unwrap(); assert_eq!( - body(&document, variables), - r#"{"query":"query A { a }","variables":{"id": 12345678901234567890},"operationName":"A"}"# - ); - assert!( - super::variables(&GraphqlDocument { - variables: "[1]".to_string(), - ..GraphqlDocument::default() - }) - .is_err() - ); - assert!( - describe(&GraphqlDocument { - variables: "{\"a\":".to_string(), - ..GraphqlDocument::default() - }) - .variables_problem - .is_some() + body(&named, Some("{\"n\": 1.10}")), + r#"{"query":"query Q { \"x\" }","variables":{"n": 1.10},"operationName":"Q"}"# ); + assert_eq!(body(&unnamed, None), r#"{"query":"{ x }"}"#); } + /// `errors` read beside `data`: each message, its path joined and its first location; data + /// laid out, a `null` one being none. #[test] - fn an_answer_is_read_as_data_and_errors_apart() { - let read = result( - r#"{"data":{"invoice":null,"n":1.10},"errors":[{"message":"Not found","path":["invoices",0,"amount"],"locations":[{"line":3,"column":5}]}]}"#, - ) - .unwrap(); + fn an_answer_is_read_as_its_data_and_its_errors() { + let answered = result(r#"{"data":{"n":1.10},"errors":[{"message":"denied","path":["orders",0,"total"],"locations":[{"line":3,"column":5},{"line":9,"column":1}]},{"message":"bare","path":[0,true]},{}]}"#).unwrap(); + let null_data = result(r#"{"data":null,"errors":[{"message":"x"}]}"#).unwrap(); + assert_eq!(answered.data.as_deref(), Some("{\n \"n\": 1.10\n}")); assert_eq!( - read.data.as_deref(), - Some("{\n \"invoice\": null,\n \"n\": 1.10\n}") - ); - assert_eq!( - read.errors, - [GraphqlError { - message: "Not found".to_string(), - path: Some("invoices[0].amount".to_string()), - location: Some("3:5".to_string()), - }] + answered.errors, + [ + GraphqlError { + message: "denied".to_string(), + path: Some("orders[0].total".to_string()), + location: Some("3:5".to_string()), + }, + GraphqlError { + message: "bare".to_string(), + path: Some("[0]".to_string()), + location: None, + }, + GraphqlError { + message: String::new(), + path: None, + location: None, + }, + ] ); - assert_eq!(result(r#"{"data":null,"errors":[]}"#), None); - assert_eq!(result(r#"{"id":7}"#), None); - assert_eq!(result("not json"), None); + assert_eq!(null_data.data, None); + } + + /// No `data` and no `errors`, or no JSON: not a GraphQL answer. + #[test] + fn a_body_with_neither_data_nor_errors_is_no_graphql_answer() { + assert_eq!(result(r#"{"message":"not found"}"#), None); + assert_eq!(result(r#"{"errors":[]}"#), None); + assert_eq!(result(""), None); } } From 7b01c5cf36301ade67a05410406171fb4dde556c Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 17:01:09 +0100 Subject: [PATCH 38/95] Code generation: unit tests rewritten for the request and options (#1761) Co-authored-by: Claude Opus 5.5 --- crates/engine/src/http/codegen.rs | 471 +++++++++++++++++++++++------- 1 file changed, 360 insertions(+), 111 deletions(-) diff --git a/crates/engine/src/http/codegen.rs b/crates/engine/src/http/codegen.rs index 35aea7728..13ad8efb9 100644 --- a/crates/engine/src/http/codegen.rs +++ b/crates/engine/src/http/codegen.rs @@ -514,182 +514,431 @@ pub(crate) mod golden { mod tests { use super::*; use crate::http::environments::Variable; - use crate::http::model::KeyValue; + use crate::http::model::{FormPart, KeyValue}; use crate::http::settings::inherit; use crate::http::variables::VariableScope; - fn layers() -> Vec { - let variable = |name: &str, value: &str, kind: VariableKind| Variable { - name: name.to_string(), + fn row(key: &str, value: &str) -> KeyValue { + KeyValue { + key: key.to_string(), value: value.to_string(), - kind, - ..Variable::default() - }; - vec![VariableLayer { - scope: VariableScope::Environment, - from: "Staging".to_string(), - variables: vec![ - variable("baseUrl", "https://api.exemple.fr", VariableKind::Text), - variable("token", "t0k3n", VariableKind::Secret), - ], - }] + ..KeyValue::default() + } } - fn document() -> RequestDocument { - RequestDocument { - url: "{{baseUrl}}/me?tenant={{tenant}}".to_string(), - headers: vec![KeyValue { - key: "Authorization".to_string(), - value: "Bearer {{token}}".to_string(), - ..KeyValue::default() - }], - ..RequestDocument::default() + fn off(key: &str) -> KeyValue { + KeyValue { + enabled: false, + ..row(key, "x") } } - fn options(resolve: bool, secrets: bool) -> CodeOptions { - CodeOptions { - resolve_variables: resolve, - include_secrets: secrets, - multiline: false, - follow_redirects: false, + fn part(key: &str, value: &str, file: bool, enabled: bool) -> FormPart { + FormPart { + enabled, + key: key.to_string(), + value: value.to_string(), + file, + ..FormPart::default() } } - fn generated(options: CodeOptions) -> GeneratedCode { - generate( - CodeTarget::Curl, - options, + fn http(document: &RequestDocument) -> CodeRequest { + request_of( RequestKind::Http, - HttpMethod::Get, - &document(), + HttpMethod::Post, + document, &inherit(&[]), - &layers(), + false, ) } + fn layer(variables: Vec) -> VariableLayer { + VariableLayer { + scope: VariableScope::Environment, + from: "Prod".to_string(), + variables, + } + } + + fn variable(name: &str, value: &str, kind: VariableKind) -> Variable { + Variable { + name: name.to_string(), + value: value.to_string(), + kind, + ..Variable::default() + } + } + + /// What a snippet of each target is saved as; the three that build no multipart body say so. #[test] - fn every_target_survives_its_stored_spelling() { + fn each_target_is_saved_in_its_language_and_says_what_it_cannot_send() { for target in CodeTarget::ALL { assert_eq!(target.as_str().parse::(), Ok(target)); + assert_eq!( + target.sends_multipart(), + !matches!( + target, + CodeTarget::Wget | CodeTarget::Java | CodeTarget::Swift + ), + "{target:?}" + ); + } + for (target, language) in [ + (CodeTarget::Curl, Language::Sh), + (CodeTarget::Powershell, Language::Ps1), + (CodeTarget::Undici, Language::Js), + (CodeTarget::Angular, Language::Ts), + (CodeTarget::Httpx, Language::Py), + (CodeTarget::Reqwest, Language::Rs), + (CodeTarget::Okhttp, Language::Kt), + (CodeTarget::Csharp, Language::Cs), + (CodeTarget::Guzzle, Language::Php), + (CodeTarget::Elixir, Language::Ex), + ] { + assert_eq!(target.language(), language, "{target:?}"); } } + /// As it is sent: a URL without a scheme over plain HTTP, one starting on a variable as + /// typed; an API key in the query added to it, encoded. #[test] - fn a_secret_stays_its_name_unless_asked_for_and_what_nothing_sets_is_said() { - let kept = generated(options(true, false)); - assert!( - kept.code - .contains("https://api.exemple.fr/me?tenant={{tenant}}") - ); - assert!(kept.code.contains("Bearer {{token}}")); - assert_eq!(kept.secrets, ["token"]); - assert_eq!(kept.unresolved, ["tenant"]); - assert_eq!(kept.language, Language::Sh); - - let clear = generated(options(true, true)); - assert!(clear.code.contains("Bearer t0k3n")); - assert!(clear.secrets.is_empty()); + fn the_url_is_written_as_it_is_sent() { + let bare = RequestDocument { + url: " api.shop.test/a?x=1 ".to_string(), + auth: RequestAuth::ApiKey { + name: " api key ".to_string(), + value: "k&1".to_string(), + place: KeyPlace::Query, + }, + ..RequestDocument::default() + }; + let variable = RequestDocument { + url: "{{base}}/a".to_string(), + ..RequestDocument::default() + }; + let unnamed_key = RequestDocument { + url: "https://shop.test/".to_string(), + auth: RequestAuth::ApiKey { + name: " ".to_string(), + value: "k".to_string(), + place: KeyPlace::Query, + }, + ..RequestDocument::default() + }; - let typed = generated(options(false, false)); - assert!(typed.code.contains("'{{baseUrl}}/me"), "{}", typed.code); - assert!(!typed.code.contains("://{{"), "{}", typed.code); + assert_eq!(http(&bare).url, "http://api.shop.test/a?x=1&api+key=k%261"); + assert_eq!(http(&variable).url, "{{base}}/a"); + assert_eq!(http(&unnamed_key).url, "https://shop.test/"); } + /// A Basic auth apart, each target writing it its own way, and not as a header; the + /// application's own headers left out — the program names itself. #[test] - fn the_application_names_itself_and_a_basic_auth_is_written_apart() { + fn a_basic_auth_is_handed_apart_and_the_application_s_headers_left_out() { let document = RequestDocument { - url: "api.exemple.fr/x".to_string(), + url: "https://shop.test/".to_string(), + headers: vec![row("X-Trace", "1")], auth: RequestAuth::Basic { username: "ada".to_string(), password: "pw".to_string(), }, ..RequestDocument::default() }; - let request = request_of( - RequestKind::Http, - HttpMethod::Get, - &document, - &inherit(&[]), - false, - ); - assert_eq!(request.url, "http://api.exemple.fr/x"); + + let request = http(&document); + assert_eq!(request.basic, Some(("ada".to_string(), "pw".to_string()))); - assert!(request.headers.is_empty(), "{:?}", request.headers); + assert_eq!(request.headers, [("X-Trace".to_string(), "1".to_string())]); + assert!(!request.follow_redirects); } + /// What leaves as the body: a text, the fields and parts switched on and named, a file by + /// its path; an empty one none. #[test] - fn a_key_in_the_query_and_a_graphql_get_go_in_the_url() { - let keyed = RequestDocument { - url: "https://x/a?b=1".to_string(), - auth: RequestAuth::ApiKey { - name: "api key".to_string(), - value: "k&1".to_string(), - place: KeyPlace::Query, - }, + fn the_body_is_what_a_send_would_write() { + for (body, expected) in [ + (RequestBody::None, CodeBody::None), + ( + RequestBody::Json { + text: String::new(), + }, + CodeBody::None, + ), + ( + RequestBody::Text { + text: "t".to_string(), + }, + CodeBody::Text("t".to_string()), + ), + ( + RequestBody::Form { + fields: vec![row(" a ", "1"), off("b"), row(" ", "x")], + }, + CodeBody::Form(vec![("a".to_string(), "1".to_string())]), + ), + ( + RequestBody::Multipart { + parts: vec![ + part(" f ", "/a.png", true, true), + part("off", "x", false, false), + part(" ", "x", false, true), + ], + }, + CodeBody::Multipart(vec![CodePart { + name: "f".to_string(), + value: "/a.png".to_string(), + file: true, + }]), + ), + ( + RequestBody::Binary { + path: " ".to_string(), + }, + CodeBody::None, + ), + ( + RequestBody::Binary { + path: " /dump.bin ".to_string(), + }, + CodeBody::File("/dump.bin".to_string()), + ), + ] { + let document = RequestDocument { + body, + ..RequestDocument::default() + }; + + assert_eq!(http(&document).body, expected); + } + } + + /// A GraphQL request is a `POST` of its JSON body, or a `GET` carrying its parts in the + /// query, whatever method the document holds. + #[test] + fn a_graphql_request_is_written_as_it_is_sent() { + let mut document = RequestDocument { + url: "https://shop.test/graphql".to_string(), ..RequestDocument::default() }; - let request = request_of( - RequestKind::Http, - HttpMethod::Get, - &keyed, + document.graphql.query = "{ me }".to_string(); + document.graphql.variables = "{\"a\":1}".to_string(); + document.graphql.operation_name = Some("Me".to_string()); + + let posted = request_of( + RequestKind::Graphql, + HttpMethod::Delete, + &document, &inherit(&[]), - false, + true, + ); + document.graphql.as_get = true; + let got = request_of( + RequestKind::Graphql, + HttpMethod::Delete, + &document, + &inherit(&[]), + true, + ); + document.graphql.operation_name = Some(String::new()); + document.graphql.variables = "[not an object]".to_string(); + let bare = request_of( + RequestKind::Graphql, + HttpMethod::Delete, + &document, + &inherit(&[]), + true, ); - assert_eq!(request.url, "https://x/a?b=1&api+key=k%261"); - let mut graphql = RequestDocument { - url: "https://x/graphql".to_string(), + assert_eq!(posted.method, HttpMethod::Post); + assert_eq!( + posted.body, + CodeBody::Text( + r#"{"query":"{ me }","variables":{"a":1},"operationName":"Me"}"#.to_string() + ) + ); + assert!(posted.follow_redirects); + assert_eq!((got.method, &got.body), (HttpMethod::Get, &CodeBody::None)); + assert_eq!( + got.url, + "https://shop.test/graphql?query=%7B+me+%7D&variables=%7B%22a%22%3A1%7D&operationName=Me" + ); + assert_eq!(bare.url, "https://shop.test/graphql?query=%7B+me+%7D"); + } + + /// The type the headers set, case aside. + #[test] + fn the_content_type_is_read_from_the_headers() { + let request = CodeRequest { + headers: vec![("content-TYPE".to_string(), "text/csv".to_string())], + ..http(&RequestDocument::default()) + }; + + assert_eq!(request.content_type(), Some("text/csv")); + assert_eq!(http(&RequestDocument::default()).content_type(), None); + } + + fn document_using(names: &str) -> RequestDocument { + RequestDocument { + url: format!("https://shop.test/{names}"), ..RequestDocument::default() + } + } + + /// A secret stays its `{{name}}` and is named, unless asked for in clear; a name nothing + /// sets is written as typed and named; off, nothing is resolved. + #[test] + fn variables_are_resolved_secrets_aside_unless_asked_for() { + let layers = [layer(vec![ + variable("host", "h", VariableKind::Text), + variable("token", "t0k3n", VariableKind::Secret), + ])]; + let document = document_using("{{host}}/{{token}}/{{nowhere}}"); + let resolve = CodeOptions { + resolve_variables: true, + ..CodeOptions::default() }; - graphql.graphql.query = "{ me { id } }".to_string(); - graphql.graphql.as_get = true; - let request = request_of( - RequestKind::Graphql, - HttpMethod::Post, - &graphql, - &inherit(&[]), - false, + let in_clear = CodeOptions { + include_secrets: true, + ..resolve + }; + let generate_with = |options| { + generate( + CodeTarget::Curl, + options, + RequestKind::Http, + HttpMethod::Get, + &document, + &inherit(&[]), + &layers, + ) + }; + + let masked = generate_with(resolve); + let clear = generate_with(in_clear); + let typed = generate_with(CodeOptions::default()); + + assert!( + masked + .code + .contains("https://shop.test/h/{{token}}/{{nowhere}}"), + "{}", + masked.code + ); + assert_eq!( + (masked.secrets, masked.unresolved), + (vec!["token".to_string()], vec!["nowhere".to_string()]) + ); + assert!( + clear.code.contains("https://shop.test/h/t0k3n/{{nowhere}}"), + "{}", + clear.code + ); + assert!(clear.secrets.is_empty()); + assert!( + typed + .code + .contains("https://shop.test/{{host}}/{{token}}/{{nowhere}}"), + "{}", + typed.code ); - assert_eq!(request.method, HttpMethod::Get); - assert_eq!(request.url, "https://x/graphql?query=%7B+me+%7B+id+%7D+%7D"); + assert_eq!(masked.language, Language::Sh); } + /// Wget, Java's client and `URLSession` build no multipart body: the interface says it. #[test] - fn wget_says_it_sends_no_multipart_form() { + fn a_target_that_cannot_send_a_multipart_body_says_so() { let document = RequestDocument { - url: "https://x".to_string(), body: RequestBody::Multipart { - parts: vec![crate::http::model::FormPart { - key: "a".to_string(), - value: "1".to_string(), - ..Default::default() - }], + parts: vec![part("a", "1", false, true)], }, - ..RequestDocument::default() + ..document_using("") }; - let code = generate( + let notice = |target| { + generate( + target, + CodeOptions::default(), + RequestKind::Http, + HttpMethod::Post, + &document, + &inherit(&[]), + &[], + ) + .notice + }; + + for target in CodeTarget::ALL { + let expected = (!target.sends_multipart()).then_some(CodeNotice::MultipartUnsupported); + + assert_eq!(notice(target), expected, "{target:?}"); + } + let text = generate( CodeTarget::Wget, - options(true, false), + CodeOptions::default(), RequestKind::Http, - HttpMethod::Post, - &document, + HttpMethod::Get, + &document_using(""), &inherit(&[]), &[], ); - assert_eq!(code.notice, Some(CodeNotice::MultipartUnsupported)); + assert_eq!(text.notice, None); + } + + /// Every target writes something for the same request, each in its own language. + #[test] + fn every_target_writes_the_request() { + let document = document_using("orders"); + + for target in CodeTarget::ALL { + let code = generate( + target, + CodeOptions::default(), + RequestKind::Http, + HttpMethod::Get, + &document, + &inherit(&[]), + &[], + ); + + assert!( + code.code.contains("shop.test/orders"), + "{target:?}: {}", + code.code + ); + assert_eq!(code.language, target.language()); + } } + /// A quote inside closes, escapes and reopens. #[test] - fn a_shell_quote_survives_a_quote_and_lines_end_on_a_backslash() { - assert_eq!(shell_quoted("O'Brien"), r"'O'\''Brien'"); + fn a_shell_argument_is_quoted_whatever_it_holds() { + assert_eq!(shell_quoted("O'Brien $HOME"), r"'O'\''Brien $HOME'"); + assert_eq!(shell_quoted(""), "''"); + } + + /// On one line, or one argument a line under the first, each but the last ending on `\`. + #[test] + fn arguments_are_written_on_one_line_or_one_a_line() { + let arguments = ["-X POST".to_string(), "'https://shop.test/'".to_string()]; + assert_eq!( - shell_lines("curl", &["-a".to_string(), "-b".to_string()], true), - "curl \\\n -a \\\n -b" + shell_lines("curl", &arguments, false), + "curl -X POST 'https://shop.test/'" ); assert_eq!( - shell_lines("curl", &["-a".to_string(), "-b".to_string()], false), - "curl -a -b" + shell_lines("curl", &arguments, true), + "curl \\\n -X POST \\\n 'https://shop.test/'" ); + assert_eq!(shell_lines("curl", &[], true), "curl"); + } + + #[test] + fn a_form_is_encoded_as_it_is_sent() { + let fields = [ + ("a b".to_string(), "x&y=z".to_string()), + ("c".to_string(), String::new()), + ]; + + assert_eq!(form_encoded(&fields), "a+b=x%26y%3Dz&c="); } } From 5f4790c1f68cbefea363b810025bb157d635f38b Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 17:01:15 +0100 Subject: [PATCH 39/95] Collection runs: unit tests rewritten for data, order and results (#1762) Co-authored-by: Claude Opus 5.5 --- crates/engine/src/http/runner.rs | 620 ++++++++++++++++++++++++------- 1 file changed, 476 insertions(+), 144 deletions(-) diff --git a/crates/engine/src/http/runner.rs b/crates/engine/src/http/runner.rs index 3ce4a454b..61e386afb 100644 --- a/crates/engine/src/http/runner.rs +++ b/crates/engine/src/http/runner.rs @@ -495,33 +495,17 @@ pub fn next_index(order: &[Placed], at: usize, next: Option<&Next>) -> Option Vec<&str> { + data.columns.iter().map(String::as_str).collect() } - use super::*; - fn row(pairs: &[(&str, &str)]) -> BTreeMap { pairs .iter() @@ -529,177 +513,525 @@ mod tests { .collect() } + /// A JSON array of objects: its keys in the order first met, a text as it is and the rest + /// as JSON; a byte-order mark before it is no reason to refuse it. #[test] - fn a_csv_reads_with_its_header_quotes_and_blank_lines() { + fn a_json_array_of_objects_is_read_a_row_an_object() { let data = read_data( - "\u{feff}customer,amount,note\r\ncus_QX12a9,12,\"a, b\"\r\n\r\ncus_R7a01x,8,\"say \"\"hi\"\"\nthen\"\n", + "\u{feff} [{\"user\":\"ada\",\"age\":36},{\"admin\":true,\"user\":\"bob\"}]", ) .unwrap(); - assert_eq!(data.columns, ["customer", "amount", "note"]); + + assert_eq!(columns(&data), ["user", "age", "admin"]); assert_eq!( data.rows, [ - row(&[ - ("customer", "cus_QX12a9"), - ("amount", "12"), - ("note", "a, b") - ]), - row(&[ - ("customer", "cus_R7a01x"), - ("amount", "8"), - ("note", "say \"hi\"\nthen") - ]), + row(&[("user", "ada"), ("age", "36")]), + row(&[("admin", "true"), ("user", "bob")]) ] ); - let short = read_data("a,b\n1").unwrap(); - assert_eq!(short.rows, [row(&[("a", "1"), ("b", "")])]); } + /// RFC 4180: a quoted field holds commas, line breaks and doubled quotes; a short row ends + /// on empty values, an unnamed column is left out, blank lines and CRs are nothing. #[test] - fn a_json_array_of_objects_reads_a_row_an_object() { + fn a_csv_with_its_header_is_read_a_row_a_line() { let data = - read_data(r#"[{"customer":"cus_1","amount":12},{"customer":"cus_2","vip":true}]"#) + read_data("user , note,,age\r\nada,\"a, \"\"quoted\"\"\nnote\",x,36\r\n\r\nbob\n") .unwrap(); - assert_eq!(data.columns, ["customer", "amount", "vip"]); + + assert_eq!(columns(&data), ["user", "note", "", "age"]); assert_eq!( - data.rows[0], - row(&[("customer", "cus_1"), ("amount", "12")]) + data.rows, + [ + row(&[ + ("user", "ada"), + ("note", "a, \"quoted\"\nnote"), + ("age", "36") + ]), + row(&[("user", "bob"), ("note", ""), ("age", "")]), + ] ); - assert_eq!(data.rows[1], row(&[("customer", "cus_2"), ("vip", "true")])); } + /// What reads as neither — a quote left open, a sentence alone, a JSON + /// that is no array of objects — is said so; a file of no row is said empty, a line of commas being blank. + #[test] + fn a_file_that_reads_as_no_data_is_refused_for_what_it_is() { + for (text, fault) in [ + ("user\n\"ada", DataFault::Unreadable), + ("just a sentence here", DataFault::Unreadable), + (",,\nx,y", DataFault::Empty), + ("[1, 2]", DataFault::Unreadable), + ("[{\"a\":", DataFault::Unreadable), + ("user,age\n", DataFault::Empty), + ("[]", DataFault::Empty), + ("", DataFault::Empty), + ] { + assert_eq!(read_data(text), Err(fault), "{text:?}"); + } + // A lone word is a header waiting for its rows, not a sentence. + assert_eq!(read_data("token"), Err(DataFault::Empty)); + } + + /// Read where it lies; past the size a run reads, refused before it is read. + #[test] + fn a_data_file_is_read_from_disk_up_to_its_limit() { + let scratch = tempfile::tempdir().unwrap(); + let path = scratch.path().join("users.csv"); + std::fs::write(&path, "user\nada\n").unwrap(); + let missing = scratch.path().join("missing.csv"); + + let data = read_file(path.to_str().unwrap()).unwrap(); + + assert_eq!(data.rows, [row(&[("user", "ada")])]); + assert_eq!( + read_file(missing.to_str().unwrap()).unwrap_err().code, + ErrorCode::FileAccess + ); + } + + /// A data file past the cap is refused before it is read whole (a defect once met). + #[test] + fn a_data_file_past_the_cap_is_refused_unread() { + let scratch = tempfile::tempdir().unwrap(); + let path = scratch.path().join("rows.csv"); + let file = std::fs::File::create(&path).unwrap(); + file.set_len(RUN_DATA_LIMIT + 1).unwrap(); + + let refused = read_file(path.to_str().unwrap()).unwrap_err(); + + assert_eq!(refused.params["fault"], "tooLarge"); + } + + fn folder(id: &str, name: &str, children: Vec) -> HttpNode { + HttpNode::Folder { + folder: HttpFolder { + id: id.to_string(), + collection_id: "c-1".to_string(), + parent_id: None, + name: name.to_string(), + position: 0, + }, + children, + } + } + + fn request(id: &str) -> HttpNode { + HttpNode::Request { + request: HttpRequestSummary { + id: id.to_string(), + collection_id: "c-1".to_string(), + folder_id: None, + name: id.to_uppercase(), + kind: RequestKind::Http, + method: HttpMethod::Get, + position: 0, + }, + } + } + + fn tree() -> HttpTree { + let at = crate::db::iso8601::parse("2026-07-25T09:00:00.000Z").unwrap(); + let collection = |id: &str, children| HttpCollectionNode { + collection: HttpCollection { + id: id.to_string(), + name: id.to_string(), + position: 0, + created_at: at, + }, + children, + }; + HttpTree { + collections: vec![ + collection( + "c-1", + vec![ + request("a"), + folder( + "f-1", + "Auth", + vec![request("b"), folder("f-2", "Deep", vec![request("c")])], + ), + request("d"), + ], + ), + collection("c-2", vec![request("other")]), + ], + } + } + + fn placed(item: HttpItemKind, id: &str) -> Vec<(String, Vec)> { + placed_under( + &tree(), + &HttpItem { + kind: item, + id: id.to_string(), + }, + ) + .into_iter() + .map(|placed| (placed.id, placed.path)) + .collect() + } + + /// Each request under a collection or a folder, in the tree's order, with the folders + /// between; another collection's never, and a request is nothing to run under. #[test] - fn a_file_that_is_neither_or_holds_nothing_is_said() { - assert_eq!(read_data("[1, 2]"), Err(DataFault::Unreadable)); - assert_eq!(read_data("a,b\n\"open"), Err(DataFault::Unreadable)); - assert_eq!(read_data("a,b\n"), Err(DataFault::Empty)); + fn the_requests_under_an_item_are_found_in_the_tree_s_order() { + let path = |names: &[&str]| names.iter().map(ToString::to_string).collect::>(); + assert_eq!( - read_data("ceci n’est ni un CSV avec en-tête ni un tableau JSON\n"), - Err(DataFault::Unreadable), - "one line without a separator" + placed(HttpItemKind::Collection, "c-1"), + [ + ("a".to_string(), path(&[])), + ("b".to_string(), path(&["Auth"])), + ("c".to_string(), path(&["Auth", "Deep"])), + ("d".to_string(), path(&[])), + ] ); - assert!(read_data("id\n1\n").is_ok(), "one column, with its rows"); assert_eq!( - read_data("customer\n"), - Err(DataFault::Empty), - "a header alone" + placed(HttpItemKind::Folder, "f-2"), + [("c".to_string(), path(&[]))] ); - assert_eq!(read_data("[]"), Err(DataFault::Empty)); - assert_eq!(read_data(""), Err(DataFault::Empty)); + assert!(placed(HttpItemKind::Folder, "missing").is_empty()); + assert!(placed(HttpItemKind::Request, "a").is_empty()); } - #[test] - fn the_order_kept_drops_what_is_gone_and_ends_on_what_was_added() { - let placed: Vec = ["a", "b", "c", "d"] - .iter() - .map(|id| Placed { - id: (*id).to_string(), - name: (*id).to_uppercase(), - path: Vec::new(), - }) - .collect(); - let entry = |id: &str, enabled: bool| RunEntry { + fn entry(id: &str, enabled: bool) -> RunEntry { + RunEntry { id: id.to_string(), enabled, - }; + } + } + + /// The order last arranged, less what went since and once each, then what was added since + /// in the tree's order, switched on. + #[test] + fn a_run_takes_the_order_last_arranged_and_what_came_since() { + let here: Vec = placed_under( + &tree(), + &HttpItem { + kind: HttpItemKind::Collection, + id: "c-1".to_string(), + }, + ); + let saved = [ + entry("d", false), + entry("gone", true), + entry("b", true), + entry("d", true), + ]; + + let order = run_order(&saved, &here); assert_eq!( - run_order(&[], &placed), + order, [ - entry("a", true), + entry("d", false), entry("b", true), - entry("c", true), - entry("d", true) - ], - "nothing arranged: the tree's order" + entry("a", true), + entry("c", true) + ] + ); + } + + /// `run:#.` belongs to its run; any other send to none. + #[test] + fn a_send_says_the_run_it_belongs_to() { + assert_eq!(run_of("run:r-1#2.3"), Some("r-1")); + assert_eq!(run_of("run:r-1"), Some("r-1")); + assert_eq!(run_of("send-7"), None); + } + + fn held(name: &str) -> HttpRequest { + let at = crate::db::iso8601::parse("2026-07-25T09:00:00.000Z").unwrap(); + HttpRequest { + id: name.to_lowercase(), + collection_id: "c-1".to_string(), + folder_id: None, + name: name.to_string(), + kind: RequestKind::Graphql, + method: HttpMethod::Post, + document: RequestDocument::default(), + created_at: at, + updated_at: at, + } + } + + fn answer(tests: Vec, failure: Option) -> SentResponse { + SentResponse { + status: 201, + reason: "Created".to_string(), + millis: 42, + size: 3, + url: String::new(), + headers: Vec::new(), + body: String::new(), + binary: false, + cut: false, + incomplete: false, + redirects: Vec::new(), + language: Language::Txt, + pretty: None, + cookies: Vec::new(), + exchange: crate::http::send::Exchange { + method: HttpMethod::Post, + url: String::new(), + headers: Vec::new(), + body: crate::http::send::SentBody::None, + }, + graphql: None, + scripts: ScriptsAnswer { + failure, + tests, + ..ScriptsAnswer::default() + }, + } + } + + fn test(name: &str, passed: bool, skipped: bool) -> TestResult { + TestResult { + name: name.to_string(), + passed, + skipped, + ..TestResult::default() + } + } + + /// An answer's status, time, tests and stop, its body kept only when asked; a skip is not a + /// failure; another error is kept as its code and what it states. + #[test] + fn a_request_of_a_run_ends_as_its_answer_says() { + let stop = ScriptStop { + message: "boom".to_string(), + ..ScriptStop::default() + }; + let answered = result_of( + 2, + &held("Login"), + vec!["Auth".to_string()], + Ok(answer(vec![test("ok", true, false)], Some(stop.clone()))), + false, + ); + let kept = result_of( + 1, + &held("Login"), + Vec::new(), + Ok(answer(Vec::new(), None)), + true, + ); + let skipped = result_of( + 1, + &held("Login"), + Vec::new(), + Err(AppError::new(ErrorCode::HttpScriptSkipped, String::new())), + true, + ); + let failed = result_of( + 1, + &held("Login"), + Vec::new(), + Err(AppError::with( + ErrorCode::HttpTimeout, + String::new(), + "delay", + "30 s", + )), + true, + ); + + assert_eq!( + ( + answered.iteration, + answered.request_id.as_str(), + answered.name.as_str() + ), + (2, "login", "Login") ); assert_eq!( - run_order( - &[ - entry("c", true), - entry("gone", true), - entry("a", false), - entry("c", false) + (answered.kind, answered.method, answered.path.as_slice()), + ( + RequestKind::Graphql, + HttpMethod::Post, + ["Auth".to_string()].as_slice() + ) + ); + assert_eq!( + (answered.status, answered.reason.as_str(), answered.millis), + (Some(201), "Created", 42) + ); + assert_eq!( + (answered.tests.len(), answered.stop, answered.response), + (1, Some(stop), None) + ); + assert!(kept.response.is_some()); + assert!(skipped.skipped && skipped.error.is_none() && !skipped.failed()); + assert_eq!( + failed.error, + Some(RunError { + code: ErrorCode::HttpTimeout, + params: BTreeMap::from([("delay".to_string(), "30 s".to_string())]) + }) + ); + } + + /// No answer, a script that stopped, or a test that failed; a test skipped is no failure, and + /// a request skipped fails nothing. + #[test] + fn a_result_fails_by_its_error_its_stop_or_a_test() { + let base = result_of( + 1, + &held("A"), + Vec::new(), + Ok(answer( + vec![test("ok", true, false), test("later", false, true)], + None, + )), + false, + ); + let failing_test = RunResult { + tests: vec![test("bad", false, false)], + ..base.clone() + }; + let stopped = RunResult { + stop: Some(ScriptStop::default()), + ..base.clone() + }; + let errored = RunResult { + error: Some(RunError { + code: ErrorCode::HttpTimeout, + params: BTreeMap::new(), + }), + ..base.clone() + }; + let skipped = RunResult { + skipped: true, + ..failing_test.clone() + }; + + assert!(!base.failed()); + assert!(failing_test.failed() && stopped.failed() && errored.failed()); + assert!(!skipped.failed()); + } + + /// The requests that failed of those that ended, the tests that passed of those that ran. + #[test] + fn a_report_sums_up_its_failures_and_its_tests() { + let base = result_of( + 1, + &held("A"), + Vec::new(), + Ok(answer( + vec![ + test("a", true, false), + test("b", false, false), + test("c", false, true), ], - &placed + None, + )), + false, + ); + let clean = RunResult { + tests: vec![test("d", true, false)], + ..base.clone() + }; + + let summary = RunSummary::of(&[base, clean]); + + assert_eq!( + summary, + RunSummary { + failures: 1, + requests: 2, + passed: 2, + tests: 3 + } + ); + assert_eq!(RunSummary::of(&[]), RunSummary::default()); + } + + /// A request gone when its turn comes ends as the error that says so, under its place. + #[test] + fn a_request_gone_since_ends_as_its_error() { + let placed = Placed { + id: "r-9".to_string(), + name: "Gone".to_string(), + path: vec!["Auth".to_string()], + }; + + let result = gone( + 3, + &placed, + AppError::with(ErrorCode::HttpItemNotFound, String::new(), "id", "r-9"), + ); + + assert_eq!( + ( + result.iteration, + result.request_id.as_str(), + result.name.as_str() ), - [ - entry("c", true), - entry("a", false), - entry("b", true), - entry("d", true) - ] + (3, "r-9", "Gone") ); + assert_eq!(result.path, ["Auth"]); + assert_eq!(result.error.unwrap().code, ErrorCode::HttpItemNotFound); + assert_eq!(result.status, None); } + /// On, to the request a script named — by its name —, or to the end; a name not in the + /// order ends it too. #[test] - fn a_run_goes_on_follows_the_request_a_script_named_or_stops() { - let order: Vec = [("a", "Login"), ("b", "Payer"), ("c", "Reçu")] + fn a_run_goes_on_to_the_next_request_or_where_a_script_points() { + let order: Vec = ["a", "b", "c"] .iter() - .map(|(id, name)| Placed { - id: (*id).to_string(), - name: (*name).to_string(), + .map(|name| Placed { + id: (*name).to_string(), + name: name.to_uppercase(), path: Vec::new(), }) .collect(); + assert_eq!(next_index(&order, 0, None), Some(1)); assert_eq!(next_index(&order, 2, None), None); - let to = |name: &str| Next::To(name.to_string()); - assert_eq!(next_index(&order, 0, Some(&to("Reçu"))), Some(2)); - assert_eq!(next_index(&order, 2, Some(&to("Login"))), Some(0)); - assert_eq!(next_index(&order, 0, Some(&to("Ailleurs"))), None); + assert_eq!( + next_index(&order, 2, Some(&Next::To("A".to_string()))), + Some(0) + ); + assert_eq!( + next_index(&order, 0, Some(&Next::To("missing".to_string()))), + None + ); assert_eq!(next_index(&order, 0, Some(&Next::End)), None); } + /// A script naming its own request again would loop until « Cancel »: one iteration sends + /// at most so many, and only stops where it would go on. #[test] - fn a_result_fails_on_an_error_a_stop_or_a_failed_test_never_when_skipped() { - let base = RunResult { - iteration: 0, - request_id: "a".to_string(), - name: "Login".to_string(), - path: Vec::new(), - kind: RequestKind::Http, - method: HttpMethod::Get, - status: Some(200), - reason: "OK".to_string(), - millis: 1, - tests: vec![TestResult { - passed: true, - ..TestResult::default() - }], - error: None, - stop: None, - skipped: false, - response: None, - }; - assert!(!base.failed()); - let failing_test = RunResult { - tests: vec![TestResult::default()], - ..base.clone() - }; - assert!(failing_test.failed()); - assert!( - RunResult { - error: Some(RunError { - code: ErrorCode::HttpRefused, - params: BTreeMap::new(), - }), - ..base.clone() - } - .failed() - ); - assert!( - !RunResult { - skipped: true, - ..failing_test - } - .failed() - ); + fn an_iteration_stops_at_the_most_steps_it_sends() { + assert!(capped(MAX_STEPS, Some(0))); + assert!(!capped(MAX_STEPS - 1, Some(0))); + assert!(!capped(MAX_STEPS, None)); } + /// « Annuler » reaches the run and the send it is at; a run not under way is cancelled as far + /// as anyone asks, and answers no send; leaving cancels them all. #[test] - fn a_send_names_the_run_it_belongs_to() { - assert_eq!(run_of("run:7#0.3"), Some("7")); - assert_eq!(run_of("send-7"), None); + fn a_run_under_way_is_cancelled_with_the_send_it_is_at() { + let runs = Runs::default(); + runs.start("r-1"); + runs.start("r-2"); + assert!(!runs.cancelled("r-1")); + + runs.at("r-1", "run:r-1#1.1"); + runs.at("missing", "x"); + + assert_eq!(runs.cancel("r-1"), Some(Some("run:r-1#1.1".to_string()))); + assert!(runs.cancelled("r-1")); + assert_eq!(runs.cancel("missing"), None); + assert!(runs.cancelled("missing")); + runs.cancel_all(); + assert!(runs.cancelled("r-2")); + runs.finish("r-2"); + assert_eq!(runs.cancel("r-2"), None); } } From ebef91bfad707a1c3a565e38bbcfce302f6f5546 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 17:01:22 +0100 Subject: [PATCH 40/95] WebSockets: unit tests rewritten for opening, messages and failures (#1763) Co-authored-by: Claude Opus 5.5 --- crates/engine/src/http/websocket.rs | 138 +++------- crates/engine/tests/commands/websocket.rs | 299 ++++++++++++++++------ 2 files changed, 253 insertions(+), 184 deletions(-) diff --git a/crates/engine/src/http/websocket.rs b/crates/engine/src/http/websocket.rs index 9cbf8b39b..c8a03477c 100644 --- a/crates/engine/src/http/websocket.rs +++ b/crates/engine/src/http/websocket.rs @@ -434,112 +434,46 @@ fn closed(frame: Option<&CloseFrame>) -> SocketEvent { mod tests { use super::*; + /// Checked as HTTP: `ws://` and `wss://` as typed, no scheme being `ws://`, a scheme read in + /// any case; `https://` in a socket was dialled as `wss://` without a word, so another + /// scheme is refused, with its twin when it has one. #[test] - fn a_socket_url_is_checked_as_http_and_sent_back_on_its_scheme() { - let checked = |typed: &str| socket_url(typed).unwrap(); - assert_eq!( - checked(" wss://echo.exemple.fr/ws "), - "https://echo.exemple.fr/ws" - ); - assert_eq!(checked("WS://localhost:8080"), "http://localhost:8080"); - assert_eq!(checked("echo.exemple.fr"), "echo.exemple.fr"); - assert_eq!(checked("{{socket}}/live"), "{{socket}}/live"); - - assert_eq!( - as_socket(&Url::parse("https://a.fr/ws?x=1").unwrap()), - "wss://a.fr/ws?x=1" - ); - assert_eq!( - as_socket(&Url::parse("http://a.fr/").unwrap()), - "ws://a.fr/" - ); - } - - /// `https://` in a socket was dialled as `wss://` without a word, and failed « Erreur réseau ». - #[test] - fn a_scheme_a_socket_does_not_open_on_is_refused_with_its_twin_when_it_has_one() { - let twin = |typed: &str| match socket_url(typed) { - Err(SendError::SocketScheme { twin }) => twin, - other => panic!("{typed}: {other:?}"), - }; - - assert_eq!( - twin("https://echo.exemple.fr/ws?x=1").as_deref(), - Some("wss://echo.exemple.fr/ws?x=1") - ); - assert_eq!( - twin(" HTTP://localhost:8080 ").as_deref(), - Some("ws://localhost:8080") - ); - assert_eq!(twin("ftp://exemple.fr"), None); - } - - #[test] - fn a_failure_of_a_socket_is_named_as_a_request_s_is() { - use std::io::{Error, ErrorKind}; - - let limit = Limit { - value: 2_000, - set_by: crate::http::transport::SetBy::Default, - }; - let read = |error: Error| failure(&tungstenite::Error::Io(error), Some(&limit)); - - assert!(matches!( - read(Error::other( - "failed to lookup address information: Name or service not known" - )), - SendError::Unresolved(_) - )); - assert!(matches!( - read(Error::from(ErrorKind::ConnectionRefused)), - SendError::Refused(_) - )); - assert_eq!( - read(Error::from(ErrorKind::TimedOut)), - SendError::Timeout(limit.clone()) - ); - assert!(matches!( - read(Error::other(rustls::Error::HandshakeNotComplete)), - SendError::Tls(_) - )); - // All that is left is « network », and the cause's own words go with it. - assert_eq!( - read(Error::other("connection reset by peer")), - SendError::Network("connection reset by peer".to_string()) - ); - assert_eq!( - failure(&tungstenite::Error::ConnectionClosed, None), - SendError::Network("Connection closed normally".to_string()) - ); + fn a_socket_url_is_checked_as_http_or_refused_with_its_twin() { + for (typed, checked) in [ + ( + " wss://echo.test/live?x=1 ", + Ok("https://echo.test/live?x=1".to_string()), + ), + ("WS://echo.test", Ok("http://echo.test".to_string())), + ("echo.test:8080/", Ok("echo.test:8080/".to_string())), + ( + "https://echo.test/a", + Err(SendError::SocketScheme { + twin: Some("wss://echo.test/a".to_string()), + }), + ), + ( + "Http://echo.test", + Err(SendError::SocketScheme { + twin: Some("ws://echo.test".to_string()), + }), + ), + ( + "ftp://echo.test", + Err(SendError::SocketScheme { twin: None }), + ), + ] { + assert_eq!(socket_url(typed), checked, "{typed}"); + } } + /// Stored with the request: a document written before a field existed still opens. #[test] - fn a_long_message_is_cut_on_a_character() { - let long = "é".repeat(MESSAGE_SHOWN); - let (shown, was_cut) = cut(&long); - assert!(was_cut && shown.len() <= MESSAGE_SHOWN && long.starts_with(&shown)); - assert_eq!(cut("hi"), ("hi".to_string(), false)); - } + fn a_websocket_document_written_before_its_fields_still_opens() { + let document: WebsocketDocument = + serde_json::from_str(r#"{"protocols":["chat"]}"#).unwrap(); - #[test] - fn a_close_frame_says_its_code_and_reason() { - let frame = CloseFrame { - code: CloseCode::Away, - reason: "bye".into(), - }; - assert_eq!( - closed(Some(&frame)), - SocketEvent::Closed { - code: Some(1001), - reason: "bye".to_string() - } - ); - assert_eq!( - closed(None), - SocketEvent::Closed { - code: None, - reason: String::new() - } - ); + assert_eq!(document.protocols, ["chat"]); + assert!(document.messages.is_empty()); } } diff --git a/crates/engine/tests/commands/websocket.rs b/crates/engine/tests/commands/websocket.rs index c304fbc5e..5e5ff02d4 100644 --- a/crates/engine/tests/commands/websocket.rs +++ b/crates/engine/tests/commands/websocket.rs @@ -80,14 +80,63 @@ fn request(url: &str) -> WebsocketRequest { } } -#[test] -fn a_socket_opens_echoes_and_closes_each_step_an_event() { - let session = Session::open(); - let seen = std::cell::Cell::new(0); - let next = || { +/// Opens sockets over TLS with a certificate nobody signed, for 127.0.0.1. +fn self_signed_echo() -> u16 { + let certified = rcgen::generate_simple_self_signed(vec!["127.0.0.1".to_string()]).unwrap(); + let key = rustls::pki_types::PrivateKeyDer::Pkcs8(certified.signing_key.serialize_der().into()); + let provider = std::sync::Arc::new(rustls::crypto::ring::default_provider()); + let config = rustls::ServerConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .unwrap() + .with_no_client_auth() + .with_single_cert(vec![certified.cert.der().clone()], key) + .unwrap(); + let config = std::sync::Arc::new(config); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + thread::spawn(move || { + for stream in listener.incoming().flatten() { + let connection = rustls::ServerConnection::new(std::sync::Arc::clone(&config)).unwrap(); + let tls = rustls::StreamOwned::new(connection, stream); + thread::spawn(move || { + if let Ok(mut socket) = tungstenite::accept_hdr(tls, take_chat) { + while socket.read().is_ok() {} + } + }); + } + }); + port +} + +/// Accepts one socket and closes it at once with `code` and `reason`. +fn closer(code: u16, reason: &'static str) -> u16 { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + let mut socket = tungstenite::accept_hdr(stream, take_chat).unwrap(); + let frame = tungstenite::protocol::CloseFrame { + code: code.into(), + reason: reason.into(), + }; + let _ = socket.close(Some(frame)); + while socket.read().is_ok() {} + }); + port +} + +/// The socket events said so far, read one after the other as they come. +struct Heard<'a> { + session: &'a Session, + seen: usize, +} + +impl Heard<'_> { + fn next(&mut self) -> SocketEvent { let waited = std::time::Instant::now(); loop { - let said: Vec = session + let said: Vec = self + .session .heard .events() .into_iter() @@ -96,8 +145,8 @@ fn a_socket_opens_echoes_and_closes_each_step_an_event() { _ => None, }) .collect(); - if let Some(event) = said.get(seen.get()) { - seen.set(seen.get() + 1); + if let Some(event) = said.get(self.seen) { + self.seen += 1; return event.clone(); } assert!( @@ -106,42 +155,74 @@ fn a_socket_opens_echoes_and_closes_each_step_an_event() { ); thread::sleep(Duration::from_millis(10)); } - }; - let (port, agent) = echo(); + } +} +fn opened_on_echo(session: &Session) -> (Heard<'_>, u16) { + let (port, _) = echo(); session .wait(|e| connect_websocket(e, request(&format!("ws://127.0.0.1:{port}/")))) .unwrap(); - // The handshake is composed like a request: it names the application too. + let mut heard = Heard { session, seen: 0 }; + assert!(matches!(heard.next(), SocketEvent::Opened { .. })); + (heard, port) +} + +#[test] +fn a_socket_answers_locked_before_a_library_is_open() { + let session = Session::locked(); + assert_eq!( - agent - .recv_timeout(Duration::from_secs(5)) - .unwrap() - .as_deref(), - Some(engine::http::send::USER_AGENT) + code(session.wait(|e| connect_websocket(e, request("ws://127.0.0.1:1/")))), + ErrorCode::Locked ); +} + +/// The handshake is composed like a request — it names the application — and asks for the +/// subprotocols in order: the one the server took is said as it opens, on the socket's scheme. +#[test] +fn a_socket_opens_naming_the_application_and_the_protocol_taken() { + let session = Session::open(); + let (port, agent) = echo(); + + session + .wait(|e| connect_websocket(e, request(&format!("127.0.0.1:{port}/live")))) + .unwrap(); + + let named = agent.recv_timeout(Duration::from_secs(5)).unwrap(); + assert_eq!(named.as_deref(), Some(engine::http::send::USER_AGENT)); + let opened = Heard { + session: &session, + seen: 0, + } + .next(); assert_eq!( - next(), + opened, SocketEvent::Opened { - url: format!("ws://127.0.0.1:{port}/"), + url: format!("ws://127.0.0.1:{port}/live"), protocol: Some("chat".to_string()) } ); +} - assert!( - session - .call(|e| send_websocket(e, "socket-1", "hello".to_string())) - .unwrap() - ); +/// Each text written and each read is an event, with its size. +#[test] +fn a_text_sent_and_its_answer_are_each_an_event() { + let session = Session::open(); + let (mut heard, _) = opened_on_echo(&session); + + let sent = session.call(|e| send_websocket(e, "socket-1", "hello".to_string())); + + assert!(sent.unwrap()); assert_eq!( - next(), + heard.next(), SocketEvent::Sent { text: "hello".to_string(), size: 5 } ); assert_eq!( - next(), + heard.next(), SocketEvent::Received { text: "echo: hello".to_string(), size: 11, @@ -149,9 +230,18 @@ fn a_socket_opens_echoes_and_closes_each_step_an_event() { cut: false } ); +} + +/// Closed, a socket is gone: closing it says so, and what is written after goes nowhere. +#[test] +fn a_socket_closed_takes_nothing_more() { + let session = Session::open(); + let (mut heard, _) = opened_on_echo(&session); assert!(session.call(|e| close_websocket(e, "socket-1")).unwrap()); - assert!(matches!(next(), SocketEvent::Closed { .. })); + + assert!(matches!(heard.next(), SocketEvent::Closed { .. })); + assert!(!session.call(|e| close_websocket(e, "socket-1")).unwrap()); assert!( !session .call(|e| send_websocket(e, "socket-1", "late".to_string())) @@ -159,43 +249,113 @@ fn a_socket_opens_echoes_and_closes_each_step_an_event() { ); } -/// `wss://nexistepas.invalid` answered « Erreur réseau » where the same host over HTTP answered -/// « Le nom d'hôte ne se résout pas »; and `https://` in a socket was dialled without a word. +/// The log shows, it does not archive: a long message crosses cut on a character's edge, its +/// size whole. #[test] -fn a_socket_names_a_host_that_does_not_resolve_and_refuses_a_scheme_that_is_not_its_own() { +fn a_long_message_crosses_cut_its_size_whole() { let session = Session::open(); - // `.invalid` is reserved never to resolve. - assert_eq!( - code(session.wait(|e| connect_websocket(e, request("ws://devnotes.invalid/")))), - ErrorCode::HttpUnresolved - ); + let (mut heard, _) = opened_on_echo(&session); + let long = "é".repeat(40_000); - let refused = session - .wait(|e| connect_websocket(e, request("https://echo.exemple.fr/live?x=1"))) - .unwrap_err(); - assert_eq!(refused.code, ErrorCode::HttpWebsocketScheme); + session + .call(|e| send_websocket(e, "socket-1", long.clone())) + .unwrap(); + + let SocketEvent::Sent { text, size } = heard.next() else { + panic!("not sent") + }; + assert_eq!(size, 80_000); + assert!(text.len() <= engine::http::websocket::MESSAGE_SHOWN && long.starts_with(&text)); + let SocketEvent::Received { + text, size, cut, .. + } = heard.next() + else { + panic!("not received") + }; + assert!(cut); + assert_eq!(size, 80_006); + assert!(text.len() <= engine::http::websocket::MESSAGE_SHOWN && text.starts_with("echo: é")); +} + +/// The server closing says its code and its reason. +#[test] +fn a_server_closing_says_its_code_and_reason() { + let session = Session::open(); + let port = closer(4001, "bye"); + + session + .wait(|e| connect_websocket(e, request(&format!("ws://127.0.0.1:{port}/")))) + .unwrap(); + + let mut heard = Heard { + session: &session, + seen: 0, + }; + assert!(matches!(heard.next(), SocketEvent::Opened { .. })); assert_eq!( - refused.params.get("twin").map(String::as_str), - Some("wss://echo.exemple.fr/live?x=1") + heard.next(), + SocketEvent::Closed { + code: Some(4001), + reason: "bye".to_string() + } ); - let refused = session - .wait(|e| connect_websocket(e, request("ftp://exemple.fr"))) - .unwrap_err(); - assert_eq!(refused.code, ErrorCode::HttpWebsocketScheme); - assert_eq!(refused.params.get("twin"), None); } +/// `https://` in a socket was dialled without a word, and failed « Erreur réseau »: a scheme +/// not its own is refused before anything is tried, with its twin when it has one. +#[test] +fn a_scheme_that_is_not_a_socket_s_is_refused_with_its_twin() { + let session = Session::open(); + + for (url, twin) in [ + ( + "https://echo.exemple.fr/live?x=1", + Some("wss://echo.exemple.fr/live?x=1"), + ), + ("HTTP://echo.exemple.fr/", Some("ws://echo.exemple.fr/")), + ("ftp://exemple.fr", None), + ] { + let refused = session + .wait(|e| connect_websocket(e, request(url))) + .unwrap_err(); + + assert_eq!(refused.code, ErrorCode::HttpWebsocketScheme, "{url}"); + assert_eq!( + refused.params.get("twin").map(String::as_str), + twin, + "{url}" + ); + } +} + +/// Named as a request's failure is: a host that does not resolve (`.invalid` never does) once +/// answered « Erreur réseau ». #[test] -fn a_closed_port_and_a_refused_handshake_fail_by_code() { +fn a_host_that_does_not_resolve_is_named_as_such() { + let session = Session::open(); + + let answer = session.wait(|e| connect_websocket(e, request("wss://devnotes.invalid/"))); + + assert_eq!(code(answer), ErrorCode::HttpUnresolved); +} + +#[test] +fn a_closed_port_is_refused() { let session = Session::open(); let closed = TcpListener::bind("127.0.0.1:0").unwrap(); let port = closed.local_addr().unwrap().port(); drop(closed); - assert_eq!( - code(session.wait(|e| connect_websocket(e, request(&format!("ws://127.0.0.1:{port}/"))))), - ErrorCode::HttpRefused - ); + let answer = + session.wait(|e| connect_websocket(e, request(&format!("ws://127.0.0.1:{port}/")))); + + assert_eq!(code(answer), ErrorCode::HttpRefused); +} + +/// A server that answers the handshake with a status is named by it. +#[test] +fn a_handshake_answered_by_a_status_is_named_by_it() { + let session = Session::open(); let plain = TcpListener::bind("127.0.0.1:0").unwrap(); let port = plain.local_addr().unwrap().port(); thread::spawn(move || { @@ -205,9 +365,11 @@ fn a_closed_port_and_a_refused_handshake_fail_by_code() { let _ = stream.write_all(b"HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n"); thread::sleep(Duration::from_secs(1)); }); + let refused = session .wait(|e| connect_websocket(e, request(&format!("ws://127.0.0.1:{port}/")))) .unwrap_err(); + assert_eq!(refused.code, ErrorCode::HttpWebsocketRefused); assert_eq!( refused.params.get("status").map(String::as_str), @@ -215,46 +377,19 @@ fn a_closed_port_and_a_refused_handshake_fail_by_code() { ); } -/// Opens sockets over TLS with a certificate nobody signed, for 127.0.0.1. -fn self_signed_echo() -> u16 { - let certified = rcgen::generate_simple_self_signed(vec!["127.0.0.1".to_string()]).unwrap(); - let key = rustls::pki_types::PrivateKeyDer::Pkcs8(certified.signing_key.serialize_der().into()); - let provider = std::sync::Arc::new(rustls::crypto::ring::default_provider()); - let config = rustls::ServerConfig::builder_with_provider(provider) - .with_safe_default_protocol_versions() - .unwrap() - .with_no_client_auth() - .with_single_cert(vec![certified.cert.der().clone()], key) - .unwrap(); - let config = std::sync::Arc::new(config); - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let port = listener.local_addr().unwrap().port(); - thread::spawn(move || { - for stream in listener.incoming().flatten() { - let connection = rustls::ServerConnection::new(std::sync::Arc::clone(&config)).unwrap(); - let tls = rustls::StreamOwned::new(connection, stream); - thread::spawn(move || { - if let Ok(mut socket) = tungstenite::accept_hdr(tls, take_chat) { - while socket.read().is_ok() {} - } - }); - } - }); - port -} - +/// A certificate nobody signed is refused while TLS is checked, and taken once it is not. #[test] fn a_self_signed_server_opens_only_with_the_check_off() { let session = Session::open(); let port = self_signed_echo(); let url = format!("wss://127.0.0.1:{port}/"); - - let checked = session.wait(|e| connect_websocket(e, request(&url))); - assert_eq!(code(checked), ErrorCode::HttpTls); - let mut unchecked = request(&url); unchecked.id = "socket-2".to_string(); unchecked.document.transport.verify_tls = Some(false); + + let checked = session.wait(|e| connect_websocket(e, request(&url))); let opened = session.wait(|e| connect_websocket(e, unchecked)); + + assert_eq!(code(checked), ErrorCode::HttpTls); assert!(opened.is_ok(), "{opened:?}"); } From f18296084b89fab0967f1f0f0d9a8fcaffbd7ed3 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 17:20:27 +0100 Subject: [PATCH 41/95] HTTP collections: unit tests rewritten for the tree and services (#1764) * Rewrite the tests of the HTTP collections: the tree, moving, copying, settings and the services Co-Authored-By: Claude Opus 5.5 * A rank out of range, folders before requests of one rank, the place left closing up and a loose request's own headers, each held Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/http/store.rs | 55 -- crates/engine/tests/commands/http.rs | 604 +++++++---------- crates/engine/tests/http.rs | 925 ++++++++++++++++++--------- 3 files changed, 856 insertions(+), 728 deletions(-) diff --git a/crates/engine/src/http/store.rs b/crates/engine/src/http/store.rs index 2e0acbfac..03cba6e5a 100644 --- a/crates/engine/src/http/store.rs +++ b/crates/engine/src/http/store.rs @@ -1105,58 +1105,3 @@ pub fn inherited( } Ok(super::settings::inherit(&levels)) } - -#[cfg(test)] -mod tests { - use super::super::model::{HttpMethod, RequestDocument, RequestKind}; - use super::*; - - /// A damaged library whose folders name each other as parents: every walk up or down ends - /// (#1477, N34). - #[test] - fn a_cycle_of_folders_ends_every_walk() { - let mut library = crate::db::open_in_memory().unwrap(); - let now = chrono::Utc::now(); - let collection = create_collection(&mut library, "API", now).unwrap(); - let a = create_folder(&mut library, &collection.id, None, "a", now).unwrap(); - let b = create_folder(&mut library, &collection.id, Some(&a.id), "b", now).unwrap(); - diesel::update(http_folders::table.find(&a.id)) - .set(http_folders::parent_id.eq(&b.id)) - .execute(library.db()) - .unwrap(); - - let (done, finished) = std::sync::mpsc::channel(); - let (collection_id, b_id) = (collection.id.clone(), b.id.clone()); - std::thread::spawn(move || { - let _ = inherited(&mut library, &collection_id, Some(&b_id)); - let _ = descendants(library.db(), &b_id); - done.send(()).unwrap(); - }); - - assert!( - finished - .recv_timeout(std::time::Duration::from_secs(5)) - .is_ok(), - "a walk never ended" - ); - } - - #[test] - fn a_position_out_of_range_reads_as_the_first() { - assert_eq!(rank(-3), 0); - assert_eq!(rank(7), 7); - } - - #[test] - fn an_unknown_kind_or_method_degrades_to_the_default() { - assert_eq!( - "TRACE".parse::().unwrap_or_default(), - HttpMethod::Get - ); - assert_eq!( - "grpc".parse::().unwrap_or_default(), - RequestKind::Http - ); - assert!(serde_json::from_str::("{}").is_ok()); - } -} diff --git a/crates/engine/tests/commands/http.rs b/crates/engine/tests/commands/http.rs index c95591eab..4ccecf139 100644 --- a/crates/engine/tests/commands/http.rs +++ b/crates/engine/tests/commands/http.rs @@ -1,466 +1,300 @@ use engine::error::ErrorCode; +use engine::http::environments::Variable; use engine::http::model::{ - HttpItem, HttpItemKind, HttpMethod, HttpNode, HttpPlace, HttpRequestDraft, HttpRequestPatch, - NewPlace, RequestDocument, RequestKind, + ContainerSettings, HttpItem, HttpItemKind, HttpMethod, HttpNode, HttpRequestDraft, + HttpRequestPatch, KeyValue, NewPlace, RequestBody, RequestDocument, RequestKind, RunEntry, }; +use engine::http::query::QuerySide; use engine::http::{ - count_http_contents, create_http_collection, create_http_folder, create_http_request, - create_http_request_in, delete_http_item, duplicate_http_item, get_http_request, http_tree, - move_http_item, rename_http_item, reorder_http_collection, save_http_request, + check_http_headers, create_http_collection, create_http_folder, create_http_request, + create_http_request_in, describe_http_body, duplicate_http_item, http_settings, http_tree, + implied_http_headers, inherited_http_settings, read_http_headers, rename_http_item, + save_http_request, save_http_run_order, save_http_settings, search_http_requests, + sync_http_query, }; use super::{Session, code}; -fn item(kind: HttpItemKind, id: &str) -> HttpItem { - HttpItem { - kind, - id: id.to_string(), - } -} - -fn draft(collection_id: &str, folder_id: Option<&str>, name: &str) -> HttpRequestDraft { +fn draft(collection_id: &str, name: &str) -> HttpRequestDraft { HttpRequestDraft { collection_id: collection_id.to_string(), - folder_id: folder_id.map(str::to_string), + folder_id: None, name: name.to_string(), kind: RequestKind::Http, method: HttpMethod::Get, document: RequestDocument { - url: "https://api.exemple.fr".to_string(), + url: format!("https://api.exemple.fr/{name}"), ..RequestDocument::default() }, } } -fn names(session: &Session) -> Vec { - fn walk(nodes: &[HttpNode], into: &mut Vec) { - for node in nodes { - match node { - HttpNode::Folder { folder, children } => { - into.push(folder.name.clone()); - walk(children, into); - } - HttpNode::Request { request } => into.push(request.name.clone()), - } - } - } - let mut seen = Vec::new(); - for node in session.call(http_tree).unwrap().collections { - seen.push(node.collection.name); - walk(&node.children, &mut seen); +fn row(key: &str, value: &str) -> KeyValue { + KeyValue { + key: key.to_string(), + value: value.to_string(), + ..KeyValue::default() } - seen } -#[test] -fn a_collection_is_built_edited_moved_copied_counted_and_deleted() { - let session = Session::open(); - let api = session - .call(|e| create_http_collection(e, " API ")) - .unwrap(); - let other = session - .call(|e| create_http_collection(e, "Autre")) - .unwrap(); - let auth = session - .call(|e| create_http_folder(e, &api.id, None, "Auth")) - .unwrap(); - let login = session - .call(|e| create_http_request(e, &draft(&api.id, Some(&auth.id), "Login"))) - .unwrap(); - assert_eq!(names(&session), vec!["API", "Auth", "Login", "Autre"]); - - let patch = HttpRequestPatch { - name: Some(" Se connecter ".to_string()), - method: Some(HttpMethod::Post), - ..HttpRequestPatch::default() - }; - let saved = session - .call(|e| save_http_request(e, &login.id, &patch)) - .unwrap(); - assert_eq!( - (saved.name.as_str(), saved.method), - ("Se connecter", HttpMethod::Post) - ); - let read = session.call(|e| get_http_request(e, &login.id)).unwrap(); - assert_eq!(read.document.url, "https://api.exemple.fr"); - - session - .call(|e| rename_http_item(e, &item(HttpItemKind::Folder, &auth.id), "Jetons")) - .unwrap(); - let copy = session - .call(|e| { - duplicate_http_item( - e, - &item(HttpItemKind::Request, &login.id), - "Se connecter (copie)", - ) - }) - .unwrap(); +fn collection(session: &Session, name: &str) -> String { session - .call(|e| { - move_http_item( - e, - ©, - &HttpPlace { - collection_id: other.id.clone(), - folder_id: None, - index: 0, - }, - ) - }) - .unwrap(); - session - .call(|e| reorder_http_collection(e, &other.id, 0)) - .unwrap(); - assert_eq!( - names(&session), - vec![ - "Autre", - "Se connecter (copie)", - "API", - "Jetons", - "Se connecter" - ] - ); + .call(|e| create_http_collection(e, name)) + .unwrap() + .id +} - let contents = session - .call(|e| count_http_contents(e, &item(HttpItemKind::Collection, &api.id))) - .unwrap(); - assert_eq!((contents.folders, contents.requests), (1, 1)); - session - .call(|e| delete_http_item(e, &item(HttpItemKind::Collection, &api.id))) - .unwrap(); - assert_eq!(names(&session), vec!["Autre", "Se connecter (copie)"]); +fn collection_item(id: &str) -> HttpItem { + HttpItem { + kind: HttpItemKind::Collection, + id: id.to_string(), + } } #[test] -fn a_blank_name_a_missing_item_and_a_locked_library_are_refused_by_code() { - let session = Session::open(); - assert_eq!( - code(session.call(|e| create_http_collection(e, " "))), - ErrorCode::InvalidInput - ); - assert_eq!( - code(session.call(|e| get_http_request(e, "absent"))), - ErrorCode::HttpItemNotFound - ); - assert_eq!( - code(session.call(|e| rename_http_item(e, &item(HttpItemKind::Request, "absent"), "x"))), - ErrorCode::HttpItemNotFound - ); +fn collections_answer_locked_before_a_library_is_open() { + let session = Session::locked(); + + assert_eq!(code(session.call(http_tree)), ErrorCode::Locked); assert_eq!( - code(session.call(|e| move_http_item( - e, - &item(HttpItemKind::Collection, "c"), - &HttpPlace { - collection_id: "absent".to_string(), - folder_id: None, - index: 0, - } - ))), - ErrorCode::HttpItemNotFound + code(session.call(|e| create_http_collection(e, "API"))), + ErrorCode::Locked ); - - assert_eq!(code(Session::locked().call(http_tree)), ErrorCode::Locked); } +/// Every name is checked before anything is read: a blank one is refused even on a library +/// that is not open, and nothing is written. #[test] -fn a_folder_hands_its_settings_down_and_a_body_says_what_it_implies() { - use engine::http::model::{ContainerSettings, RequestAuth, RequestBody}; - use engine::http::{ - describe_http_body, http_settings, inherited_http_settings, save_http_settings, +fn a_blank_name_is_refused_before_anything_is_read() { + let locked = Session::locked(); + let open = Session::open(); + let api = collection(&open, "API"); + let request = open + .call(|e| create_http_request(e, &draft(&api, "Login"))) + .unwrap(); + let item = HttpItem { + kind: HttpItemKind::Request, + id: request.id.clone(), + }; + let place = |collection: Option<&str>, folder: Option<&str>| NewPlace { + collection: collection.map(str::to_string), + folder: folder.map(str::to_string), + }; + let blank_name = HttpRequestPatch { + name: Some(" ".to_string()), + ..HttpRequestPatch::default() }; + for session in [&locked, &open] { + let answers = [ + session.call(|e| create_http_collection(e, " ")).map(|_| ()), + session + .call(|e| create_http_folder(e, &api, None, "")) + .map(|_| ()), + session + .call(|e| create_http_request(e, &draft(&api, " "))) + .map(|_| ()), + session + .call(|e| create_http_request_in(e, &draft(&api, "Ok"), &place(Some(" "), None))) + .map(|_| ()), + session + .call(|e| create_http_request_in(e, &draft(&api, "Ok"), &place(None, Some("")))) + .map(|_| ()), + session + .call(|e| save_http_request(e, &request.id, &blank_name)) + .map(|_| ()), + session.call(|e| rename_http_item(e, &item, "")), + session + .call(|e| duplicate_http_item(e, &item, " ")) + .map(|_| ()), + ]; + for answer in answers { + assert_eq!(code(answer), ErrorCode::InvalidInput); + } + } + assert_eq!(open.call(http_tree).unwrap().collections.len(), 1); +} + +/// What is created, renamed and copied through the services is trimmed. +#[test] +fn names_typed_through_the_services_are_trimmed() { let session = Session::open(); - let api = session.call(|e| create_http_collection(e, "API")).unwrap(); - let factures = session - .call(|e| create_http_folder(e, &api.id, None, "Factures")) + let api = collection(&session, " API "); + let request = session + .call(|e| create_http_request(e, &draft(&api, " Login "))) .unwrap(); - let bearer = RequestAuth::Bearer { - token: "{{accessToken}}".to_string(), + let item = HttpItem { + kind: HttpItemKind::Request, + id: request.id.clone(), }; - let settings = ContainerSettings { - auth: bearer.clone(), - headers: Vec::new(), - ..ContainerSettings::default() - }; - session - .call(|e| { - save_http_settings( - e, - &item(HttpItemKind::Folder, &factures.id), - settings.clone(), - ) - }) - .unwrap(); - let read = session - .call(|e| http_settings(e, &item(HttpItemKind::Folder, &factures.id))) + session + .call(|e| rename_http_item(e, &item, " Sign in ")) .unwrap(); - assert_eq!(read, settings); - let inherited = session - .call(|e| inherited_http_settings(e, &api.id, Some(&factures.id))) + session + .call(|e| duplicate_http_item(e, &item, " Sign in 2 ")) .unwrap(); - assert_eq!(inherited.auth, bearer); - assert_eq!( - code(session.call(|e| http_settings(e, &item(HttpItemKind::Request, "r")))), - ErrorCode::InvalidInput - ); - let json = || RequestBody::Json { - text: "{\"a\":".to_string(), - }; - let broken = describe_http_body(&json(), HttpMethod::Post).unwrap(); - assert_eq!(broken.content_type.as_deref(), Some("application/json")); - assert!(broken.problem.is_some()); - assert!(!broken.unusual); - // The same body once the method is a `GET`: sent all the same, and said. - for (method, unusual) in [ - (HttpMethod::Get, true), - (HttpMethod::Head, true), - (HttpMethod::Delete, false), - (HttpMethod::Options, false), - ] { - let said = describe_http_body(&json(), method).unwrap(); - assert_eq!(said.unusual, unusual, "{method:?}"); - } - let none = describe_http_body(&RequestBody::None, HttpMethod::Get).unwrap(); + let tree = session.call(http_tree).unwrap(); assert_eq!( - (none.content_type, none.problem, none.unusual), - (None, None, false) + ( + request.name.as_str(), + tree.collections[0].collection.name.as_str() + ), + ("Login", "API") ); + let names: Vec<&str> = tree.collections[0] + .children + .iter() + .map(|node| match node { + HttpNode::Request { request } => request.name.as_str(), + HttpNode::Folder { folder, .. } => folder.name.as_str(), + }) + .collect(); + assert_eq!(names, ["Sign in", "Sign in 2"]); } -/// Key `X-Recette: 1` in a folder's settings was stored as typed, and every request under the -/// folder then failed « this URL cannot be sent ». +/// Key `X-Recette: 1` in a folder's settings was stored as typed, and every request under it +/// then failed: refused where it is typed, named by its row, and nothing saved. #[test] -fn a_header_that_cannot_be_sent_is_refused_in_the_settings_marked_and_read_from_its_line() { - use engine::http::model::{ContainerSettings, HeaderFault, KeyValue}; - use engine::http::{check_http_headers, http_settings, read_http_headers, save_http_settings}; - +fn a_header_that_cannot_be_sent_is_refused_in_the_settings() { let session = Session::open(); - let api = session.call(|e| create_http_collection(e, "API")).unwrap(); - let recette = session - .call(|e| create_http_folder(e, &api.id, None, "Recette")) - .unwrap(); - let row = |key: &str, value: &str, enabled: bool| KeyValue { - enabled, - key: key.to_string(), - value: value.to_string(), - ..KeyValue::default() - }; - let save = |headers: Vec| { - let settings = ContainerSettings { - headers, - ..ContainerSettings::default() - }; - session.call(|e| save_http_settings(e, &item(HttpItemKind::Folder, &recette.id), settings)) - }; - let kept = || { - session - .call(|e| http_settings(e, &item(HttpItemKind::Folder, &recette.id))) - .unwrap() - .headers + let api = collection(&session, "API"); + let item = collection_item(&api); + let with = |key: &str, value: &str| ContainerSettings { + headers: vec![row("Accept", "*/*"), row(key, value)], + ..ContainerSettings::default() }; - let refused = save(vec![row("X-Recette: 1", "rsgfdregr", true)]).unwrap_err(); - assert_eq!(refused.code, ErrorCode::HttpHeaderName); + let name = session + .call(|e| save_http_settings(e, &item, with(" X-Recette: 1 ", "x"))) + .unwrap_err(); + let value = session + .call(|e| save_http_settings(e, &item, with("X-Id", "a\nb"))) + .unwrap_err(); + + assert_eq!(name.code, ErrorCode::HttpHeaderName); assert_eq!( - ( - refused.params.get("header").map(String::as_str), - refused.params.get("source").map(String::as_str) - ), - (Some("X-Recette: 1"), Some("request")) + name.params.get("header").map(String::as_str), + Some("X-Recette: 1") ); - assert!(kept().is_empty()); - - let refused = save(vec![row("X-Trace", "a\nb", true)]).unwrap_err(); - assert_eq!(refused.code, ErrorCode::HttpHeaderValue); + assert_eq!(value.code, ErrorCode::HttpHeaderValue); assert_eq!( - refused.params.get("header").map(String::as_str), - Some("X-Trace") + session.call(|e| http_settings(e, &item)).unwrap(), + ContainerSettings::default() ); +} - // Switched off, it is not sent: kept as typed, beside the one that is. - save(vec![ - row("X-Recette: 1", "rsgfdregr", false), - row("X-Recette", "1", true), - row("X-{{tenant}}", "{{token}}", true), - ]) - .unwrap(); - assert_eq!(kept().len(), 3); +/// The dialog does not hold the run order: the one the runner left is kept through a save. +#[test] +fn saving_settings_keeps_the_run_order_the_runner_left() { + let session = Session::open(); + let api = collection(&session, "API"); + let item = collection_item(&api); + let order = vec![RunEntry { + id: "r-1".to_string(), + enabled: false, + }]; + let variables = vec![Variable { + name: "host".to_string(), + ..Variable::default() + }]; + let with_variables = ContainerSettings { + variables: variables.clone(), + ..ContainerSettings::default() + }; - let faults = check_http_headers(&[ - row("Accept", "*/*", true), - row("X Recette", "1", true), - row("X Recette", "1", false), - ]) - .unwrap(); - assert_eq!(faults, vec![None, Some(HeaderFault::Name), None]); + session + .call(|e| save_http_run_order(e, &item, order.clone())) + .unwrap(); + session + .call(|e| save_http_settings(e, &item, with_variables)) + .unwrap(); - let read = read_http_headers(":authority: api.exemple.fr\nX-Recette: 1\naccept: */*").unwrap(); - assert_eq!( - read, - vec![row("X-Recette", "1", true), row("accept", "*/*", true)] - ); + let saved = session.call(|e| http_settings(e, &item)).unwrap(); + assert_eq!((saved.run_order, saved.variables), (order, variables)); } +/// What a body implies, whether a JSON one reads, whether its method seldom carries one: said, +/// none decided. #[test] -fn the_query_and_its_table_are_kept_in_step_through_the_command() { - use engine::http::query::QuerySide; - use engine::http::sync_http_query; +fn a_body_says_its_type_whether_it_reads_and_whether_it_is_unusual() { + let json = |text: &str| RequestBody::Json { + text: text.to_string(), + }; - let synced = sync_http_query("/x?a=1", &Vec::new(), QuerySide::Url).unwrap(); + let broken = describe_http_body(&json("{\"a\":"), HttpMethod::Get).unwrap(); + let blank = describe_http_body(&json(" "), HttpMethod::Post).unwrap(); + let none = describe_http_body(&RequestBody::None, HttpMethod::Get).unwrap(); - assert_eq!(synced.params[0].key, "a"); + assert_eq!(broken.content_type.as_deref(), Some("application/json")); + assert!(broken.problem.is_some() && broken.unusual); + assert!(blank.problem.is_none() && !blank.unusual); + assert_eq!((none.content_type, none.unusual), (None, false)); } -/// On a library with no collection, a first save sent its reader to the rail and back. The -/// save creates what it lacks, in one write — or writes nothing at all. +/// What a request sends without a row of its own, read as a send reads it: what its collection +/// hands down, or nothing above it when it is filed nowhere yet. #[test] -fn a_first_save_creates_the_collection_or_the_folder_it_lacks_or_nothing_at_all() { +fn the_headers_a_request_sends_unasked_include_what_its_collection_hands_down() { let session = Session::open(); - let before = names(&session).len(); - let new = |collection: Option<&str>, folder: Option<&str>| NewPlace { - collection: collection.map(str::to_string), - folder: folder.map(str::to_string), + let api = collection(&session, "API"); + let item = collection_item(&api); + let settings = ContainerSettings { + headers: vec![row("X-Tenant", "acme")], + ..ContainerSettings::default() }; - - // A collection that does not exist yet: the request at its root, whatever place it named. - let first = session - .call(|e| { - create_http_request_in( - e, - &draft("nowhere", Some("nowhere"), "Santé"), - &new(Some(" Boutique "), None), - ) - }) + session + .call(|e| save_http_settings(e, &item, settings)) .unwrap(); - assert_eq!(first.folder_id, None); - assert_eq!(names(&session)[before..], ["Boutique", "Santé"]); + let document = RequestDocument::default(); - // A folder under the place the draft names — a collection's root, then a folder. - let second = session - .call(|e| { - create_http_request_in( - e, - &draft(&first.collection_id, None, "Lister"), - &new(None, Some("Commandes")), - ) - }) + let filed = session + .call(|e| implied_http_headers(e, RequestKind::Http, &document, Some(api.clone()), None)) .unwrap(); - let commandes = second.folder_id.clone().unwrap(); - session - .call(|e| { - create_http_request_in( - e, - &draft(&first.collection_id, Some(&commandes), "Anciennes"), - &new(None, Some("Archives")), - ) - }) + let loose = session + .call(|e| implied_http_headers(e, RequestKind::Http, &document, None, None)) .unwrap(); - assert_eq!( - names(&session)[before..], - [ - "Boutique", - "Santé", - "Commandes", - "Lister", - "Archives", - "Anciennes" - ] - ); - - // Both at once: the folder goes in the new collection, the request in the folder. - let both = session - .call(|e| { - create_http_request_in( - e, - &draft(&first.collection_id, Some(&commandes), "Chercher"), - &new(Some("Catalogue"), Some("Produits")), - ) - }) + let inherited = session + .call(|e| inherited_http_settings(e, &api, None)) .unwrap(); - assert_ne!(both.collection_id, first.collection_id); - assert_eq!( - names(&session)[before + 6..], - ["Catalogue", "Produits", "Chercher"] - ); - // Refused whole: a request, a folder or a collection without a name, a place that is not - // there — and no collection is left behind, empty, by any of them. - let held = names(&session); - for (request, place) in [ - (draft("nowhere", None, " "), new(Some("Orpheline"), None)), - ( - draft("nowhere", None, "Seule"), - new(Some("Orpheline"), Some(" ")), - ), - (draft("nowhere", None, "Seule"), new(Some(" "), None)), - ] { - assert_eq!( - code(session.call(|e| create_http_request_in(e, &request, &place))), - ErrorCode::InvalidInput - ); - } - assert_eq!( - code(session.call(|e| create_http_request_in( - e, - &draft("absent", None, "Seule"), - &new(None, Some("Dossier")) - ))), - ErrorCode::HttpItemNotFound + assert!( + filed + .iter() + .any(|header| header.name == "X-Tenant" && header.value == "acme") ); - assert_eq!(names(&session), held); + assert!(!loose.iter().any(|header| header.name == "X-Tenant")); + assert!(loose.iter().any(|header| header.name == "User-Agent")); + assert_eq!(inherited.headers[0].header.key, "X-Tenant"); } -/// GraphQL and WebSocket were the last two entries of the method menu: a kind filed among -/// verbs. It is chosen when the request is created, and nothing changes it afterwards. +/// The rules are the model's: the table marks each row, a pasted line becomes rows, the edited +/// side of a query wins. #[test] -fn a_request_is_created_of_its_kind_and_keeps_it_through_an_update_and_a_copy() { - use engine::http::graphql::GraphqlDocument; +fn the_editor_s_helpers_answer_by_the_model_s_rules() { + let faults = check_http_headers(&[row("Ok", "1"), row("Bad name", "1")]).unwrap(); + let rows = read_http_headers("Accept: application/json\nnot a header").unwrap(); + let synced = sync_http_query("https://shop.test/?a=1", &[], QuerySide::Url).unwrap(); + + assert_eq!((faults[0], faults[1].is_some()), (None, true)); + assert_eq!(rows, [row("Accept", "application/json")]); + assert_eq!(synced.params, [row("a", "1")]); +} +/// The palette finds a request by what was typed, ranked by the core. +#[test] +fn the_palette_finds_requests_through_the_service() { let session = Session::open(); - let api = session.call(|e| create_http_collection(e, "API")).unwrap(); - let asked = HttpRequestDraft { - kind: RequestKind::Graphql, - ..draft(&api.id, None, "Produits") - }; - let created = session.call(|e| create_http_request(e, &asked)).unwrap(); - assert_eq!(created.kind, RequestKind::Graphql); + let api = collection(&session, "API"); + for name in ["Login", "Health"] { + session + .call(|e| create_http_request(e, &draft(&api, name))) + .unwrap(); + } - let patch = HttpRequestPatch { - method: Some(HttpMethod::Post), - document: Some(RequestDocument { - graphql: GraphqlDocument { - query: "{ products { id } }".to_string(), - ..GraphqlDocument::default() - }, - ..RequestDocument::default() - }), - ..HttpRequestPatch::default() - }; - let saved = session - .call(|e| save_http_request(e, &created.id, &patch)) - .unwrap(); - assert_eq!( - (saved.kind, saved.method), - (RequestKind::Graphql, HttpMethod::Post) - ); - let read = session.call(|e| get_http_request(e, &created.id)).unwrap(); - assert_eq!(read.kind, RequestKind::Graphql); - assert_eq!(read.document.graphql.query, "{ products { id } }"); + let hits = session.call(|e| search_http_requests(e, "log")).unwrap(); - let copy = session - .call(|e| { - duplicate_http_item( - e, - &item(HttpItemKind::Request, &created.id), - "Produits (copie)", - ) - }) - .unwrap(); - let copied = session.call(|e| get_http_request(e, ©.id)).unwrap(); - assert_eq!(copied.kind, RequestKind::Graphql); - assert_eq!(copied.document.graphql.query, "{ products { id } }"); + let names: Vec<&str> = hits.iter().map(|hit| hit.name.as_str()).collect(); + assert_eq!(names, ["Login"]); } diff --git a/crates/engine/tests/http.rs b/crates/engine/tests/http.rs index 0cf60356e..a98369174 100644 --- a/crates/engine/tests/http.rs +++ b/crates/engine/tests/http.rs @@ -1,11 +1,13 @@ //! The HTTP collections as data: a tree of collections, folders and requests, sealed, ordered //! under each parent, moved, copied and deleted with what they hold. +use diesel::prelude::*; +use engine::db::schema::{http_folders, http_requests}; use engine::db::{Library, open_in_memory}; use engine::error::StorageError; use engine::http::model::{ - HttpItem, HttpItemKind, HttpMethod, HttpNode, HttpPlace, HttpRequestDraft, HttpRequestPatch, - HttpTree, RequestDocument, RequestKind, + ContainerSettings, HttpItem, HttpItemKind, HttpMethod, HttpNode, HttpPlace, HttpRequestDraft, + HttpRequestPatch, HttpTree, KeyValue, RequestAuth, RequestDocument, RequestKind, }; use engine::http::{search, store}; @@ -27,26 +29,34 @@ fn folder( .id } -fn request( - connection: &mut Library, - collection_id: &str, - folder_id: Option<&str>, - name: &str, -) -> String { - let draft = HttpRequestDraft { +fn draft(collection_id: &str, folder_id: Option<&str>, name: &str) -> HttpRequestDraft { + HttpRequestDraft { collection_id: collection_id.to_string(), folder_id: folder_id.map(str::to_string), name: name.to_string(), - kind: RequestKind::Http, - method: HttpMethod::Get, + kind: RequestKind::Graphql, + method: HttpMethod::Patch, document: RequestDocument { url: format!("https://api.exemple.fr/{name}"), ..RequestDocument::default() }, - }; - store::create_request(connection, &draft, name, t0()) - .unwrap() - .id + } +} + +fn request( + connection: &mut Library, + collection_id: &str, + folder_id: Option<&str>, + name: &str, +) -> String { + store::create_request( + connection, + &draft(collection_id, folder_id, name), + name, + t0(), + ) + .unwrap() + .id } fn item(kind: HttpItemKind, id: &str) -> HttpItem { @@ -88,354 +98,715 @@ fn read(connection: &mut Library) -> Vec { outline(&store::tree(connection).unwrap()) } +fn invalid(answer: &Result) -> bool { + matches!(answer, Err(StorageError::Invalid(_))) +} + +fn not_found(answer: &Result) -> bool { + matches!(answer, Err(StorageError::HttpItemNotFound(_))) +} + +/// Collections in the order they were made; under each parent, folders and requests by rank, +/// a folder before a request of the same rank; a new one last. #[test] fn a_collection_reads_back_as_a_tree_in_the_order_things_were_made() { - let mut connection = open_in_memory().unwrap(); - let api = collection(&mut connection, "API Paiements"); - let auth = folder(&mut connection, &api, None, "Auth"); - request(&mut connection, &api, Some(&auth), "Login"); - let factures = folder(&mut connection, &api, None, "Factures"); - request( - &mut connection, - &api, - Some(&factures), - "Lister les factures", - ); - request(&mut connection, &api, Some(&factures), "Une facture"); - request(&mut connection, &api, None, "Santé"); - collection(&mut connection, "Notifications"); + let mut library = open_in_memory().unwrap(); + let api = collection(&mut library, "API"); + collection(&mut library, "Admin"); + let auth = folder(&mut library, &api, None, "Auth"); + request(&mut library, &api, Some(&auth), "Login"); + request(&mut library, &api, None, "Health"); + folder(&mut library, &api, Some(&auth), "Tokens"); assert_eq!( - read(&mut connection), - vec![ - "API Paiements[Auth[Login] Factures[Lister les factures Une facture] Santé]", - "Notifications[]", - ] + read(&mut library), + ["API[Auth[Login Tokens[]] Health]", "Admin[]"] ); } +/// A request is created where its draft says, read back whole, its kind and method as chosen. #[test] -fn names_and_documents_are_sealed_and_the_method_is_not() { - use diesel::prelude::*; - use engine::db::schema::http_requests; +fn a_request_is_created_where_its_draft_says_and_reads_back_whole() { + let mut library = open_in_memory().unwrap(); + let api = collection(&mut library, "API"); + let auth = folder(&mut library, &api, None, "Auth"); - let mut connection = open_in_memory().unwrap(); - let api = collection(&mut connection, "API"); - let id = request(&mut connection, &api, None, "Login"); + let created = store::create_request( + &mut library, + &draft(&api, Some(&auth), "Login"), + "Login", + t0(), + ) + .unwrap(); - let (name, method, document): (String, String, String) = http_requests::table - .find(&id) - .select(( - http_requests::name, - http_requests::method, - http_requests::document, - )) - .first(connection.db()) - .unwrap(); - assert_ne!(name, "Login"); - assert!(!document.contains("api.exemple.fr")); - assert_eq!(method, "GET"); + let read = store::get_request(&mut library, &created.id).unwrap(); + assert_eq!(read, created); + assert_eq!( + (read.folder_id.as_deref(), read.kind, read.method), + (Some(auth.as_str()), RequestKind::Graphql, HttpMethod::Patch) + ); + assert_eq!((read.created_at, read.updated_at), (t0(), t0())); + assert_eq!(read.document.url, "https://api.exemple.fr/Login"); +} - let opened = store::get_request(&mut connection, &id).unwrap(); - assert_eq!(opened.name, "Login"); - assert_eq!(opened.document.url, "https://api.exemple.fr/Login"); +/// A folder of another collection, or one not there, is refused before anything is written. +#[test] +fn a_request_or_folder_is_refused_a_parent_of_another_collection() { + let mut library = open_in_memory().unwrap(); + let api = collection(&mut library, "API"); + let other = collection(&mut library, "Other"); + let elsewhere = folder(&mut library, &other, None, "Elsewhere"); + + assert!(invalid(&store::create_request( + &mut library, + &draft(&api, Some(&elsewhere), "Lost"), + "Lost", + t0() + ))); + assert!(invalid(&store::create_folder( + &mut library, + &api, + Some(&elsewhere), + "Lost", + t0() + ))); + assert!(not_found(&store::create_folder( + &mut library, + "missing", + None, + "Lost", + t0() + ))); + assert!(not_found(&store::create_request( + &mut library, + &draft(&api, Some("missing"), "Lost"), + "Lost", + t0() + ))); + assert_eq!(read(&mut library), ["API[]", "Other[Elsewhere[]]"]); } +/// Saved into a new collection, a request is at its root; into a new folder, under the place +/// the draft names. Refused, it leaves nothing made for it. #[test] -fn a_saved_request_keeps_what_the_patch_left_out_and_moves_its_instant() { - let mut connection = open_in_memory().unwrap(); - let api = collection(&mut connection, "API"); - let id = request(&mut connection, &api, None, "Login"); +fn a_request_s_first_save_makes_its_collection_or_folder_with_it() { + let mut library = open_in_memory().unwrap(); + let api = collection(&mut library, "API"); + let auth = folder(&mut library, &api, None, "Auth"); + let other = collection(&mut library, "Other"); + let elsewhere = folder(&mut library, &other, None, "Elsewhere"); - let patch = HttpRequestPatch { - method: Some(HttpMethod::Post), - ..HttpRequestPatch::default() - }; - let saved = - store::save_request(&mut connection, &id, &patch, Some("Se connecter"), t1()).unwrap(); + store::create_request_in( + &mut library, + &draft(&api, Some(&auth), "Root"), + "Root", + Some("New"), + None, + t0(), + ) + .unwrap(); + store::create_request_in( + &mut library, + &draft(&api, Some(&auth), "Deep"), + "Deep", + None, + Some("Tokens"), + t0(), + ) + .unwrap(); + store::create_request_in( + &mut library, + &draft(&api, None, "Both"), + "Both", + Some("Fresh"), + Some("Inside"), + t0(), + ) + .unwrap(); + let refused = store::create_request_in( + &mut library, + &draft(&api, Some(&elsewhere), "Lost"), + "Lost", + None, + Some("Never"), + t0(), + ); + assert!(invalid(&refused)); assert_eq!( - (saved.name.as_str(), saved.method), - ("Se connecter", HttpMethod::Post) + read(&mut library), + [ + "API[Auth[Tokens[Deep]]]", + "Other[Elsewhere[]]", + "New[Root]", + "Fresh[Inside[Both]]" + ] ); - assert_eq!(saved.document.url, "https://api.exemple.fr/Login"); - assert_eq!((saved.created_at, saved.updated_at), (t0(), t1())); - assert!(matches!( - store::save_request(&mut connection, "absent", &patch, None, t1()), - Err(StorageError::HttpItemNotFound(_)) - )); } +/// What the patch leaves out is untouched; the name apart; the instant moves. #[test] -fn a_request_moves_into_a_folder_at_its_rank_and_the_rest_close_up() { - let mut connection = open_in_memory().unwrap(); - let api = collection(&mut connection, "API"); - let auth = folder(&mut connection, &api, None, "Auth"); - request(&mut connection, &api, Some(&auth), "Login"); - request(&mut connection, &api, Some(&auth), "Logout"); - let refresh = request(&mut connection, &api, None, "Refresh"); +fn a_saved_request_keeps_what_the_patch_left_out_and_moves_its_instant() { + let mut library = open_in_memory().unwrap(); + let api = collection(&mut library, "API"); + let id = request(&mut library, &api, None, "Login"); + let document = RequestDocument { + url: "https://api.exemple.fr/v2/login".to_string(), + ..RequestDocument::default() + }; - store::move_item( - &mut connection, - &item(HttpItemKind::Request, &refresh), - &place(&api, Some(&auth), 1), + let renamed = store::save_request( + &mut library, + &id, + &HttpRequestPatch::default(), + Some("Sign in"), + t1(), + ) + .unwrap(); + let saved = store::save_request( + &mut library, + &id, + &HttpRequestPatch { + method: Some(HttpMethod::Post), + document: Some(document.clone()), + ..HttpRequestPatch::default() + }, + None, + t1(), ) .unwrap(); + + assert_eq!( + (renamed.name.as_str(), renamed.method, renamed.updated_at), + ("Sign in", HttpMethod::Patch, t1()) + ); + assert_eq!(renamed.document.url, "https://api.exemple.fr/Login"); assert_eq!( - read(&mut connection), - vec!["API[Auth[Login Refresh Logout]]"] + (saved.name.as_str(), saved.method, saved.document), + ("Sign in", HttpMethod::Post, document) ); + assert_eq!(saved.created_at, t0()); + assert!(not_found(&store::save_request( + &mut library, + "missing", + &HttpRequestPatch::default(), + None, + t1() + ))); + assert!(not_found(&store::get_request(&mut library, "missing"))); +} - store::move_item( - &mut connection, - &item(HttpItemKind::Folder, &auth), - &place(&api, None, 9), +/// Each kind renamed in place; one not there named. +#[test] +fn a_collection_a_folder_or_a_request_is_renamed() { + let mut library = open_in_memory().unwrap(); + let api = collection(&mut library, "API"); + let auth = folder(&mut library, &api, None, "Auth"); + let login = request(&mut library, &api, Some(&auth), "Login"); + + store::rename( + &mut library, + &item(HttpItemKind::Collection, &api), + "Payments", ) .unwrap(); - store::move_item( - &mut connection, - &item(HttpItemKind::Request, &refresh), - &place(&api, None, 0), + store::rename(&mut library, &item(HttpItemKind::Folder, &auth), "Security").unwrap(); + store::rename( + &mut library, + &item(HttpItemKind::Request, &login), + "Sign in", ) .unwrap(); - assert_eq!( - read(&mut connection), - vec!["API[Refresh Auth[Login Logout]]"] - ); + + assert_eq!(read(&mut library), ["Payments[Security[Sign in]]"]); + for kind in [ + HttpItemKind::Collection, + HttpItemKind::Folder, + HttpItemKind::Request, + ] { + assert!( + not_found(&store::rename(&mut library, &item(kind, "missing"), "x")), + "{kind:?}" + ); + } } +/// What goes with an item is said first — a collection's folders and requests, a folder's +/// folders below and every request among them — then taken with it. #[test] -fn a_folder_cannot_move_into_itself_and_takes_its_contents_to_another_collection() { - let mut connection = open_in_memory().unwrap(); - let api = collection(&mut connection, "API"); - let other = collection(&mut connection, "Autre"); - let outer = folder(&mut connection, &api, None, "Outer"); - let inner = folder(&mut connection, &api, Some(&outer), "Inner"); - request(&mut connection, &api, Some(&inner), "Deep"); - - for target in [&outer, &inner] { - let refused = store::move_item( - &mut connection, - &item(HttpItemKind::Folder, &outer), - &place(&api, Some(target), 0), +fn a_deletion_says_first_what_goes_with_it_then_takes_it() { + let mut library = open_in_memory().unwrap(); + let api = collection(&mut library, "API"); + let auth = folder(&mut library, &api, None, "Auth"); + let tokens = folder(&mut library, &api, Some(&auth), "Tokens"); + request(&mut library, &api, Some(&auth), "Login"); + let refresh = request(&mut library, &api, Some(&tokens), "Refresh"); + request(&mut library, &api, None, "Health"); + let other = collection(&mut library, "Other"); + + let of_collection = + store::contents(&mut library, &item(HttpItemKind::Collection, &api)).unwrap(); + let of_folder = store::contents(&mut library, &item(HttpItemKind::Folder, &auth)).unwrap(); + let of_request = store::contents(&mut library, &item(HttpItemKind::Request, &refresh)).unwrap(); + assert_eq!((of_collection.folders, of_collection.requests), (2, 3)); + assert_eq!((of_folder.folders, of_folder.requests), (1, 2)); + assert_eq!((of_request.folders, of_request.requests), (0, 0)); + + store::delete(&mut library, &item(HttpItemKind::Folder, &auth)).unwrap(); + assert_eq!(read(&mut library), ["API[Health]", "Other[]"]); + assert!(not_found(&store::get_request(&mut library, &refresh))); + store::delete(&mut library, &item(HttpItemKind::Collection, &other)).unwrap(); + for kind in [ + HttpItemKind::Collection, + HttpItemKind::Folder, + HttpItemKind::Request, + ] { + assert!( + not_found(&store::delete(&mut library, &item(kind, "missing"))), + "{kind:?}" + ); + assert!( + not_found(&store::contents(&mut library, &item(kind, "missing"))), + "{kind:?}" ); - assert!(matches!(refused, Err(StorageError::Invalid(error)) if error.field == "folderId")); } +} + +/// Into a folder at its rank, the rest closing up behind; to another rank under its own +/// parent; a rank past the end is the end. +#[test] +fn a_request_moves_to_its_rank_and_the_rest_close_up() { + let mut library = open_in_memory().unwrap(); + let api = collection(&mut library, "API"); + let auth = folder(&mut library, &api, None, "Auth"); + let a = request(&mut library, &api, None, "A"); + request(&mut library, &api, None, "B"); + request(&mut library, &api, Some(&auth), "In"); store::move_item( - &mut connection, - &item(HttpItemKind::Folder, &outer), - &place(&other, None, 0), + &mut library, + &item(HttpItemKind::Request, &a), + &place(&api, Some(&auth), 0), ) .unwrap(); - assert_eq!( - read(&mut connection), - vec!["API[]", "Autre[Outer[Inner[Deep]]]"] - ); - let moved = store::tree(&mut connection).unwrap(); - let HttpNode::Folder { children, .. } = &moved.collections[1].children[0] else { - panic!("Outer is a folder"); - }; - let HttpNode::Folder { children, folder } = &children[0] else { - panic!("Inner is a folder"); - }; - assert_eq!(folder.collection_id, other); - let HttpNode::Request { request } = &children[0] else { - panic!("Deep is a request"); - }; - assert_eq!(request.collection_id, other); + assert_eq!(read(&mut library), ["API[Auth[A In] B]"]); + store::move_item( + &mut library, + &item(HttpItemKind::Request, &a), + &place(&api, Some(&auth), 99), + ) + .unwrap(); + assert_eq!(read(&mut library), ["API[Auth[In A] B]"]); + store::move_item( + &mut library, + &item(HttpItemKind::Request, &a), + &place(&api, None, 0), + ) + .unwrap(); + assert_eq!(read(&mut library), ["API[A Auth[In] B]"]); + store::move_item( + &mut library, + &item(HttpItemKind::Request, &a), + &place(&api, Some(&auth), 0), + ) + .unwrap(); + let tree = store::tree(&mut library).unwrap(); + let ranks: Vec = tree.collections[0] + .children + .iter() + .map(|node| match node { + HttpNode::Folder { folder, .. } => folder.position, + HttpNode::Request { request } => request.position, + }) + .collect(); + assert_eq!(ranks, [0, 1], "the place left closes up"); } +/// A folder takes everything below it, into another collection if need be; it cannot move +/// into itself or below itself, a collection is reordered rather than moved, and a folder of +/// another collection is no place. #[test] -fn a_request_is_refused_a_folder_of_another_collection() { - let mut connection = open_in_memory().unwrap(); - let api = collection(&mut connection, "API"); - let other = collection(&mut connection, "Autre"); - let elsewhere = folder(&mut connection, &other, None, "Ailleurs"); - let id = request(&mut connection, &api, None, "Login"); - - let refused = store::move_item( - &mut connection, - &item(HttpItemKind::Request, &id), - &place(&api, Some(&elsewhere), 0), +fn a_folder_moves_with_what_it_holds_but_never_into_itself() { + let mut library = open_in_memory().unwrap(); + let api = collection(&mut library, "API"); + let other = collection(&mut library, "Other"); + let auth = folder(&mut library, &api, None, "Auth"); + let tokens = folder(&mut library, &api, Some(&auth), "Tokens"); + let refresh = request(&mut library, &api, Some(&tokens), "Refresh"); + let foreign = folder(&mut library, &other, None, "Foreign"); + + for (target, index) in [(&auth, 0), (&tokens, 0)] { + assert!(invalid(&store::move_item( + &mut library, + &item(HttpItemKind::Folder, &auth), + &place(&api, Some(target), index) + ))); + } + assert!(invalid(&store::move_item( + &mut library, + &item(HttpItemKind::Collection, &api), + &place(&other, None, 0) + ))); + assert!(invalid(&store::move_item( + &mut library, + &item(HttpItemKind::Folder, &auth), + &place(&api, Some(&foreign), 0) + ))); + store::move_item( + &mut library, + &item(HttpItemKind::Folder, &auth), + &place(&other, Some(&foreign), 0), + ) + .unwrap(); + + assert_eq!( + read(&mut library), + ["API[]", "Other[Foreign[Auth[Tokens[Refresh]]]]"] + ); + assert_eq!( + store::get_request(&mut library, &refresh) + .unwrap() + .collection_id, + other + ); + assert_eq!( + store::contents(&mut library, &item(HttpItemKind::Collection, &other)) + .unwrap() + .requests, + 1 ); - assert!(matches!(refused, Err(StorageError::Invalid(error)) if error.field == "folderId")); - assert!(matches!( - store::create_folder(&mut connection, &api, Some(&elsewhere), "X", t0()), - Err(StorageError::Invalid(_)) - )); } +/// To its rank among the collections; a rank past the end is the end. #[test] -fn a_deletion_says_first_what_goes_with_it_then_takes_it() { - let mut connection = open_in_memory().unwrap(); - let api = collection(&mut connection, "API"); - let outer = folder(&mut connection, &api, None, "Outer"); - let inner = folder(&mut connection, &api, Some(&outer), "Inner"); - request(&mut connection, &api, Some(&outer), "A"); - request(&mut connection, &api, Some(&inner), "B"); - request(&mut connection, &api, None, "C"); - - let counted = store::contents(&mut connection, &item(HttpItemKind::Folder, &outer)).unwrap(); - assert_eq!((counted.folders, counted.requests), (1, 2)); - let whole = store::contents(&mut connection, &item(HttpItemKind::Collection, &api)).unwrap(); - assert_eq!((whole.folders, whole.requests), (2, 3)); - - store::delete(&mut connection, &item(HttpItemKind::Folder, &outer)).unwrap(); - assert_eq!(read(&mut connection), vec!["API[C]"]); - - store::delete(&mut connection, &item(HttpItemKind::Collection, &api)).unwrap(); - assert!(read(&mut connection).is_empty()); - assert!(matches!( - store::delete(&mut connection, &item(HttpItemKind::Request, "absent")), - Err(StorageError::HttpItemNotFound(_)) - )); +fn collections_are_reordered_and_a_rank_past_the_end_is_the_end() { + let mut library = open_in_memory().unwrap(); + let a = collection(&mut library, "A"); + collection(&mut library, "B"); + let c = collection(&mut library, "C"); + + store::reorder_collection(&mut library, &c, 0).unwrap(); + store::reorder_collection(&mut library, &a, 99).unwrap(); + + assert_eq!(read(&mut library), ["C[]", "B[]", "A[]"]); + assert!(not_found(&store::reorder_collection( + &mut library, + "missing", + 0 + ))); } +/// Right after its original, under the name given, with everything it held: a request its +/// document, kind and method; a folder or a collection all below it, settings included. #[test] fn a_copy_sits_after_its_original_with_everything_it_held() { - let mut connection = open_in_memory().unwrap(); - let api = collection(&mut connection, "API"); - let auth = folder(&mut connection, &api, None, "Auth"); - let nested = folder(&mut connection, &api, Some(&auth), "Jetons"); - request(&mut connection, &api, Some(&nested), "Refresh"); - let login = request(&mut connection, &api, Some(&auth), "Login"); - request(&mut connection, &api, None, "Santé"); - collection(&mut connection, "Fin"); - - store::duplicate( - &mut connection, + let mut library = open_in_memory().unwrap(); + let api = collection(&mut library, "API"); + let auth = folder(&mut library, &api, None, "Auth"); + let login = request(&mut library, &api, Some(&auth), "Login"); + request(&mut library, &api, None, "Health"); + collection(&mut library, "Last"); + let settings = ContainerSettings { + auth: RequestAuth::Bearer { + token: "{{token}}".to_string(), + }, + ..ContainerSettings::default() + }; + store::save_settings(&mut library, &item(HttpItemKind::Folder, &auth), &settings).unwrap(); + store::save_settings( + &mut library, + &item(HttpItemKind::Collection, &api), + &settings, + ) + .unwrap(); + + let request_copy = store::duplicate( + &mut library, &item(HttpItemKind::Request, &login), - "Login (copie)", + "Login 2", t1(), ) .unwrap(); - store::duplicate( - &mut connection, + let folder_copy = store::duplicate( + &mut library, &item(HttpItemKind::Folder, &auth), - "Auth (copie)", + "Auth 2", t1(), ) .unwrap(); - let copy = store::duplicate( - &mut connection, + let collection_copy = store::duplicate( + &mut library, &item(HttpItemKind::Collection, &api), - "API (copie)", + "API 2", t1(), ) .unwrap(); - let auth_tree = "Auth[Jetons[Refresh] Login Login (copie)]"; - let copied_auth = "Auth (copie)[Jetons[Refresh] Login Login (copie)]"; assert_eq!( - read(&mut connection), - vec![ - format!("API[{auth_tree} {copied_auth} Santé]"), - format!("API (copie)[{auth_tree} {copied_auth} Santé]"), - "Fin[]".to_string(), + read(&mut library), + [ + "API[Auth[Login Login 2] Auth 2[Login Login 2] Health]", + "API 2[Auth[Login Login 2] Auth 2[Login Login 2] Health]", + "Last[]" ] ); - assert_eq!(copy.kind, HttpItemKind::Collection); - assert_ne!(copy.id, api); + let copied = store::get_request(&mut library, &request_copy.id).unwrap(); + let original = store::get_request(&mut library, &login).unwrap(); + assert_eq!( + (copied.document, copied.kind, copied.method), + (original.document, original.kind, original.method) + ); + assert_eq!((copied.created_at, copied.updated_at), (t1(), t1())); + assert_eq!( + store::settings(&mut library, &folder_copy).unwrap(), + settings + ); + assert_eq!( + store::settings(&mut library, &collection_copy).unwrap(), + settings + ); + assert!(not_found(&store::duplicate( + &mut library, + &item(HttpItemKind::Request, "missing"), + "x", + t1() + ))); } +/// A collection's or a folder's own, read back as saved; a request has none of its own. #[test] -fn collections_are_reordered_and_a_rank_past_the_end_is_the_end() { - let mut connection = open_in_memory().unwrap(); - let first = collection(&mut connection, "Un"); - collection(&mut connection, "Deux"); - collection(&mut connection, "Trois"); - - store::reorder_collection(&mut connection, &first, 99).unwrap(); - assert_eq!(read(&mut connection), vec!["Deux[]", "Trois[]", "Un[]"]); +fn a_collection_or_a_folder_keeps_settings_and_a_request_has_none() { + let mut library = open_in_memory().unwrap(); + let api = collection(&mut library, "API"); + let login = request(&mut library, &api, None, "Login"); + let settings = ContainerSettings { + headers: vec![KeyValue { + key: "X-Tenant".to_string(), + value: "acme".to_string(), + ..KeyValue::default() + }], + ..ContainerSettings::default() + }; - store::rename( - &mut connection, - &item(HttpItemKind::Collection, &first), - "Premier", + assert_eq!( + store::settings(&mut library, &item(HttpItemKind::Collection, &api)).unwrap(), + ContainerSettings::default() + ); + store::save_settings( + &mut library, + &item(HttpItemKind::Collection, &api), + &settings, ) .unwrap(); - store::reorder_collection(&mut connection, &first, 0).unwrap(); + assert_eq!( - read(&mut connection), - vec!["Premier[]", "Deux[]", "Trois[]"] + store::settings(&mut library, &item(HttpItemKind::Collection, &api)).unwrap(), + settings ); + assert!(invalid(&store::settings( + &mut library, + &item(HttpItemKind::Request, &login) + ))); + assert!(invalid(&store::save_settings( + &mut library, + &item(HttpItemKind::Request, &login), + &settings + ))); + assert!(not_found(&store::save_settings( + &mut library, + &item(HttpItemKind::Folder, "missing"), + &settings + ))); + assert!(not_found(&store::settings( + &mut library, + &item(HttpItemKind::Folder, "missing") + ))); } +/// The collection, then each folder down to the request's own: the nearest auth wins and every +/// header above is handed down. #[test] -fn a_request_inherits_the_nearest_auth_and_every_header_above_it() { - use engine::http::model::{ContainerSettings, KeyValue, RequestAuth}; - - let mut connection = open_in_memory().unwrap(); - let api = collection(&mut connection, "API Paiements"); - let factures = folder(&mut connection, &api, None, "Factures"); - let archives = folder(&mut connection, &api, Some(&factures), "Archives"); - let bearer = RequestAuth::Bearer { - token: "{{accessToken}}".to_string(), +fn a_request_inherits_from_its_collection_down_to_its_folder() { + let mut library = open_in_memory().unwrap(); + let api = collection(&mut library, "API"); + let auth = folder(&mut library, &api, None, "Auth"); + let tokens = folder(&mut library, &api, Some(&auth), "Tokens"); + let header = |key: &str| ContainerSettings { + headers: vec![KeyValue { + key: key.to_string(), + value: "1".to_string(), + ..KeyValue::default() + }], + auth: RequestAuth::Bearer { + token: key.to_string(), + }, + ..ContainerSettings::default() }; store::save_settings( - &mut connection, + &mut library, &item(HttpItemKind::Collection, &api), - &ContainerSettings { - auth: bearer.clone(), - headers: vec![KeyValue { - key: "Accept".to_string(), - value: "application/json".to_string(), - ..KeyValue::default() - }], - ..ContainerSettings::default() - }, + &header("X-Api"), ) .unwrap(); + store::save_settings( + &mut library, + &item(HttpItemKind::Folder, &tokens), + &header("X-Tokens"), + ) + .unwrap(); + + let inherited = store::inherited(&mut library, &api, Some(&tokens)).unwrap(); - let inherited = store::inherited(&mut connection, &api, Some(&archives)).unwrap(); - assert_eq!(inherited.auth, bearer); + let headers: Vec<(&str, &str)> = inherited + .headers + .iter() + .map(|known| (known.header.key.as_str(), known.from.name.as_str())) + .collect(); + assert_eq!(headers, [("X-Api", "API"), ("X-Tokens", "Tokens")]); assert_eq!( - inherited.auth_from.map(|from| (from.kind, from.name)), - Some((HttpItemKind::Collection, "API Paiements".to_string())) + inherited.auth, + RequestAuth::Bearer { + token: "X-Tokens".to_string() + } ); - assert_eq!(inherited.headers[0].header.key, "Accept"); + let layers: Vec<&str> = inherited + .variables + .iter() + .map(|layer| layer.from.as_str()) + .collect(); + assert_eq!(layers, ["Tokens", "Auth", "API"]); + assert!(not_found(&store::inherited(&mut library, "missing", None))); +} - let saved = store::settings(&mut connection, &item(HttpItemKind::Collection, &api)).unwrap(); - assert_eq!(saved.auth, bearer); - assert!(matches!( - store::settings(&mut connection, &item(HttpItemKind::Request, "r")), - Err(StorageError::Invalid(_)) - )); +/// A damaged library whose folders name each other as parents: every walk up or down ends (a +/// defect once met). +#[test] +fn a_cycle_of_folders_ends_every_walk() { + let mut library = open_in_memory().unwrap(); + let api = collection(&mut library, "API"); + let a = folder(&mut library, &api, None, "A"); + let b = folder(&mut library, &api, Some(&a), "B"); + request(&mut library, &api, Some(&b), "Inside"); + diesel::update(http_folders::table.find(&a)) + .set(http_folders::parent_id.eq(&b)) + .execute(library.db()) + .unwrap(); + + let contents = store::contents(&mut library, &item(HttpItemKind::Folder, &a)).unwrap(); + let inherited = store::inherited(&mut library, &api, Some(&b)).unwrap(); + let hits = search::rank(store::search_candidates(&mut library).unwrap(), "inside"); + + assert_eq!((contents.folders, contents.requests), (1, 1)); + assert_eq!(inherited.variables.len(), 3); + assert_eq!(hits.len(), 1); } +/// A value written by a newer version — a kind, a method — degrades to the default, and a rank +/// out of range reads as the first, rather than hiding the request. #[test] -fn a_body_and_an_auth_are_kept_in_the_sealed_document() { - use engine::http::model::{KeyPlace, RequestAuth, RequestBody}; +fn what_a_newer_version_wrote_degrades_rather_than_hides() { + let mut library = open_in_memory().unwrap(); + let api = collection(&mut library, "API"); + request(&mut library, &api, None, "Later"); + request(&mut library, &api, None, "Odd"); + diesel::update(http_requests::table) + .set(( + http_requests::kind.eq("grpc"), + http_requests::method.eq("PURGE"), + )) + .execute(library.db()) + .unwrap(); + diesel::update(http_requests::table.filter(http_requests::position.eq(1))) + .set(http_requests::position.eq(-5)) + .execute(library.db()) + .unwrap(); - let mut connection = open_in_memory().unwrap(); - let api = collection(&mut connection, "API"); - let id = request(&mut connection, &api, None, "Payer"); - let document = RequestDocument { - url: "/pay".to_string(), - body: RequestBody::Json { - text: r#"{"amount": 4900}"#.to_string(), - }, - auth: RequestAuth::ApiKey { - name: "X-Api-Key".to_string(), - value: "secret".to_string(), - place: KeyPlace::Header, - }, - ..RequestDocument::default() - }; - let patch = HttpRequestPatch { - document: Some(document.clone()), - ..HttpRequestPatch::default() - }; + let tree = store::tree(&mut library).unwrap(); - store::save_request(&mut connection, &id, &patch, None, t1()).unwrap(); + let odd = tree.collections[0] + .children + .iter() + .find_map(|node| match node { + HttpNode::Request { request } if request.name == "Odd" => Some(request), + _ => None, + }) + .unwrap(); + assert_eq!( + (odd.kind, odd.method, odd.position), + (RequestKind::Http, HttpMethod::Get, 0) + ); +} + +/// Of one rank, a folder comes before a request. +#[test] +fn of_one_rank_a_folder_comes_before_a_request() { + let mut library = open_in_memory().unwrap(); + let api = collection(&mut library, "API"); + request(&mut library, &api, None, "Request"); + folder(&mut library, &api, None, "Folder"); + diesel::update(http_folders::table) + .set(http_folders::position.eq(0)) + .execute(library.db()) + .unwrap(); + + assert_eq!(read(&mut library), ["API[Folder[] Request]"]); +} + +/// Found by its sealed URL, and said where it is filed; a document that does not open costs the +/// request its URL, not the search. +#[test] +fn the_palette_finds_a_request_by_its_sealed_url_and_says_where_it_is_filed() { + let mut library = open_in_memory().unwrap(); + let api = collection(&mut library, "API Paiements"); + let factures = folder(&mut library, &api, None, "Factures"); + let archives = folder(&mut library, &api, Some(&factures), "Archives"); + request(&mut library, &api, Some(&archives), "Ancienne facture"); + let broken = request(&mut library, &api, None, "Santé"); + let garbage = library.vault().seal("not json").unwrap(); + diesel::update(http_requests::table.find(&broken)) + .set(http_requests::document.eq(garbage)) + .execute(library.db()) + .unwrap(); + let candidates = store::search_candidates(&mut library).unwrap(); + let hits = search::rank(candidates.clone(), "exemple.fr/ancienne"); + + assert_eq!(hits.len(), 1); + assert_eq!(hits[0].url, "https://api.exemple.fr/Ancienne facture"); + assert_eq!(hits[0].place, ["API Paiements", "Factures", "Archives"]); + let health = candidates + .iter() + .find(|candidate| candidate.hit.name == "Santé") + .unwrap(); assert_eq!( - store::get_request(&mut connection, &id).unwrap().document, - document + (health.hit.url.as_str(), health.hit.place.as_slice()), + ("", ["API Paiements".to_string()].as_slice()) ); } +/// Names and documents are sealed; a request's kind and method are columns, deliberately. +#[test] +fn names_and_documents_are_sealed_and_the_method_is_not() { + let mut library = open_in_memory().unwrap(); + let api = collection(&mut library, "zq-collection"); + let folder_id = folder(&mut library, &api, None, "zq-folder"); + request(&mut library, &api, Some(&folder_id), "zq-request"); + + let rows: Vec<(String, String, String, String)> = http_requests::table + .select(( + http_requests::name, + http_requests::document, + http_requests::kind, + http_requests::method, + )) + .load(library.db()) + .unwrap(); + + let (name, document, kind, method) = &rows[0]; + assert!(!name.contains("zq-") && !document.contains("zq-") && !document.contains("exemple")); + assert_eq!((kind.as_str(), method.as_str()), ("graphql", "PATCH")); +} + /// A row of a table, every string of it marked. fn marked(key: &str, value: &str) -> engine::http::model::KeyValue { engine::http::model::KeyValue { @@ -702,25 +1073,3 @@ fn nothing_typed_or_answered_is_readable_in_the_file_it_was_written_to() { assert!(haystack.contains("PATCH")); assert!(haystack.contains("graphql")); } - -#[test] -fn the_palette_finds_a_request_by_its_sealed_url_and_says_where_it_is_filed() { - let mut connection = open_in_memory().unwrap(); - let api = collection(&mut connection, "API Paiements"); - let factures = folder(&mut connection, &api, None, "Factures"); - let archives = folder(&mut connection, &api, Some(&factures), "Archives"); - request(&mut connection, &api, Some(&archives), "Ancienne facture"); - request(&mut connection, &api, None, "Santé"); - - let hits = search::rank( - store::search_candidates(&mut connection).unwrap(), - "exemple.fr/ancienne", - ); - - assert_eq!(hits.len(), 1); - assert_eq!(hits[0].name, "Ancienne facture"); - assert_eq!(hits[0].url, "https://api.exemple.fr/Ancienne facture"); - assert_eq!(hits[0].place, ["API Paiements", "Factures", "Archives"]); - let everything = search::rank(store::search_candidates(&mut connection).unwrap(), ""); - assert_eq!(everything.len(), 2); -} From f44055e306e51a55d876082530e51e0b7ec75d2b Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 18:05:59 +0100 Subject: [PATCH 42/95] HTTP history: unit tests rewritten for masking and the store (#1759) * Rewrite the tests of the HTTP history: masking, recording, reopening and the store Co-Authored-By: Claude Opus 5.5 * A field typed by hand in a body is named so Sonar does not read it as a credential Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/http/history.rs | 1143 ++++++++++++----------- crates/engine/src/http/history/store.rs | 298 ++++-- 2 files changed, 819 insertions(+), 622 deletions(-) diff --git a/crates/engine/src/http/history.rs b/crates/engine/src/http/history.rs index 2d6973a3c..b5200029c 100644 --- a/crates/engine/src/http/history.rs +++ b/crates/engine/src/http/history.rs @@ -713,6 +713,9 @@ pub fn by_day(items: Vec, tz_offset_minutes: i32) -> Vec KeyValue { KeyValue { @@ -722,6 +725,12 @@ mod tests { } } + fn text(body: &str) -> SentBody { + SentBody::Text { + text: body.to_string(), + } + } + fn exchange(url: &str, headers: Vec, body: SentBody) -> Exchange { Exchange { method: HttpMethod::Post, @@ -731,298 +740,414 @@ mod tests { } } - #[test] - fn the_secrets_are_masked_wherever_they_left_and_the_rest_is_kept() { - let masked = mask( - &exchange( - "https://api.exemple.fr/x?page=1&Key=s3cret#top", - vec![ - header("Authorization", "Bearer abc.def"), - header("Cookie", "session=1"), - header("X-Api-Key", "k"), - header("Accept", "application/json"), - ], - SentBody::None, - ), - &["key".to_string(), "x-api-key".to_string()], - ); - - assert_eq!( - masked.url, - "https://api.exemple.fr/x?page=1&Key=••••••••#top" - ); - assert_eq!( - masked - .headers - .iter() - .map(|header| header.value.as_str()) - .collect::>(), - [ - "Bearer ••••••••", - "••••••••", - "••••••••", - "application/json" - ] - ); - } - - fn answered(exchange: Exchange, secrets: &[&str], response: SentResponse) -> Sent { - Sent { - kind: RequestKind::Http, - name: "Login".to_string(), - request_id: None, - exchange, - secrets: secrets.iter().map(ToString::to_string).collect(), - secret_values: Vec::new(), - environment: None, - outcome: Ok(response), - } - } - - fn answer() -> SentResponse { + fn response(body: &str) -> SentResponse { SentResponse { status: 200, reason: "OK".to_string(), millis: 12, - size: 2, - url: String::new(), + size: 34, + url: "https://shop.test/".to_string(), headers: Vec::new(), - body: "{}".to_string(), + body: body.to_string(), binary: false, cut: false, incomplete: false, redirects: Vec::new(), - language: crate::notes::language::Language::Json, + language: Language::Txt, pretty: None, cookies: Vec::new(), - exchange: exchange("https://api.exemple.fr", Vec::new(), SentBody::None), + exchange: exchange("https://shop.test/", Vec::new(), SentBody::None), graphql: None, - scripts: crate::http::scripts::model::ScriptsAnswer::default(), + scripts: ScriptsAnswer::default(), } } + fn sent( + exchange: Exchange, + outcome: Result)>, + ) -> Sent { + Sent { + kind: RequestKind::Http, + name: "Login".to_string(), + request_id: None, + exchange, + secrets: Vec::new(), + secret_values: Vec::new(), + environment: None, + outcome, + } + } + + fn entry(kind: RequestKind, exchange: Exchange) -> HistoryEntry { + let summary = HistorySummary { + name: "Login".to_string(), + url: exchange.url.clone(), + millis: None, + size: None, + failure: None, + failure_params: BTreeMap::new(), + kind, + method: exchange.method, + status: None, + environment: None, + }; + HistoryEntry { + item: HistoryItem { + id: "h-1".to_string(), + sent_at: crate::db::iso8601::parse("2026-07-25T09:00:00.000Z").unwrap(), + method: exchange.method, + status: None, + request_id: None, + summary, + url_head: String::new(), + url_tail: String::new(), + }, + record: HistoryRecord { + exchange, + response: None, + }, + } + } + + fn value_of<'a>(headers: &'a [KeyValue], key: &str) -> &'a str { + &headers + .iter() + .find(|header| header.key == key) + .unwrap() + .value + } + + /// What repeats is the host, what tells sends apart follows it; its credentials are not + /// shown, and a text that is no URL is all tail. #[test] - fn what_the_request_sent_as_a_secret_is_found_as_it_was_written() { - let found = sent_secrets( - &exchange( - "https://api.exemple.fr/x?page=1&key=cl3-api#top", - vec![ - header("Authorization", "Bearer jeton-collection"), - header("Cookie", "session=s3ss10n; theme=dark"), - header("Accept", "application/json"), - ], - SentBody::None, + fn a_url_is_listed_as_its_host_and_what_follows() { + for (url, parts) in [ + ( + "https://shop.test/orders?page=2", + ("shop.test", "/orders?page=2"), ), - &["key".to_string()], + ( + "https://ada:pw@shop.test:8443#top", + ("shop.test:8443", "#top"), + ), + ("https://shop.test", ("shop.test", "")), + ("{{base}}/orders", ("", "{{base}}/orders")), + ] { + let (head, tail) = url_parts(url); + + assert_eq!((head.as_str(), tail.as_str()), parts, "{url}"); + } + } + + /// An auth keeps its scheme, a cookie and the proxy's auth go whole, an API key's header too; + /// the URL keeps its user but not the password, and a key in its query is masked as written. + #[test] + fn a_request_is_kept_without_its_credentials() { + let leaving = exchange( + "https://ada:s3cret@shop.test/a?api_key=k3y&page=2#top", + vec![ + header("Authorization", "Bearer t0k3n"), + header("authorization", "opaque"), + header("Proxy-Authorization", "Basic abc"), + header("Cookie", "sid=abc"), + header("X-Api-Key", "k3y"), + header("Accept", "application/json"), + ], + text("{}"), ); + let kept = mask(&leaving, &["x-api-key".to_string(), "api_key".to_string()]); + assert_eq!( - found, + kept.url, + format!("https://ada:{MASK}@shop.test/a?api_key={MASK}&page=2#top") + ); + let values: Vec<&str> = kept + .headers + .iter() + .map(|header| header.value.as_str()) + .collect(); + assert_eq!( + values, [ - "Bearer jeton-collection", - "jeton-collection", - "s3ss10n", - "cl3-api", - "dark" + format!("Bearer {MASK}").as_str(), + MASK, + MASK, + MASK, + MASK, + "application/json" ] ); + assert_eq!(kept.body, text("{}")); + assert_eq!( + mask( + &exchange("https://shop.test/a", Vec::new(), SentBody::None), + &[] + ) + .url, + "https://shop.test/a" + ); } - /// HRS-11: an echo service sends the request back; the history keeps it masked. + /// What the console shows: each secret in force as its name, an auth or a cookie masked, + /// an API key's header left, the console knowing no key list. #[test] - fn an_answer_that_says_back_the_auth_sent_is_kept_masked() { - let echoed = "{\"headers\":{\"Authorization\":\"Bearer jeton-collection\"}}"; - let sent = answered( - exchange( - "https://echo.exemple.fr/anything", - vec![header("Authorization", "Bearer jeton-collection")], - SentBody::None, - ), - &[], - SentResponse { - body: echoed.to_string(), - pretty: Some(echoed.to_string()), - ..answer() - }, + fn a_request_is_shown_with_its_secrets_as_their_names() { + let leaving = exchange( + "https://shop.test/?t=t0k3n", + vec![ + header("X-Token", "t0k3n"), + header("Authorization", "Bearer t0k3n"), + ], + text("{\"token\":\"t0k3n\"}"), ); - let (_, record) = record_of(&sent); - let kept = record.response.unwrap(); + let shown = shown(&leaving, &[("token".to_string(), "t0k3n".to_string())]); - assert_eq!(kept.body, "{\"headers\":{\"Authorization\":\"••••••••\"}}"); - assert_eq!(kept.pretty, Some(kept.body.clone())); + assert_eq!(shown.url, "https://shop.test/?t={{token}}"); + assert_eq!(value_of(&shown.headers, "X-Token"), "{{token}}"); + assert_eq!( + value_of(&shown.headers, "Authorization"), + format!("Bearer {MASK}") + ); + assert_eq!(shown.body, text("{\"token\":\"{{token}}\"}")); } - /// #487: a secret variable is kept as its name — in the request, the answer that echoes - /// it, the URL it went to —, never in clear; and the entry says which environment it left with. + /// What the request sent as a secret, as written, the longest first and once: an auth's + /// token and its whole value, each cookie's value, an API key in a header or the query; a + /// value too short, or already written as its name, is no secret to look for. #[test] - fn a_secret_variable_is_kept_as_its_name_wherever_it_shows() { - let mut sent = answered( - exchange( - "https://api.exemple.fr/v1?key=t0k3n-value", - vec![header("X-Token", "t0k3n-value")], - SentBody::Text { - text: "{\"token\":\"t0k3n-value\"}".to_string(), - }, - ), - &[], - SentResponse { - url: "https://api.exemple.fr/v1?key=t0k3n-value".to_string(), - body: "{\"echo\":\"t0k3n-value\"}".to_string(), - pretty: Some("{\n \"echo\": \"t0k3n-value\"\n}".to_string()), - headers: vec![header("X-Echo", "t0k3n-value")], - ..answer() - }, + fn the_secrets_a_request_sent_are_gathered_to_be_masked_in_the_answer() { + let leaving = exchange( + "https://shop.test/?api_key=k3y-in-url&x=1#api_key=frag", + vec![ + header("Authorization", "Bearer t0k3n"), + header("Cookie", "sid=s1d-value; tiny=ab"), + header("X-Api-Key", "k3y-in-header"), + header("X-Other", "not secret"), + header("Proxy-Authorization", "{{proxy}}"), + ], + SentBody::None, ); - sent.secret_values = vec![("token".to_string(), "t0k3n-value".to_string())]; - sent.environment = Some(SentEnvironment { - name: "Staging".to_string(), - colour: crate::folders::model::FolderColour::Amber, - }); - let (summary, record) = record_of(&sent); + let found = sent_secrets(&leaving, &["x-api-key".to_string(), "api_key".to_string()]); - let kept = serde_json::to_string(&(&summary, &record)).unwrap(); - assert!(!kept.contains("t0k3n-value"), "{kept}"); - assert_eq!(record.exchange.headers[0].value, "{{token}}"); - assert_eq!(summary.url, "https://api.exemple.fr/v1?key={{token}}"); assert_eq!( - record - .response - .as_ref() - .map(|response| response.body.as_str()), - Some("{\"echo\":\"{{token}}\"}") + found, + [ + "k3y-in-header", + "Bearer t0k3n", + "k3y-in-url", + "s1d-value", + "t0k3n" + ] ); assert_eq!( - summary.environment.map(|sent| sent.name), - Some("Staging".to_string()) + masked_echo("echo t0k3n and s1d-value", &found), + format!("echo {MASK} and {MASK}") ); } - /// One auth a line: whatever kind left, its secret is not in what is kept. + /// ⚠️ What an answer sets is what the next request sends: a `Set-Cookie` keeps its name and + /// what it is set for, a cookie read from it its name; every URL the answer names is the + /// request's own again, a key in its query masked. #[test] - fn every_kind_of_auth_is_masked_in_the_request_that_is_kept() { - let kept = |name: &str, value: &str, secrets: &[&str]| { - let secrets: Vec = secrets.iter().map(ToString::to_string).collect(); - mask( - &exchange("https://x", vec![header(name, value)], SentBody::None), - &secrets, - ) - .headers[0] - .value - .clone() + fn an_answer_is_kept_without_the_cookies_it_sets_or_the_keys_its_urls_carry() { + let mut answer = response("ok"); + answer.url = "https://shop.test/done?api_key=k3y".to_string(); + answer.headers = vec![ + header("Set-Cookie", "sid=abc; Path=/; HttpOnly"), + header("set-cookie", "bare=1"), + header("Location", "https://shop.test/next?api_key=k3y"), + header("Server", "test"), + ]; + let set = Cookie { + name: "sid".to_string(), + value: "abc".to_string(), + from: Some("https://shop.test/login?api_key=k3y".to_string()), + ..Cookie::default() }; + answer.cookies = vec![set.clone()]; + answer.redirects = vec![Redirect { + status: 302, + url: "https://shop.test/done?api_key=k3y".to_string(), + from: "https://shop.test/login?api_key=k3y".to_string(), + cookies: vec![set], + }]; + let mut leaving = sent( + exchange("https://shop.test/login", Vec::new(), SentBody::None), + Ok(answer), + ); + leaving.secrets = vec!["api_key".to_string()]; - // Basic and Bearer keep their scheme: what kind of auth left is worth knowing. + let (_, record) = record_of(&leaving); + + let kept = record.response.unwrap(); + let masked = format!("api_key={MASK}"); + assert!(kept.url.ends_with(&masked)); assert_eq!( - kept("Authorization", "Basic dXNlcjpodW50ZXIy", &[]), - "Basic ••••••••" + value_of(&kept.headers, "Set-Cookie"), + format!("sid={MASK}; Path=/; HttpOnly") ); assert_eq!( - kept("authorization", "Bearer eyJhbGciOi", &[]), - "Bearer ••••••••" + value_of(&kept.headers, "set-cookie"), + format!("bare={MASK}") ); - // A key in a header goes by the name the request gave it, whatever its case. - assert_eq!(kept("X-Api-Key", "k-123", &["x-api-key"]), "••••••••"); - assert_eq!(kept("X-Api-Key", "k-123", &[]), "k-123"); + assert!(value_of(&kept.headers, "Location").ends_with(&masked)); + assert_eq!(value_of(&kept.headers, "Server"), "test"); assert_eq!( - kept("Proxy-Authorization", "Basic cHJveHk6cHc=", &[]), - "••••••••" + ( + kept.cookies[0].name.as_str(), + kept.cookies[0].value.as_str() + ), + ("sid", MASK) ); - assert_eq!(kept("Cookie", "session=abc; theme=dark", &[]), "••••••••"); + assert!(kept.cookies[0].from.as_deref().unwrap().ends_with(&masked)); + let hop = &kept.redirects[0]; + assert!(hop.url.ends_with(&masked) && hop.from.ends_with(&masked)); + assert_eq!(hop.cookies[0].value, MASK); } - /// A password typed in the URL itself is as much a secret as one typed under « Auth ». + /// A secret variable's value as its name, wherever the answer repeats it; what the request + /// sent as a secret masked wherever the answer says it back — an echo service does. #[test] - fn a_password_in_the_url_is_masked_and_its_user_kept() { - let masked = |url: &str| mask(&exchange(url, Vec::new(), SentBody::None), &[]).url; + fn an_answer_repeating_a_secret_is_kept_without_it() { + let mut answer = response("{\"token\":\"t0k3n\",\"auth\":\"Bearer abc-123\"}"); + answer.pretty = Some("t0k3n abc-123".to_string()); + answer.headers = vec![header("X-Echo", "abc-123")]; + answer.url = "https://shop.test/?t=t0k3n".to_string(); + answer.redirects = vec![Redirect { + status: 301, + url: "https://shop.test/abc-123".to_string(), + from: "https://shop.test/t0k3n".to_string(), + cookies: Vec::new(), + }]; + answer.graphql = Some(GraphqlResult { + data: Some("{\"me\":\"abc-123\"}".to_string()), + errors: vec![GraphqlError { + message: "bad token t0k3n".to_string(), + path: None, + location: None, + }], + }); + let mut leaving = sent( + exchange( + "https://shop.test/", + vec![header("Authorization", "Bearer abc-123")], + SentBody::None, + ), + Ok(answer), + ); + leaving.secret_values = vec![("token".to_string(), "t0k3n".to_string())]; + let (_, record) = record_of(&leaving); + + let kept = record.response.unwrap(); assert_eq!( - masked("https://ada:hunter2@api.exemple.fr/v1?page=2"), - "https://ada:••••••••@api.exemple.fr/v1?page=2" + kept.body, + format!("{{\"token\":\"{{{{token}}}}\",\"auth\":\"{MASK}\"}}") ); - // A user alone, an address with a port, a bracketed one: nothing to mask. assert_eq!( - masked("https://ada@api.exemple.fr/v1"), - "https://ada@api.exemple.fr/v1" + kept.pretty.as_deref(), + Some(format!("{{{{token}}}} {MASK}").as_str()) ); - assert_eq!(masked("http://[::1]:8080/x"), "http://[::1]:8080/x"); + assert_eq!(value_of(&kept.headers, "X-Echo"), MASK); + assert_eq!(kept.url, "https://shop.test/?t={{token}}"); assert_eq!( - masked("http://127.0.0.1:8080/a@b"), - "http://127.0.0.1:8080/a@b" + ( + kept.redirects[0].url.as_str(), + kept.redirects[0].from.as_str() + ), + ( + format!("https://shop.test/{MASK}").as_str(), + "https://shop.test/{{token}}" + ) ); - // Reopened as a draft, the dots do not come back as a password. + let graphql = kept.graphql.unwrap(); assert_eq!( - draft_url("https://ada:••••••••@api.exemple.fr/v1?page=2"), - "https://ada@api.exemple.fr/v1?page=2" + graphql.data.as_deref(), + Some(format!("{{\"me\":\"{MASK}\"}}").as_str()) ); + assert_eq!(graphql.errors[0].message, "bad token {{token}}"); } - /// The answer names the request's URL again — where it came from, each hop — and sets the - /// cookie the next request sends: each was kept whole beside a request that was masked. + /// What is sealed: the request masked, a secret variable as its name, both bodies cut at + /// `BODY_KEPT` on a character's edge, a body cut no longer laid out; the answer's timeline + /// is the masked request. #[test] - fn what_the_answer_repeats_of_the_secrets_is_masked_too() { - let cookie = |from: Option<&str>| Cookie { - name: "session".to_string(), - value: "abc123".to_string(), - from: from.map(str::to_string), - ..Cookie::default() - }; - let response = SentResponse { - url: "https://api.exemple.fr/home?key=s3cret".to_string(), - headers: vec![ - header("Set-Cookie", "session=abc123; Path=/; HttpOnly"), - header("set-cookie", "bare=zzz"), - header("Location", "/next?key=s3cret&page=1"), - header("Content-Type", "application/json"), - ], - cookies: vec![cookie(None)], - redirects: vec![Redirect { - status: 302, - url: "https://api.exemple.fr/home?key=s3cret".to_string(), - from: "https://ada:hunter2@api.exemple.fr/login?key=s3cret".to_string(), - cookies: vec![cookie(Some("https://api.exemple.fr/login?key=s3cret"))], - }], - ..answer() - }; - let (summary, record) = record_of(&answered( + fn a_send_is_recorded_masked_and_cut() { + let long = format!("{}é", "a".repeat(BODY_KEPT - 1)); + let mut answer = response(&long); + answer.pretty = Some("laid out".to_string()); + let mut leaving = sent( exchange( - "https://ada:hunter2@api.exemple.fr/login?key=s3cret", - Vec::new(), - SentBody::None, + "https://shop.test/?q=t0k3n", + vec![header("Authorization", "Bearer t0k3n")], + text(&long), ), - &["key"], - response, - )); + Ok(answer), + ); + leaving.secret_values = vec![("token".to_string(), "t0k3n".to_string())]; - let written = serde_json::to_string(&(&summary, &record)).unwrap(); - for secret in ["s3cret", "abc123", "hunter2", "zzz"] { - assert!(!written.contains(secret), "{secret} is kept in the history"); - } - let kept = record.response.unwrap(); - assert_eq!(kept.url, "https://api.exemple.fr/home?key=••••••••"); + let (summary, record) = record_of(&leaving); + + assert_eq!(record.exchange.url, "https://shop.test/?q={{token}}"); assert_eq!( - kept.headers - .iter() - .map(|header| header.value.as_str()) - .collect::>(), - [ - "session=••••••••; Path=/; HttpOnly", - "bare=••••••••", - "/next?key=••••••••&page=1", - "application/json" - ] + value_of(&record.exchange.headers, "Authorization"), + format!("Bearer {MASK}") ); - // What it was called and where it applies is not the secret. - assert_eq!(kept.cookies[0].name, "session"); + assert_eq!(record.exchange.body, text(&"a".repeat(BODY_KEPT - 1))); + let kept = record.response.unwrap(); + assert_eq!(kept.body.len(), BODY_KEPT - 1); + assert!(kept.cut); + assert_eq!(kept.pretty, None); + assert_eq!(kept.exchange, record.exchange); + assert_eq!(summary.url, "https://shop.test/?q={{token}}"); + } + + /// What a list shows: what was sent, how it went, with what environment; a failure as its + /// code and what its sentence states, and no answer. + #[test] + fn a_send_s_summary_says_how_it_went() { + let environment = SentEnvironment { + name: "Prod".to_string(), + colour: crate::folders::model::FolderColour::Red, + }; + let mut answered = sent( + exchange("https://shop.test/", Vec::new(), SentBody::None), + Ok(response("ok")), + ); + answered.kind = RequestKind::Graphql; + answered.environment = Some(environment.clone()); + let params = BTreeMap::from([("delay".to_string(), "30 s".to_string())]); + let failed = sent( + exchange("https://shop.test/", Vec::new(), SentBody::None), + Err((ErrorCode::HttpTimeout, params.clone())), + ); + + let (summary, _) = record_of(&answered); + let (failure, record) = record_of(&failed); + assert_eq!( - kept.redirects[0].from, - "https://ada:••••••••@api.exemple.fr/login?key=••••••••" + summary, + HistorySummary { + name: "Login".to_string(), + url: "https://shop.test/".to_string(), + millis: Some(12), + size: Some(34), + failure: None, + failure_params: BTreeMap::new(), + kind: RequestKind::Graphql, + method: HttpMethod::Post, + status: Some(200), + environment: Some(environment), + } ); assert_eq!( - kept.redirects[0].cookies[0].from.as_deref(), - Some("https://api.exemple.fr/login?key=••••••••") + (failure.failure, failure.failure_params, failure.status), + (Some(ErrorCode::HttpTimeout), params, None) ); + assert_eq!(record.response, None); } /// Its method and its status were columns the migration dropped, and nothing moved them @@ -1040,424 +1165,326 @@ mod tests { } /// The limit, asserted rather than left to be discovered: the mask knows the secrets a - /// request declares — its auth, its cookies — not one typed by hand in a parameter or a - /// body. Those are kept, sealed like the rest of the record. + /// request declares — its auth, its cookies, its key — not one typed by hand in a parameter + /// or a body. Those are kept, sealed like the rest of the record. #[test] fn a_secret_typed_by_hand_in_a_parameter_or_a_body_is_kept_as_it_was_sent() { - let (summary, record) = record_of(&answered( - exchange( - "https://api.exemple.fr/x?token=typed-by-hand", - Vec::new(), - SentBody::Text { - text: r#"{"password":"in-the-body"}"#.to_string(), - }, - ), - &[], - answer(), - )); + let by_hand = exchange( + "https://api.exemple.fr/x?token=typed-by-hand", + Vec::new(), + text(r#"{"pin":"in-the-body"}"#), + ); + + let (summary, record) = record_of(&sent(by_hand, Ok(response("")))); assert_eq!(summary.url, "https://api.exemple.fr/x?token=typed-by-hand"); - assert_eq!( - record.exchange.body, - SentBody::Text { - text: r#"{"password":"in-the-body"}"#.to_string() - } - ); + assert_eq!(record.exchange.body, text(r#"{"pin":"in-the-body"}"#)); } + /// A secret is typed again, never replayed as dots: a masked header or query pair goes, the + /// URL's user stays without its password; what is written again by itself goes too — the + /// `Content-Type` the body implies, the application's own headers. #[test] - fn a_record_cuts_long_bodies_and_says_how_it_ended() { - let long = "é".repeat(BODY_KEPT); - let sent = Sent { - kind: RequestKind::Http, - name: "Login".to_string(), - request_id: None, - exchange: exchange( - "https://api.exemple.fr", - Vec::new(), - SentBody::Text { text: long.clone() }, - ), - secrets: Vec::new(), - secret_values: Vec::new(), - environment: None, - outcome: Err(( - ErrorCode::HttpTimeout, - BTreeMap::from([("amount".to_string(), "2".to_string())]), - )), - }; + fn a_send_reopened_is_a_draft_without_what_was_masked() { + let recorded = exchange( + &format!("https://ada:{MASK}@shop.test/a?api_key={MASK}&page=2"), + vec![ + header("Authorization", &format!("Bearer {MASK}")), + header("Content-Type", "application/json; charset=utf-8"), + header("User-Agent", "DevNotes/1.3.0"), + header("Accept", "*/*"), + header("X-Trace", "1"), + ], + text("{\"a\":1}"), + ); + + let draft = draft_of(&entry(RequestKind::Http, recorded)); - let (summary, record) = record_of(&sent); - assert_eq!(summary.failure, Some(ErrorCode::HttpTimeout)); assert_eq!( - summary.failure_params.get("amount").map(String::as_str), - Some("2") + (draft.name.as_str(), draft.kind, draft.method), + ("Login", RequestKind::Http, HttpMethod::Post) + ); + assert_eq!(draft.document.url, "https://ada@shop.test/a?page=2"); + let params: Vec<(&str, &str)> = draft + .document + .params + .iter() + .map(|row| (row.key.as_str(), row.value.as_str())) + .collect(); + assert_eq!(params, [("page", "2")]); + assert_eq!(draft.document.headers, [header("X-Trace", "1")]); + assert_eq!( + draft.document.body, + RequestBody::Json { + text: "{\"a\":1}".to_string() + } ); - assert_eq!((summary.millis, record.response), (None, None)); - let SentBody::Text { text } = record.exchange.body else { - panic!("a text body"); - }; - assert!(text.len() <= BODY_KEPT && long.starts_with(&text)); } + /// A text without a JSON type is text; a file or a multipart was not kept; a query of + /// masked pairs alone leaves no `?`. #[test] - fn an_entry_sent_again_leaves_its_secrets_and_implied_type_behind() { - let entry = HistoryEntry { - item: HistoryItem { - id: "h".to_string(), - sent_at: "2026-10-07T10:00:00Z".parse().unwrap(), - method: HttpMethod::Post, - status: Some(201), - request_id: None, - summary: HistorySummary { - kind: RequestKind::Http, - name: "Payer".to_string(), - url: String::new(), - millis: None, - size: None, - failure: None, - failure_params: BTreeMap::new(), - method: HttpMethod::Post, - status: None, - environment: None, - }, - url_head: String::new(), - url_tail: String::new(), - }, - record: HistoryRecord { - exchange: mask( - &exchange( - "https://api.exemple.fr/pay?page=2&key=s3cret", - vec![ - header("Authorization", "Bearer t"), - header("Accept", "application/json"), - header("Content-Type", "application/json"), - header("User-Agent", "DevNotes/0.10.1"), - header("X-Agent", "DevNotes/0.10.1"), - ], - SentBody::Text { - text: "{\"a\":1}".to_string(), - }, - ), - &["key".to_string()], - ), - response: None, - }, + fn a_draft_s_body_is_what_could_be_kept() { + let body = |sent: SentBody, headers: Vec| { + draft_of(&entry( + RequestKind::Http, + exchange(&format!("https://shop.test/?k={MASK}"), headers, sent), + )) + .document }; - let draft = draft_of(&entry); + let plain = body(text("hello"), vec![header("Content-Type", "text/plain")]); + assert_eq!( - (draft.name.as_str(), draft.method), - ("Payer", HttpMethod::Post) + plain.body, + RequestBody::Text { + text: "hello".to_string() + } ); - assert_eq!(draft.document.url, "https://api.exemple.fr/pay?page=2"); - assert_eq!(draft.document.params.len(), 1); + assert_eq!(plain.url, "https://shop.test/"); assert_eq!( - draft - .document - .headers - .iter() - .map(|header| header.key.as_str()) - .collect::>(), - ["Accept", "X-Agent"] + body(text("{}"), Vec::new()).body, + RequestBody::Text { + text: "{}".to_string() + } ); assert_eq!( - draft.document.body, - RequestBody::Json { - text: "{\"a\":1}".to_string() - } + body(SentBody::Bytes { size: 3 }, Vec::new()).body, + RequestBody::None + ); + assert_eq!( + body( + SentBody::Multipart { + fields: vec!["a".to_string()] + }, + Vec::new() + ) + .body, + RequestBody::None ); } - /// Cut at its end, every URL of a host read `https://httpbin.org/hea…`. + /// Back in its two boxes: a `POST`'s JSON body, its variables laid out; a `GET`'s query + /// pairs, leaving the URL the others. One that no longer reads as GraphQL stays HTTP. #[test] - fn a_url_is_read_in_two_parts_the_host_and_what_tells_two_sends_apart() { - let parts = |url: &str| { - let (head, tail) = url_parts(url); - format!("{head}|{tail}") + fn a_graphql_send_reopens_as_graphql() { + let posted = exchange( + "https://shop.test/graphql", + Vec::new(), + text(r#"{"query":"{ me { id } }","variables":{"id":7},"operationName":"Me"}"#), + ); + let got = Exchange { + method: HttpMethod::Get, + ..exchange( + "https://shop.test/graphql?query=%7B+me+%7D&variables=%7B%22a%22%3A1%7D&v=2", + Vec::new(), + SentBody::None, + ) }; + let unreadable = exchange("https://shop.test/graphql", Vec::new(), text("not json")); + + let from_post = draft_of(&entry(RequestKind::Graphql, posted)); + let from_get = draft_of(&entry(RequestKind::Graphql, got)); + let not_graphql = draft_of(&entry(RequestKind::Graphql, unreadable)); + assert_eq!(from_post.kind, RequestKind::Graphql); + assert_eq!(from_post.document.graphql.query, "{ me { id } }"); + assert_eq!(from_post.document.graphql.variables, "{\n \"id\": 7\n}"); assert_eq!( - parts("https://httpbin.org/redirect/3"), - "httpbin.org|/redirect/3" + from_post.document.graphql.operation_name.as_deref(), + Some("Me") ); + assert!(!from_post.document.graphql.as_get && from_post.document.body == RequestBody::None); assert_eq!( - parts("http://127.0.0.1:8080/users?page=2&key=••••••••#top"), - "127.0.0.1:8080|/users?page=2&key=••••••••#top" + ( + from_get.document.graphql.query.as_str(), + from_get.document.graphql.as_get + ), + ("{ me }", true) ); - assert_eq!(parts("https://ada:pw@api.exemple.fr"), "api.exemple.fr|"); - assert_eq!(parts("https://api.exemple.fr?x=1"), "api.exemple.fr|?x=1"); - assert_eq!(parts("pas une URL"), "|pas une URL"); + assert_eq!(from_get.document.graphql.variables, "{\n \"a\": 1\n}"); + assert_eq!(from_get.document.url, "https://shop.test/graphql?v=2"); + assert_eq!(not_graphql.kind, RequestKind::Http); } - fn sent(url: &str, headers: Vec, body: SentBody, secrets: &[&str]) -> HistoryEntry { - let secrets: Vec = secrets.iter().map(ToString::to_string).collect(); - HistoryEntry { - item: HistoryItem { - id: "h".to_string(), - sent_at: "2026-10-07T10:00:00Z".parse().unwrap(), - method: HttpMethod::Post, - status: Some(200), - request_id: Some("r".to_string()), - summary: HistorySummary { - kind: RequestKind::Http, - name: "Payer".to_string(), - url: String::new(), - millis: None, - size: None, - failure: None, - failure_params: BTreeMap::new(), - method: HttpMethod::Post, - status: None, - environment: None, - }, - url_head: String::new(), - url_tail: String::new(), - }, - record: HistoryRecord { - exchange: mask(&exchange(url, headers, body), &secrets), - response: None, - }, - } - } - - fn held(kind: RequestKind, document: RequestDocument) -> HttpRequest { + fn current(kind: RequestKind, document: RequestDocument) -> HttpRequest { + let at = crate::db::iso8601::parse("2026-07-25T09:00:00.000Z").unwrap(); HttpRequest { - id: "r".to_string(), - collection_id: "c".to_string(), + id: "r-1".to_string(), + collection_id: "c-1".to_string(), folder_id: None, - name: "ma req".to_string(), + name: "Saved name".to_string(), kind, method: HttpMethod::Get, document, - created_at: "2026-10-01T00:00:00Z".parse().unwrap(), - updated_at: "2026-10-01T00:00:00Z".parse().unwrap(), + created_at: at, + updated_at: at, } } - /// « Rouvrir » made a stranger of the send; and a mask must never come back as a value. + /// ⚠️ A header kept masked takes the request's own row of that name back — never the dots — + /// or none; one handed down today with the value sent is no change of the request's; a row + /// keeps the request's description. What was sent goes over the request, which keeps its + /// name, its auth and the body a file or a multipart was not kept for. #[test] - fn a_send_goes_back_onto_its_request_with_the_request_s_own_secrets() { - use crate::http::model::{HttpItemKind, KeyPlace, RequestAuth}; - use crate::http::settings::HttpOrigin; - - let entry = sent( - "https://api.exemple.fr/pay?page=2&key=s3cret", - vec![ - header("Authorization", "Bearer old"), - header("X-Token", "s3cret"), - header("X-Client", "web"), - header("X-Trace", "7"), - header("Content-Type", "application/json"), - header("User-Agent", "DevNotes/0.10.1"), - ], - SentBody::Text { - text: "{\"a\":1}".to_string(), - }, - &["key", "x-token"], - ); - let current = held( - RequestKind::Http, - RequestDocument { - url: "https://api.exemple.fr/pay".to_string(), - headers: vec![ - KeyValue { - description: "le jeton du moment".to_string(), - ..header("x-token", "n3w") - }, - KeyValue { - description: "à garder".to_string(), - ..header("X-Trace", "1") - }, - header("X-Gone", "1"), + fn a_send_put_back_onto_its_request_keeps_the_request_s_secrets() { + let recorded = Exchange { + method: HttpMethod::Put, + ..exchange( + "https://shop.test/b?page=3", + vec![ + header("X-Api-Key", MASK), + header("Authorization", &format!("Bearer {MASK}")), + header("X-Tenant", "acme"), + header("X-Trace", "2"), ], - auth: RequestAuth::ApiKey { - name: "key".to_string(), - value: "n3w".to_string(), - place: KeyPlace::Query, + SentBody::Bytes { size: 4 }, + ) + }; + let mine = RequestDocument { + url: "https://shop.test/a".to_string(), + headers: vec![ + KeyValue { + description: "the key".to_string(), + ..header("x-api-key", "{{key}}") }, - description: "Paie une facture".to_string(), - ..RequestDocument::default() + KeyValue { + description: "which trace".to_string(), + ..header("X-Trace", "1") + }, + ], + body: RequestBody::Binary { + path: "/dump.bin".to_string(), }, - ); - let above = vec![InheritedHeader { - header: header("x-client", "web"), - from: HttpOrigin { - kind: HttpItemKind::Collection, - id: "c".to_string(), - name: "API".to_string(), + auth: RequestAuth::Bearer { + token: "{{token}}".to_string(), + }, + ..RequestDocument::default() + }; + let above = [InheritedHeader { + header: header("X-Tenant", "acme"), + from: crate::http::settings::HttpOrigin { + kind: crate::http::model::HttpItemKind::Collection, + id: "c-1".to_string(), + name: "Shop".to_string(), }, }]; - let draft = onto(&entry, ¤t, &above); + let put_back = onto( + &entry(RequestKind::Http, recorded), + ¤t(RequestKind::Http, mine.clone()), + &above, + ); assert_eq!( - (draft.name.as_str(), draft.method), - ("ma req", HttpMethod::Post) + (put_back.name.as_str(), put_back.kind, put_back.method), + ("Saved name", RequestKind::Http, HttpMethod::Put) ); - // The key the auth writes is the auth's still, and no dot is in the URL. - assert_eq!(draft.document.url, "https://api.exemple.fr/pay?page=2"); - assert_eq!(draft.document.params.len(), 1); - assert_eq!(draft.document.auth, current.document.auth); - assert_eq!(draft.document.description, "Paie une facture"); + assert_eq!(put_back.document.url, "https://shop.test/b?page=3"); + assert_eq!(put_back.document.params.len(), 1); assert_eq!( - draft.document.body, - RequestBody::Json { - text: "{\"a\":1}".to_string() - } + put_back.document.headers, + [ + mine.headers[0].clone(), + KeyValue { + description: "which trace".to_string(), + ..header("X-Trace", "2") + }, + ] ); - // Masked: the request's own row, as it is now. Sent: its value, the row's description. - // Handed down, implied or written by the auth: no row of the request's. assert_eq!( - draft - .document - .headers - .iter() - .map(|row| ( - row.key.as_str(), - row.value.as_str(), - row.description.as_str() - )) - .collect::>(), - vec![ - ("x-token", "n3w", "le jeton du moment"), - ("X-Trace", "7", "à garder"), - ] + (&put_back.document.body, &put_back.document.auth), + (&mine.body, &mine.auth) ); - assert!(!format!("{draft:?}").contains(MASK)); } - /// Reopened as a draft, a GraphQL send was an HTTP `POST` with a JSON body. + /// A text body or none goes over the request's; a GraphQL request takes its query back and + /// keeps its method. #[test] - fn a_send_reopened_as_a_draft_is_of_the_kind_that_was_sent() { - let mut posted = sent( - "https://api.exemple.fr/graphql", - vec![header("X-Trace", "1")], - SentBody::Text { - text: r#"{"query":"{ me }"}"#.to_string(), - }, - &[], - ); - assert_eq!(draft_of(&posted).kind, RequestKind::Http); - - posted.item.summary.kind = RequestKind::Graphql; - let draft = draft_of(&posted); - assert_eq!(draft.kind, RequestKind::Graphql); - assert_eq!(draft.document.graphql.query, "{ me }"); - assert_eq!(draft.document.body, RequestBody::None); - assert_eq!(draft.document.headers.len(), 1); - - // Said to be GraphQL and not reading as one: sent again as what it was on the wire. - let odd = HistoryEntry { - item: posted.item.clone(), - record: HistoryRecord { - exchange: exchange("https://api.exemple.fr/graphql", Vec::new(), SentBody::None), - response: None, + fn a_send_put_back_takes_its_body_or_its_graphql() { + let mine = RequestDocument { + body: RequestBody::Json { + text: "{\"old\":1}".to_string(), }, + ..RequestDocument::default() }; - assert_eq!(draft_of(&odd).kind, RequestKind::Http); - } - - #[test] - fn a_graphql_send_goes_back_into_its_query_and_variables_and_a_file_is_left_alone() { - let posted = sent( - "https://api.exemple.fr/graphql", + let texted = exchange("https://shop.test/", Vec::new(), text("new")); + let posted = exchange( + "https://shop.test/graphql?x=1", Vec::new(), - SentBody::Text { - text: r#"{"query":"query Me { me }","variables":{"n":12345678901234567890},"operationName":"Me"}"#.to_string(), - }, - &[], - ); - let current = held(RequestKind::Graphql, RequestDocument::default()); - let draft = onto(&posted, ¤t, &[]); - assert_eq!(draft.method, HttpMethod::Get); - assert_eq!(draft.document.url, "https://api.exemple.fr/graphql"); - assert_eq!( - draft.document.graphql, - GraphqlDocument { - query: "query Me { me }".to_string(), - variables: "{\n \"n\": 12345678901234567890\n}".to_string(), - operation_name: Some("Me".to_string()), - as_get: false, - } + text(r#"{"query":"{ me }"}"#), ); - let got = sent( - "https://api.exemple.fr/graphql?query=%7B%20me%20%7D&variables=%7B%22a%22%3A1%7D&trace=1", - Vec::new(), - SentBody::None, + let http = onto( + &entry(RequestKind::Http, texted), + ¤t(RequestKind::Http, mine.clone()), &[], ); - let draft = onto(&got, ¤t, &[]); - assert_eq!(draft.document.url, "https://api.exemple.fr/graphql?trace=1"); - assert_eq!(draft.document.graphql.query, "{ me }"); - assert_eq!(draft.document.graphql.variables, "{\n \"a\": 1\n}"); - assert!(draft.document.graphql.as_get); - // What does not read as GraphQL changes nothing of the request's. - let odd = sent( - "https://api.exemple.fr/graphql", - Vec::new(), - SentBody::None, + let graphql = onto( + &entry(RequestKind::Graphql, posted), + ¤t(RequestKind::Graphql, mine.clone()), &[], ); - assert_eq!( - onto(&odd, ¤t, &[]).document.graphql, - current.document.graphql - ); - // A file was not kept: the request's own body stays. - let mut uploading = held(RequestKind::Http, RequestDocument::default()); - uploading.document.body = RequestBody::Binary { - path: "C:/tmp/a.bin".to_string(), - }; - let upload = sent( - "https://api.exemple.fr/upload", - Vec::new(), - SentBody::Bytes { size: 12 }, - &[], + assert_eq!( + http.document.body, + RequestBody::Text { + text: "new".to_string() + } ); assert_eq!( - onto(&upload, &uploading, &[]).document.body, - uploading.document.body + (graphql.method, graphql.document.graphql.query.as_str()), + (HttpMethod::Get, "{ me }") ); + assert_eq!(graphql.document.url, "https://shop.test/graphql?x=1"); + assert_eq!(graphql.document.body, mine.body); } + /// Newest first as read, a group a local day: a send at 23:30 in UTC is the next day two + /// hours east — −120 as the interface counts it. #[test] - fn entries_are_grouped_by_the_local_day() { + fn the_history_is_grouped_by_local_day() { let item = |id: &str, at: &str| HistoryItem { id: id.to_string(), - sent_at: at.parse().unwrap(), - method: HttpMethod::Get, - status: Some(200), - request_id: None, - summary: HistorySummary { - kind: RequestKind::Http, - name: id.to_string(), - url: String::new(), - millis: None, - size: None, - failure: None, - failure_params: BTreeMap::new(), - method: HttpMethod::Get, - status: None, - environment: None, - }, - url_head: String::new(), - url_tail: String::new(), + sent_at: crate::db::iso8601::parse(at).unwrap(), + ..entry( + RequestKind::Http, + exchange("https://shop.test/", Vec::new(), SentBody::None), + ) + .item }; - let days = by_day( - vec![ - item("c", "2026-10-07T00:30:00Z"), - item("b", "2026-10-06T23:30:00Z"), - item("a", "2026-10-06T10:00:00Z"), - ], - -120, - ); + let items = vec![ + item("late", "2026-07-25T23:30:00.000Z"), + item("evening", "2026-07-25T20:00:00.000Z"), + item("before", "2026-07-24T09:00:00.000Z"), + ]; - assert_eq!( + let utc = by_day(items.clone(), 0); + let east = by_day(items, -120); + + let grouped = |days: &[HistoryDay]| -> Vec<(String, Vec)> { days.iter() - .map(|day| (day.day.as_str(), day.items.len())) - .collect::>(), - [("2026-10-07", 2), ("2026-10-06", 1)] + .map(|day| { + ( + day.day.clone(), + day.items.iter().map(|item| item.id.clone()).collect(), + ) + }) + .collect() + }; + assert_eq!( + grouped(&utc), + [ + ( + "2026-07-25".to_string(), + vec!["late".to_string(), "evening".to_string()] + ), + ("2026-07-24".to_string(), vec!["before".to_string()]) + ] + ); + assert_eq!( + grouped(&east)[0], + ("2026-07-26".to_string(), vec!["late".to_string()]) ); } } diff --git a/crates/engine/src/http/history/store.rs b/crates/engine/src/http/history/store.rs index b2301e9ee..e6e07f33d 100644 --- a/crates/engine/src/http/history/store.rs +++ b/crates/engine/src/http/history/store.rs @@ -190,19 +190,22 @@ pub fn clear(connection: &mut Library) -> Result { #[cfg(test)] mod tests { use super::*; - use crate::http::history::{HistoryRecord, HistorySummary}; - use crate::http::model::HttpMethod; + use crate::http::model::{HttpMethod, HttpRequestDraft, RequestKind}; use crate::http::send::{Exchange, SentBody}; - fn summary() -> HistorySummary { + fn now() -> DateTime { + iso8601::parse("2026-07-25T09:00:00.000Z").unwrap() + } + + fn summary(name: &str) -> HistorySummary { HistorySummary { - kind: crate::http::model::RequestKind::Http, - name: "Ping".to_string(), - url: "https://api.exemple.fr".to_string(), - millis: Some(1), - size: Some(0), + name: name.to_string(), + url: "https://api.shop.test/orders/42".to_string(), + millis: Some(12), + size: Some(34), failure: None, failure_params: std::collections::BTreeMap::new(), + kind: RequestKind::Http, method: HttpMethod::Delete, status: Some(401), environment: None, @@ -212,8 +215,8 @@ mod tests { fn record() -> HistoryRecord { HistoryRecord { exchange: Exchange { - method: HttpMethod::Get, - url: "https://api.exemple.fr".to_string(), + method: HttpMethod::Delete, + url: "https://api.shop.test/orders/42".to_string(), headers: Vec::new(), body: SentBody::None, }, @@ -221,87 +224,254 @@ mod tests { } } + fn write( + library: &mut Library, + name: &str, + request_id: Option<&str>, + at: DateTime, + ) -> String { + super::record(library, request_id, &summary(name), &record(), at).unwrap() + } + + fn names(library: &mut Library) -> Vec { + list(library) + .unwrap() + .into_iter() + .map(|item| item.summary.name) + .collect() + } + + fn a_request(library: &mut Library) -> String { + let collection = crate::http::store::create_collection(library, "Shop", now()).unwrap(); + let draft = HttpRequestDraft { + collection_id: collection.id, + folder_id: None, + name: "Orders".to_string(), + kind: RequestKind::Http, + method: HttpMethod::Get, + document: crate::http::model::RequestDocument::default(), + }; + crate::http::store::create_request(library, &draft, "Orders", now()) + .unwrap() + .id + } + + /// Newest first; of one instant, the one written last; read back with what a list shows, + /// its URL in two parts. #[test] - fn what_is_past_the_retention_or_the_count_goes_as_the_next_is_written() { + fn a_send_is_listed_newest_first_as_it_was_recorded() { let mut library = crate::db::open_in_memory().unwrap(); - let now: DateTime = "2026-10-07T12:00:00Z".parse().unwrap(); - let long_ago = now - TimeDelta::days(RETENTION_DAYS + 1); - record_at(&mut library, long_ago); - assert_eq!(count(&mut library).unwrap(), 1); + write(&mut library, "first", None, now()); + write(&mut library, "second", None, now()); + write(&mut library, "earlier", None, now() - TimeDelta::hours(1)); + + let items = list(&mut library).unwrap(); + + let shown: Vec<&str> = items + .iter() + .map(|item| item.summary.name.as_str()) + .collect(); + assert_eq!(shown, ["second", "first", "earlier"]); + let item = &items[0]; + assert_eq!( + (item.sent_at, item.method, item.status), + (now(), HttpMethod::Delete, Some(401)) + ); + assert_eq!( + (item.url_head.as_str(), item.url_tail.as_str()), + ("api.shop.test", "/orders/42") + ); + } - for second in 0..=KEPT_AT_MOST { - record_at(&mut library, now + TimeDelta::seconds(second)); - } + /// A request deleted since it was sent is history without its link. + #[test] + fn a_send_keeps_its_request_only_while_it_exists() { + let mut library = crate::db::open_in_memory().unwrap(); + let request = a_request(&mut library); + write(&mut library, "linked", Some(&request), now()); + write(&mut library, "gone", Some("deleted-since"), now()); - assert_eq!(i64::from(count(&mut library).unwrap()), KEPT_AT_MOST); - let newest = list(&mut library).unwrap(); - assert_eq!(newest[0].sent_at, now + TimeDelta::seconds(KEPT_AT_MOST)); - assert_eq!( - purge_expired(&mut library, now + TimeDelta::days(RETENTION_DAYS + 1)).unwrap(), - usize::try_from(KEPT_AT_MOST).unwrap() + let links: Vec> = list(&mut library) + .unwrap() + .into_iter() + .map(|item| item.request_id) + .collect(); + + assert_eq!(links, [None, Some(request)]); + } + + /// Kept thirty days from each write: what is older goes as the next one is written. + #[test] + fn a_write_lets_go_of_what_is_past_the_retention() { + let mut library = crate::db::open_in_memory().unwrap(); + write( + &mut library, + "a month ago", + None, + now() - TimeDelta::days(RETENTION_DAYS) - TimeDelta::seconds(1), + ); + write( + &mut library, + "at the edge", + None, + now() - TimeDelta::days(RETENTION_DAYS), ); + + write(&mut library, "today", None, now()); + + assert_eq!(names(&mut library), ["today", "at the edge"]); } - /// « Vider l'historique » was the only way out for the one send made with the wrong token. + /// Five hundred entries at most: past them, the oldest goes as the next one is written. #[test] - fn one_entry_is_deleted_and_put_back_where_it_was() { + fn a_write_lets_go_of_what_is_past_the_count() { let mut library = crate::db::open_in_memory().unwrap(); - let now: DateTime = "2026-10-07T12:00:00Z".parse().unwrap(); - for second in 0..3 { - record_at(&mut library, now + TimeDelta::seconds(second)); + write(&mut library, "oldest", None, now() - TimeDelta::days(1)); + + for _ in 0..KEPT_AT_MOST { + write(&mut library, "recent", None, now()); } - let before = list(&mut library).unwrap(); - let middle = before[1].id.clone(); - let removed = delete(&mut library, &middle).unwrap(); - assert_eq!(removed.item, before[1]); - assert_eq!( - list(&mut library) - .unwrap() - .iter() - .map(|item| item.id.as_str()) - .collect::>(), - [before[0].id.as_str(), before[2].id.as_str()] + assert_eq!(i64::from(count(&mut library).unwrap()), KEPT_AT_MOST); + assert!(!names(&mut library).contains(&"oldest".to_string())); + } + + /// Retention holds even when nothing is written: at launch, and never fatal. + #[test] + fn the_retention_is_swept_at_launch_without_a_write() { + let mut library = crate::db::open_in_memory().unwrap(); + write( + &mut library, + "old", + None, + Utc::now() - TimeDelta::days(RETENTION_DAYS + 1), ); - assert!(matches!( - delete(&mut library, &middle), - Err(StorageError::HttpItemNotFound(_)) - )); + write(&mut library, "kept", None, Utc::now()); + let db: crate::db::Db = std::sync::Mutex::new(Some(library)); + + crate::http::history::sweep_at_startup(&db); + crate::http::history::sweep_at_startup(&std::sync::Mutex::new(None)); + + assert_eq!(names(db.lock().unwrap().as_mut().unwrap()), ["kept"]); + } + + /// Deleted, an entry is answered whole; put back, it takes its place again under its id and + /// at its instant, once. + #[test] + fn an_entry_deleted_comes_back_where_it_was() { + let mut library = crate::db::open_in_memory().unwrap(); + write(&mut library, "older", None, now() - TimeDelta::hours(1)); + let id = write(&mut library, "middle", None, now()); + write(&mut library, "newer", None, now() + TimeDelta::hours(1)); + let removed = delete(&mut library, &id).unwrap(); + assert_eq!(names(&mut library), ["newer", "older"]); restore(&mut library, &removed).unwrap(); - // Put back twice is put back once. restore(&mut library, &removed).unwrap(); - assert_eq!(list(&mut library).unwrap(), before); - assert_eq!(entry(&mut library, &middle).unwrap(), removed); + + assert_eq!(names(&mut library), ["newer", "middle", "older"]); + assert_eq!(entry(&mut library, &id).unwrap(), removed); + assert_eq!(removed.record, record()); } + /// Put back after its request went, an entry comes back without the link. #[test] - fn a_list_reads_each_url_in_its_two_parts() { + fn an_entry_put_back_after_its_request_went_has_no_link() { let mut library = crate::db::open_in_memory().unwrap(); - record_at(&mut library, "2026-10-07T12:00:00Z".parse().unwrap()); + let request = a_request(&mut library); + let id = write(&mut library, "linked", Some(&request), now()); + let removed = delete(&mut library, &id).unwrap(); + let gone = crate::http::model::HttpItem { + kind: crate::http::model::HttpItemKind::Request, + id: request, + }; + crate::http::store::delete(&mut library, &gone).unwrap(); + + restore(&mut library, &removed).unwrap(); - let item = &list(&mut library).unwrap()[0]; - let (head, tail) = url_parts(&item.summary.url); - assert_eq!((&item.url_head, &item.url_tail), (&head, &tail)); - assert!(!item.url_head.is_empty()); + assert_eq!(entry(&mut library, &id).unwrap().item.request_id, None); } - /// Both were columns of their own, readable beside the instant of the send. #[test] - fn the_method_and_the_status_of_a_send_are_read_from_its_sealed_summary() { + fn an_entry_not_there_is_named_and_the_history_clears_whole() { let mut library = crate::db::open_in_memory().unwrap(); - record_at(&mut library, "2026-10-07T12:00:00Z".parse().unwrap()); + write(&mut library, "a", None, now()); + write(&mut library, "b", None, now()); - let item = list(&mut library).unwrap().remove(0); - assert_eq!((item.method, item.status), (HttpMethod::Delete, Some(401))); + assert!( + matches!(entry(&mut library, "missing"), Err(StorageError::HttpItemNotFound(id)) if id == "missing") + ); + assert!(matches!( + delete(&mut library, "missing"), + Err(StorageError::HttpItemNotFound(_)) + )); + assert_eq!(clear(&mut library).unwrap(), 2); + assert_eq!(count(&mut library).unwrap(), 0); + } - let removed = delete(&mut library, &item.id).unwrap(); - restore(&mut library, &removed).unwrap(); - let back = entry(&mut library, &item.id).unwrap().item; - assert_eq!((back.method, back.status), (HttpMethod::Delete, Some(401))); + /// ⚠️ In the clear, a reader of the raw file would read « a DELETE answered 401 at 14:02 »: + /// the method, the status, the URL and the name are sealed with the rest. + #[test] + fn a_send_is_sealed_but_for_its_instant() { + let mut library = crate::db::open_in_memory().unwrap(); + write(&mut library, "Delete the order", None, now()); + + let (summary, sealed): (String, String) = http_history::table + .select((http_history::summary, http_history::record)) + .first(library.db()) + .unwrap(); + + for clear in ["DELETE", "Delete", "401", "api.shop.test", "orders"] { + assert!( + !summary.contains(clear) && !sealed.contains(clear), + "{clear} in the clear" + ); + } } - fn record_at(library: &mut Library, at: DateTime) { - super::record(library, Some("gone"), &summary(), &record(), at).unwrap(); + /// What does not read is named by its field rather than skipped. + #[test] + fn an_entry_that_does_not_read_is_named_by_its_field() { + let mut library = crate::db::open_in_memory().unwrap(); + let id = write(&mut library, "a", None, now()); + let garbage = library.vault().seal("not json").unwrap(); + + diesel::update(http_history::table.find(&id)) + .set(http_history::record.eq(&garbage)) + .execute(library.db()) + .unwrap(); + assert!(matches!( + entry(&mut library, &id), + Err(StorageError::CorruptRow { + field: "record", + .. + }) + )); + diesel::update(http_history::table.find(&id)) + .set(http_history::summary.eq(&garbage)) + .execute(library.db()) + .unwrap(); + assert!(matches!( + list(&mut library), + Err(StorageError::CorruptRow { + field: "summary", + .. + }) + )); + let readable = seal_json(library.vault(), &summary("a")).unwrap(); + diesel::update(http_history::table.find(&id)) + .set(( + http_history::summary.eq(readable), + http_history::sent_at.eq("not a date"), + )) + .execute(library.db()) + .unwrap(); + assert!(matches!( + list(&mut library), + Err(StorageError::CorruptRow { + field: "sentAt", + .. + }) + )); } } From aa34aa03bce5c5e29ca97aa5f492b8a25a6afcb0 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:21:40 +0100 Subject: [PATCH 43/95] Request scripts: a form's file part is sent as a file (#1767) Co-authored-by: Claude Opus 5.5 --- crates/engine/src/http/scripts/engine.rs | 26 ++++++++++++++++++++++- crates/engine/src/http/scripts/prelude.js | 1 + 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/http/scripts/engine.rs b/crates/engine/src/http/scripts/engine.rs index 12df83d97..ac3df5fd8 100644 --- a/crates/engine/src/http/scripts/engine.rs +++ b/crates/engine/src/http/scripts/engine.rs @@ -307,7 +307,7 @@ impl Engine { mod tests { use super::*; use crate::http::scripts::model::{ - LayerScope, Phase, Script, ScriptKind, ScriptLayer, ScriptLevel, ScriptRequest, + LayerScope, Phase, Script, ScriptBody, ScriptKind, ScriptLayer, ScriptLevel, ScriptRequest, ScriptResponse, ScriptRow, WriteScope, }; @@ -460,6 +460,30 @@ mod tests { }); } + /// Read as a text, its path left in place of the file (#1765). + #[test] + fn a_form_s_file_part_stays_a_file_through_a_script() { + hosted(|| { + let mut job = before("pm.request.body.formdata.add({ key: 'note', value: 'x' });"); + job.request.body = ScriptBody { + mode: "formdata".to_string(), + formdata: vec![ScriptRow { + key: "scan".to_string(), + value: "/tmp/scan.png".to_string(), + part: Some("file".to_string()), + ..ScriptRow::default() + }], + ..ScriptBody::default() + }; + let parts = engine().0.run(&job, SECOND).request.unwrap().body.formdata; + let parts: Vec<(&str, Option<&str>)> = parts + .iter() + .map(|part| (part.key.as_str(), part.part.as_deref())) + .collect(); + assert_eq!(parts, [("scan", Some("file")), ("note", Some("text"))]); + }); + } + #[test] fn env_writes_the_active_environment_and_with_none_the_globals() { hosted(|| { diff --git a/crates/engine/src/http/scripts/prelude.js b/crates/engine/src/http/scripts/prelude.js index a89702e8f..22c36359c 100644 --- a/crates/engine/src/http/scripts/prelude.js +++ b/crates/engine/src/http/scripts/prelude.js @@ -366,6 +366,7 @@ key: String(item.key ?? item.name ?? ''), value: stored(item.value), disabled: Boolean(item.disabled), + ...(item.type === undefined ? {} : { type: String(item.type) }), }; } From ceff40197e8917df126514a72b0546b3a7eded23 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 21:06:48 +0100 Subject: [PATCH 44/95] Find and replace: $1 is the group whatever follows it (#1778) Co-authored-by: Claude Opus 5.5 --- crates/text/src/search.rs | 63 ++++++++++++++++++++++++++++++++++----- 1 file changed, 56 insertions(+), 7 deletions(-) diff --git a/crates/text/src/search.rs b/crates/text/src/search.rs index dc5036880..37f9a139d 100644 --- a/crates/text/src/search.rs +++ b/crates/text/src/search.rs @@ -4,7 +4,7 @@ use std::ops::Range; -use regex::{Regex, RegexBuilder}; +use regex::{Captures, Regex, RegexBuilder}; /// Past this many, the count stops: typing in the field stays smooth on a 2 MB snippet. pub const COUNT_CAP: usize = 1000; @@ -50,8 +50,8 @@ impl Query { self.search.is_empty() || self.matcher().is_some() } - /// What replaces `found`: `$&` and `$1` name the match and its groups in a regular - /// expression, as they did in the reference; a text replaces as it is written. + /// What replaces `found`: in a regular expression, `$&` is the match, `$1` its first group + /// whatever follows it, `$$` a dollar, as in the reference; a text replaces as it is written. pub fn replacement(&self, found: &str) -> String { if !self.regexp { return self.replace.clone(); @@ -62,13 +62,40 @@ impl Query { let Some(captures) = matcher.captures(found) else { return self.replace.clone(); }; - let template = self.replace.replace("$&", "${0}"); - let mut out = String::new(); - captures.expand(&template, &mut out); - out + expanded(&self.replace, &captures) } } +/// ⚠️ Not the crate's own expansion, which reads `$1px` as a group named `1px`: nothing. +fn expanded(template: &str, captures: &Captures<'_>) -> String { + let mut out = String::new(); + let mut rest = template; + while let Some(at) = rest.find('$') { + out.push_str(&rest[..at]); + let after = &rest[at + 1..]; + let digits = after.len() - after.trim_start_matches(|c: char| c.is_ascii_digit()).len(); + // The longest number that is a group: `$12` with two groups is the first, then `2`. + let group = (1..=digits).rev().find_map(|length| { + let number: usize = after[..length].parse().ok()?; + (1..captures.len()) + .contains(&number) + .then_some((number, length)) + }); + let taken = if let Some((number, length)) = group { + out.push_str(captures.get(number).map_or("", |found| found.as_str())); + length + } else if after.starts_with('&') { + out.push_str(&captures[0]); + 1 + } else { + out.push('$'); + usize::from(after.starts_with('$')) + }; + rest = &after[taken..]; + } + out + rest +} + /// Every match of `query` in `text`, up to `cap`. pub fn find(text: &str, query: &Query, cap: usize) -> Vec> { let Some(matcher) = query.matcher() else { @@ -170,6 +197,28 @@ mod tests { ..query(r"(\w+):(\w+)") }; assert_eq!(swap.replacement("port:5432"), "5432=port (port:5432)"); + for (template, replaced) in [ + ("$1px", "portpx"), + ("$1_$2", "port_5432"), + ("$12", "port2"), + ("$01", "port"), + ("$3 $0", "$3 $0"), + ("$$1 $total $", "$1 $total $"), + ("{$&}", "{port:5432}"), + ("é$2é", "é5432é"), + ] { + let query = Query { + replace: template.into(), + ..swap.clone() + }; + assert_eq!(query.replacement("port:5432"), replaced, "{template}"); + } + let optional = Query { + regexp: true, + replace: "[$1]".into(), + ..query(r"a(b)?") + }; + assert_eq!(optional.replacement("a"), "[]"); let plain = Query { replace: "$1".into(), ..query("a") From 4a249153647d0e25f70b5c179e561a660f87b11b Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Wed, 2 Dec 2026 21:10:54 +0100 Subject: [PATCH 45/95] HTTP sending: unit tests rewritten for what leaves and comes back (#1771) * Rewrite the tests of sending: what is composed, what leaves, what comes back and every way it fails Co-Authored-By: Claude Opus 5.5 * A cookie carried is not named like the cookie set Co-Authored-By: Claude Opus 5.5 * An unnamed API key or part, a code's multipart type, an operation not chosen, a key of any name and a send that replaced another, each held Co-Authored-By: Claude Opus 5.5 * A 308, an XML of no UTF-8 and an environment gone beside another, each held Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/http/send.rs | 1451 ++++++++------- crates/engine/tests/commands/http_send.rs | 2053 +++++++++++---------- 2 files changed, 1910 insertions(+), 1594 deletions(-) diff --git a/crates/engine/src/http/send.rs b/crates/engine/src/http/send.rs index d1a7fc650..2bc864d0f 100644 --- a/crates/engine/src/http/send.rs +++ b/crates/engine/src/http/send.rs @@ -1360,23 +1360,9 @@ impl Sending { #[cfg(test)] mod tests { use super::*; - use crate::http::graphql::GraphqlDocument; - - #[test] - fn a_send_that_fell_is_not_told_as_cancelled() { - let runtime = tokio::runtime::Runtime::new().unwrap(); - let (fell, aborted) = runtime.block_on(async { - let fell = tokio::spawn(async { panic!("a send fell") }).await; - let waiting = tokio::spawn(std::future::pending::<()>()); - waiting.abort(); - (fell.unwrap_err(), waiting.await.unwrap_err()) - }); - - assert!(matches!(ended(&fell), SendError::Fell)); - assert!(matches!(ended(&aborted), SendError::Cancelled)); - } - use crate::http::model::{FormPart, HttpItemKind}; - use crate::http::settings::{HttpOrigin, InheritedHeader}; + use crate::http::model::{ContainerSettings, FormPart, HttpItemKind}; + use crate::http::settings::inherit; + use crate::http::transport::TransportSettings; fn row(key: &str, value: &str) -> KeyValue { KeyValue { @@ -1386,6 +1372,13 @@ mod tests { } } + fn off(key: &str) -> KeyValue { + KeyValue { + enabled: false, + ..row(key, "x") + } + } + fn document(url: &str) -> RequestDocument { RequestDocument { url: url.to_string(), @@ -1393,39 +1386,30 @@ mod tests { } } - fn nothing() -> Inherited { - Inherited { - auth: RequestAuth::None, - auth_from: None, - headers: Vec::new(), - transport: crate::http::transport::Transport::default(), - limits: Limits::default(), - user_agent_off: false, - variables: Vec::new(), - scripts: Vec::new(), - } - } - - fn from(kind: HttpItemKind, name: &str) -> HttpOrigin { + fn origin(name: &str) -> HttpOrigin { HttpOrigin { - kind, + kind: HttpItemKind::Collection, id: name.to_lowercase(), name: name.to_string(), } } - fn off(key: &str) -> KeyValue { - KeyValue { - enabled: false, - ..row(key, "") - } + fn above(settings: ContainerSettings) -> Inherited { + inherit(&[(origin("Shop"), settings)]) } - fn get(document: &RequestDocument, inherited: &Inherited) -> Outgoing { - compose(RequestKind::Http, HttpMethod::Get, document, inherited).unwrap() + fn headers_above(rows: Vec) -> Inherited { + above(ContainerSettings { + headers: rows, + ..ContainerSettings::default() + }) } - fn header<'a>(outgoing: &'a Outgoing, name: &str) -> Option<&'a str> { + fn post(document: &RequestDocument, inherited: &Inherited) -> Result { + compose(RequestKind::Http, HttpMethod::Post, document, inherited) + } + + fn value<'a>(outgoing: &'a Outgoing, name: &str) -> Option<&'a str> { outgoing .headers .iter() @@ -1433,780 +1417,933 @@ mod tests { .map(|(_, value)| value.as_str()) } + /// Without a scheme, sent over HTTP as a browser would; another scheme, or no host, refused + /// by a reason that never repeats the URL — a key or a password may sit in it. #[test] - fn a_url_without_a_scheme_is_sent_over_http_and_any_other_scheme_is_refused() { - let outgoing = compose( - RequestKind::Http, - HttpMethod::Get, - &document("api.example.com/users?page=1"), - ¬hing(), - ) - .unwrap(); - assert_eq!(outgoing.url.as_str(), "http://api.example.com/users?page=1"); - - for refused in ["ftp://example.com", "http://", " "] { - assert!(matches!( - compose( - RequestKind::Http, - HttpMethod::Get, - &document(refused), - ¬hing() + fn a_url_is_sent_over_http_unless_it_says_https_and_anything_else_is_refused() { + let bare = post(&document(" api.shop.test/a?x=1 "), &inherit(&[])).unwrap(); + let secure = post(&document("https://api.shop.test"), &inherit(&[])).unwrap(); + + assert_eq!(bare.url.as_str(), "http://api.shop.test/a?x=1"); + assert_eq!(secure.url.scheme(), "https"); + for url in [ + "ftp://user:s3cret@shop.test/", + "file:///etc/hosts", + "https://", + "http://:8080/", + "not a url with spaces://", + ] { + match post(&document(url), &inherit(&[])) { + Err(SendError::InvalidUrl(reason)) => assert!( + !reason.contains("s3cret") && !reason.contains("hosts"), + "{url}: {reason}" ), - Err(SendError::InvalidUrl(_)) - )); + other => panic!("{url}: {other:?}"), + } } } + /// The first `{{name}}` no level set, in reading order: the request cannot leave with it. #[test] - fn a_variable_left_anywhere_stops_the_request_by_its_name() { - assert_eq!( - compose( - RequestKind::Http, - HttpMethod::Get, - &document("{{baseUrl}}/users"), - ¬hing() - ), - Err(SendError::Variable("baseUrl".to_string())) - ); - - let mut bearer = nothing(); - bearer.auth = RequestAuth::Bearer { - token: "{{accessToken}}".to_string(), - }; - assert_eq!( - compose( - RequestKind::Http, - HttpMethod::Get, - &document("https://example.com"), - &bearer - ), - Err(SendError::Variable("accessToken".to_string())) + fn a_name_left_anywhere_stops_the_request_by_the_first_one() { + let mut held = document("https://shop.test/{{path}}"); + held.headers = vec![row("X-Token", "{{token}}")]; + + let in_url = post(&held, &inherit(&[])); + held.url = "https://shop.test/".to_string(); + let in_header = post(&held, &inherit(&[])); + let above = post( + &document("https://shop.test/"), + &headers_above(vec![row("X-Tenant", "{{tenant}}")]), ); - // Angular's `{{ user.name }}` is text, not a variable. - let mut templated = document("https://example.com"); - templated.body = RequestBody::Text { - text: "{{ user.name }}".to_string(), - }; - assert!(compose(RequestKind::Http, HttpMethod::Post, &templated, ¬hing()).is_ok()); + assert_eq!(in_url, Err(SendError::Variable("path".to_string()))); + assert_eq!(in_header, Err(SendError::Variable("token".to_string()))); + assert_eq!(above, Err(SendError::Variable("tenant".to_string()))); } + /// The inherited headers, its own over them by name whatever the case; a row switched off or + /// unnamed sends nothing. #[test] - fn its_own_headers_override_the_inherited_ones_by_name_and_a_disabled_one_is_not_sent() { - let mut inherited = nothing(); - inherited.headers = vec![InheritedHeader { - header: row("Accept", "text/plain"), - from: HttpOrigin { - kind: HttpItemKind::Collection, - id: "c".to_string(), - name: "API".to_string(), - }, - }]; - let mut own = document("https://example.com"); - own.headers = vec![ - row("accept", "application/json"), - KeyValue { - enabled: false, - ..row("X-Debug", "1") - }, + fn its_own_headers_go_over_the_inherited_ones_by_name() { + let mut held = document("https://shop.test/"); + held.headers = vec![ + row("x-tenant", "mine"), + off("X-Debug"), + row(" ", "unnamed"), + row(" X-Own ", "1"), ]; - let outgoing = compose(RequestKind::Http, HttpMethod::Get, &own, &inherited).unwrap(); - assert_eq!( - outgoing.headers, - vec![ - ("accept".to_string(), "application/json".to_string()), - ("User-Agent".to_string(), USER_AGENT.to_string()), - ] - ); + let sent = post( + &held, + &headers_above(vec![row("X-Tenant", "theirs"), row("X-Debug", "1")]), + ) + .unwrap(); + + assert_eq!(value(&sent, "X-Tenant"), Some("mine")); + assert_eq!(value(&sent, "X-Debug"), Some("1")); + assert_eq!(value(&sent, "X-Own"), Some("1")); + assert!(sent.headers.iter().all(|(key, _)| !key.trim().is_empty())); } - /// « Erreur réseau » for a socket, « Le nom d'hôte ne se résout pas » for a request: the - /// same failure, read by two functions. One reads a chain now, whoever built it. + /// Each auth, its own or inherited, becomes its header or a query pair — unless a row of its + /// own already writes it — and an API key's name is what the history masks. #[test] - fn a_cause_is_read_the_same_whatever_wraps_it() { - use std::io::{Error, ErrorKind}; - - #[derive(Debug)] - struct Wrapped(Box); - impl std::fmt::Display for Wrapped { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(formatter, "error sending request") - } - } - impl std::error::Error for Wrapped { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - Some(self.0.as_ref()) - } - } - let limit = Limit { - value: 5_000, - set_by: SetBy::Request, - }; - let read = |error: Error| { - let plain = cause_of(&error, Some(&limit)); - let kind = error.kind(); - let wrapped = Wrapped(Box::new(Error::new(kind, Wrapped(Box::new(error))))); - assert_eq!( - cause_of(&wrapped, Some(&limit)).map(|found| std::mem::discriminant(&found)), - plain.as_ref().map(std::mem::discriminant), - ); - plain + fn the_auth_becomes_a_header_or_a_query_pair_unless_a_row_writes_it() { + let with = |auth: RequestAuth| RequestDocument { + auth, + ..document("https://shop.test/a?x=1") }; + let basic = post( + &with(RequestAuth::Basic { + username: "ada".to_string(), + password: "pw".to_string(), + }), + &inherit(&[]), + ) + .unwrap(); + let bearer = post( + &with(RequestAuth::Bearer { + token: " t0k3n ".to_string(), + }), + &inherit(&[]), + ) + .unwrap(); + let header_key = post( + &with(RequestAuth::ApiKey { + name: " X-Api-Key ".to_string(), + value: "k".to_string(), + place: KeyPlace::Header, + }), + &inherit(&[]), + ) + .unwrap(); + let query_key = post( + &with(RequestAuth::ApiKey { + name: "api key".to_string(), + value: "k&1".to_string(), + place: KeyPlace::Query, + }), + &inherit(&[]), + ) + .unwrap(); + let unnamed_key = post( + &with(RequestAuth::ApiKey { + name: " ".to_string(), + value: "k".to_string(), + place: KeyPlace::Query, + }), + &inherit(&[]), + ) + .unwrap(); + let inherited = post( + &document("https://shop.test/"), + &above(ContainerSettings { + auth: RequestAuth::Bearer { + token: "above".to_string(), + }, + ..ContainerSettings::default() + }), + ) + .unwrap(); + let mut typed = with(RequestAuth::Bearer { + token: "t".to_string(), + }); + typed.headers = vec![row("authorization", "Custom x")]; + let typed = post(&typed, &inherit(&[])).unwrap(); - // The three wordings of a name that does not resolve. - for wording in [ - "dns error: failed to lookup address information", - "failed to lookup address information: Name or service not known", - "No such host is known. (os error 11001)", - ] { - assert!( - matches!(read(Error::other(wording)), Some(SendError::Unresolved(_))), - "{wording}" - ); - } - assert!(matches!( - read(Error::from(ErrorKind::ConnectionRefused)), - Some(SendError::Refused(_)) - )); + assert_eq!(value(&basic, "Authorization"), Some("Basic YWRhOnB3")); + assert_eq!(value(&bearer, "Authorization"), Some("Bearer t0k3n")); assert_eq!( - read(Error::from(ErrorKind::TimedOut)), - Some(SendError::Timeout(limit.clone())) + ( + value(&header_key, "X-Api-Key"), + header_key.secrets.as_slice() + ), + (Some("k"), ["x-api-key".to_string()].as_slice()) ); - assert!(matches!( - read(Error::other(rustls::Error::HandshakeNotComplete)), - Some(SendError::Tls(_)) - )); - assert!(matches!( - read(Error::other("invalid peer certificate: UnknownIssuer")), - Some(SendError::Tls(_)) - )); - // Nothing known: the caller says « network », with the last cause's own words. - assert_eq!(read(Error::other("connection reset by peer")), None); assert_eq!( - innermost(&Wrapped(Box::new(Error::other("connection reset by peer")))), - "connection reset by peer" + query_key.url.as_str(), + "https://shop.test/a?x=1&api+key=k%261" ); - // Once open, a socket has no delay of its own to name. - assert_eq!(cause_of(&Error::from(ErrorKind::TimedOut), None), None); + assert_eq!(query_key.secrets, ["api key"]); + assert_eq!( + (unnamed_key.url.as_str(), unnamed_key.secrets.len()), + ("https://shop.test/a?x=1", 0) + ); + assert_eq!(value(&inherited, "Authorization"), Some("Bearer above")); + assert_eq!(value(&typed, "Authorization"), Some("Custom x")); } - /// Windows says it in the system's language: « Hôte inconnu » matches no wording. - #[cfg(windows)] #[test] - fn a_name_that_does_not_resolve_is_read_by_its_code_on_windows() { - for code in [11001, 11002, 11004] { - let error = std::io::Error::from_raw_os_error(code); - assert!( - matches!(cause_of(&error, None), Some(SendError::Unresolved(_))), - "{code}" - ); - } + fn an_api_key_without_a_name_sends_nothing() { + let unnamed = RequestDocument { + auth: RequestAuth::ApiKey { + name: " ".to_string(), + value: "k".to_string(), + place: KeyPlace::Header, + }, + ..document("https://shop.test/") + }; + + let sent = post(&unnamed, &inherit(&[])).unwrap(); + + let names: Vec<&str> = sent.headers.iter().map(|(name, _)| name.as_str()).collect(); assert_eq!( - cause_of(&std::io::Error::from_raw_os_error(10054), None), - None + (names, sent.secrets.len()), + (vec!["User-Agent", "Accept"], 0) ); } - /// `api.github.com` answers 403 to a request that names no agent, and none was sent. + /// Its tool alone knows the boundary. #[test] - fn a_request_names_the_application_unless_a_row_says_otherwise_at_any_level() { - let plain = document("https://api.github.com/events"); - let outgoing = get(&plain, ¬hing()); - assert!(USER_AGENT.starts_with("DevNotes/")); + fn a_program_is_not_handed_a_multipart_form_s_type() { + let with = |body: RequestBody| RequestDocument { + body, + ..document("https://shop.test/") + }; + let written = + |body: RequestBody| written_for_code(RequestKind::Http, &with(body), &inherit(&[])); + + assert!(written(RequestBody::Multipart { parts: Vec::new() }).is_empty()); assert_eq!( - USER_AGENT.strip_prefix("DevNotes/"), - Some(env!("CARGO_PKG_VERSION")) + written(RequestBody::Json { + text: String::new() + }), + [("Content-Type".to_string(), "application/json".to_string())] ); - assert_eq!(header(&outgoing, "user-agent"), Some(USER_AGENT)); - assert_eq!(header(&outgoing, "accept"), Some("*/*")); - assert!( - outgoing - .headers - .iter() - .all(|(name, value)| is_default(name, value)) - ); - assert!(is_default("user-agent", "DevNotes/0.9.0")); - assert!(!is_default("User-Agent", "curl/8.5.0") && !is_default("Accept", "text/csv")); + } + + /// The application names itself and takes anything, unless a row says otherwise; a + /// `User-Agent` switched off, here or above, sends none. + #[test] + fn the_application_names_itself_unless_a_row_says_otherwise() { + let plain = post(&document("https://shop.test/"), &inherit(&[])).unwrap(); + let mut own = document("https://shop.test/"); + own.headers = vec![ + row("User-Agent", "curl/8"), + row("accept", "application/json"), + ]; + let own = post(&own, &inherit(&[])).unwrap(); + let mut silenced = document("https://shop.test/"); + silenced.headers = vec![off("user-agent")]; + let silenced = post(&silenced, &inherit(&[])).unwrap(); + let silenced_above = post( + &document("https://shop.test/"), + &headers_above(vec![off("User-Agent")]), + ) + .unwrap(); - let mut collection = nothing(); - collection.headers = vec![InheritedHeader { - header: row("user-agent", "Équipe/1"), - from: from(HttpItemKind::Collection, "API"), - }]; assert_eq!( - header(&get(&plain, &collection), "user-agent"), - Some("Équipe/1") + (value(&plain, "User-Agent"), value(&plain, "Accept")), + (Some(USER_AGENT), Some("*/*")) ); + assert_eq!( + (value(&own, "User-Agent"), value(&own, "Accept")), + (Some("curl/8"), Some("application/json")) + ); + assert_eq!(value(&silenced, "User-Agent"), None); + assert_eq!(value(&silenced_above, "User-Agent"), None); + assert!(is_default("user-agent", "DevNotes/0.1.0") && is_default("Accept", "*/*")); + assert!(!is_default("User-Agent", "curl/8") && !is_default("Accept", "text/html")); + } - let mut own = plain.clone(); - own.headers = vec![row(" User-Agent ", "curl/8.5.0"), row("Accept", "text/csv")]; - let outgoing = get(&own, &collection); - assert_eq!(header(&outgoing, "user-agent"), Some("curl/8.5.0")); - assert_eq!(header(&outgoing, "accept"), Some("text/csv")); - assert_eq!(outgoing.headers.len(), 2); + /// Off here, set above: the inherited one still leaves, as any other header would. + #[test] + fn a_user_agent_switched_off_never_removes_one_set_above() { + let mut silenced = document("https://shop.test/"); + silenced.headers = vec![off("user-agent")]; + + let sent = post(&silenced, &headers_above(vec![row("User-Agent", "team/1")])).unwrap(); + + assert_eq!(value(&sent, "User-Agent"), Some("team/1")); } - /// « Cette URL ne peut pas être envoyée », on a good URL, for a header its folder set. + /// Named, with who wrote it — the request or the level above — rather than blamed on the URL. #[test] fn a_header_that_cannot_be_built_stops_the_request_by_its_name_and_who_wrote_it() { - let auth = from(HttpItemKind::Folder, "Auth"); - let mut inherited = nothing(); - inherited.headers = vec![InheritedHeader { - header: row("X-Recette: 1", "rsgfdregr"), - from: auth.clone(), - }]; - let plain = document("https://api.exemple.fr"); + let mut own = document("https://shop.test/"); + own.headers = vec![row("X Bad", "1")]; + + let mine = post(&own, &inherit(&[])); + let theirs = post( + &document("https://shop.test/"), + &headers_above(vec![row("X-Id", "a\nb")]), + ); + assert_eq!( - compose(RequestKind::Http, HttpMethod::Get, &plain, &inherited), + mine, Err(SendError::Header { - name: "X-Recette: 1".to_string(), + name: "X Bad".to_string(), fault: HeaderFault::Name, - set_by: SetBy::Above(auth), + set_by: SetBy::Request }) ); - - let mut own = plain.clone(); - own.headers = vec![row("X-Trace", "a\nb")]; assert_eq!( - compose(RequestKind::Http, HttpMethod::Get, &own, ¬hing()), + theirs, Err(SendError::Header { - name: "X-Trace".to_string(), + name: "X-Id".to_string(), fault: HeaderFault::Value, - set_by: SetBy::Request, + set_by: SetBy::Above(origin("Shop")) }) ); - - // Its own row of the same name replaces the inherited one, fault and all. - own.headers = vec![row("x-recette: 1", "ok"), off("X Off")]; - assert!(matches!( - compose(RequestKind::Http, HttpMethod::Get, &own, &inherited), - Err(SendError::Header { - set_by: SetBy::Request, - .. - }) - )); - own.headers = vec![off("X Off")]; - assert!(compose(RequestKind::Http, HttpMethod::Get, &own, ¬hing()).is_ok()); - - // The key's own name, when the auth writes the header. - let mut keyed = plain; - keyed.auth = RequestAuth::ApiKey { - name: "X Key".to_string(), - value: "s3cret".to_string(), - place: KeyPlace::Header, - }; - assert!(matches!( - compose(RequestKind::Http, HttpMethod::Get, &keyed, ¬hing()), - Err(SendError::Header { - fault: HeaderFault::Name, - .. - }) - )); } - fn hop(method: reqwest::Method, url: &str, headers: &[(&str, &str)]) -> Hop { - Hop { - method, - url: Url::parse(url).unwrap(), - headers: headers - .iter() - .map(|(name, value)| ((*name).to_string(), (*value).to_string())) - .collect(), - body: OutgoingBody::Bytes(b"{}".to_vec()), - } - } + /// Its type unless one is typed; a form encoded from the fields switched on and named; a + /// text as typed. + #[test] + fn a_body_carries_its_type_unless_one_is_typed() { + let with = |body: RequestBody| RequestDocument { + body, + ..document("https://shop.test/") + }; + let json = post( + &with(RequestBody::Json { + text: "{\"a\":1}".to_string(), + }), + &inherit(&[]), + ) + .unwrap(); + let form = post( + &with(RequestBody::Form { + fields: vec![row(" a b ", "x&y"), off("c"), row("", "z")], + }), + &inherit(&[]), + ) + .unwrap(); + let mut typed = with(RequestBody::Text { + text: "t".to_string(), + }); + typed.headers = vec![row("content-type", "text/csv")]; + let typed = post(&typed, &inherit(&[])).unwrap(); + let none = post(&with(RequestBody::None), &inherit(&[])).unwrap(); - fn to(location: &str) -> Vec { - vec![row("location", location)] + assert_eq!( + (value(&json, "Content-Type"), &json.body), + ( + Some("application/json"), + &OutgoingBody::Bytes(b"{\"a\":1}".to_vec()) + ) + ); + assert_eq!( + (value(&form, "Content-Type"), &form.body), + ( + Some("application/x-www-form-urlencoded"), + &OutgoingBody::Bytes(b"a+b=x%26y".to_vec()) + ) + ); + assert_eq!(value(&typed, "Content-Type"), Some("text/csv")); + assert_eq!( + (value(&none, "Content-Type"), &none.body), + (None, &OutgoingBody::None) + ); } - /// What the client did when it followed the redirects itself, now that a hop is ours. + /// A file is read when it is sent: a part keeps its file's name, a missing one is named, one + /// past the limit refused before it is read; a multipart type is left to the client, which + /// alone knows its boundary. #[test] - fn a_redirect_is_followed_by_its_status_its_location_read_against_what_answered() { - let posted = hop( - reqwest::Method::POST, - "https://api.exemple.fr/v1/login?next=1#top", - &[("Content-Type", "application/json"), ("X-Trace", "1")], - ); + fn a_file_is_read_when_sent_and_one_missing_or_too_heavy_is_named() { + let scratch = tempfile::tempdir().unwrap(); + let file = scratch.path().join("scan.pdf"); + std::fs::write(&file, b"%PDF").unwrap(); + let heavy = scratch.path().join("heavy.bin"); + std::fs::File::create(&heavy) + .unwrap() + .set_len(SENT_FILE_MEGABYTES * 1024 * 1024 + 1) + .unwrap(); + let path = file.to_str().unwrap().to_string(); + let part = |key: &str, value: &str, file: bool, enabled: bool| FormPart { + enabled, + key: key.to_string(), + value: value.to_string(), + file, + ..FormPart::default() + }; + let with = |body: RequestBody| RequestDocument { + body, + ..document("https://shop.test/") + }; - for status in [301, 302, 303] { - let next = posted.after(status, &to("../me")).unwrap(); - assert_eq!(next.url.as_str(), "https://api.exemple.fr/me"); - assert_eq!(next.method, reqwest::Method::GET); - assert_eq!(next.body, OutgoingBody::None); - assert_eq!( - next.headers, - vec![ - ("X-Trace".to_string(), "1".to_string()), - ( - "Referer".to_string(), - "https://api.exemple.fr/v1/login?next=1".to_string() - ), - ] - ); - } - for status in [307, 308] { - let next = posted.after(status, &to("/v2/login")).unwrap(); - assert_eq!(next.method, reqwest::Method::POST); - assert_eq!(next.body, posted.body); - assert!(next.headers.iter().any(|(name, _)| name == "Content-Type")); - } - // A `HEAD` stays one; what is no redirect, or leads nowhere a request goes, is the answer. - let head = hop(reqwest::Method::HEAD, "https://exemple.fr/", &[]); + let multipart = post( + &with(RequestBody::Multipart { + parts: vec![ + part(" title ", "Facture", false, true), + part("scan", &path, true, true), + part("off", "x", false, false), + part(" ", "x", false, true), + ], + }), + &inherit(&[]), + ) + .unwrap(); + let binary = post( + &with(RequestBody::Binary { path: path.clone() }), + &inherit(&[]), + ) + .unwrap(); + let missing = scratch + .path() + .join("missing.bin") + .to_str() + .unwrap() + .to_string(); + + assert_eq!( + multipart.body, + OutgoingBody::Multipart(vec![ + ("title".to_string(), Part::Text("Facture".to_string())), + ( + "scan".to_string(), + Part::File { + name: "scan.pdf".to_string(), + bytes: b"%PDF".to_vec() + } + ) + ]) + ); + assert_eq!(value(&multipart, "Content-Type"), None); + assert_eq!(binary.body, OutgoingBody::Bytes(b"%PDF".to_vec())); assert_eq!( - head.after(302, &to("/a")).unwrap().method, - reqwest::Method::HEAD + post( + &with(RequestBody::Binary { + path: missing.clone() + }), + &inherit(&[]) + ), + Err(SendError::FileUnreadable(missing)) + ); + let heavy = heavy.to_str().unwrap().to_string(); + assert_eq!( + post( + &with(RequestBody::Binary { + path: heavy.clone() + }), + &inherit(&[]) + ), + Err(SendError::FileTooLarge(heavy)) ); - for status in [200, 300, 304, 305, 404] { - assert!(posted.after(status, &to("/a")).is_none(), "{status}"); - } - assert!(posted.after(302, &[]).is_none()); - assert!(posted.after(302, &to("ftp://exemple.fr/a")).is_none()); - assert!(posted.after(302, &to("http://")).is_none()); } + /// A JSON `POST` of the query, or its parts in the query of a `GET` with no body nor type, + /// whatever the method held; variables that are no object are refused. #[test] - fn another_host_or_port_gets_no_secret_and_a_plain_page_no_referer_from_a_secure_one() { - let secret = hop( - reqwest::Method::GET, - "https://ada:pw@api.exemple.fr/login", - &[ - ("authorization", "Bearer t"), - ("Cookie", "typed=1"), - ("Proxy-Authorization", "Basic x"), - ("Accept", "*/*"), - ("Referer", "https://ailleurs.fr/"), - ], + fn a_graphql_request_is_a_json_post_or_a_get_with_its_parts_in_the_query() { + let mut held = document("https://shop.test/graphql?v=2"); + held.graphql.query = "{ me }".to_string(); + held.graphql.variables = "{\"a\":1}".to_string(); + held.graphql.operation_name = Some("Me".to_string()); + + let posted = compose( + RequestKind::Graphql, + HttpMethod::Delete, + &held, + &inherit(&[]), + ) + .unwrap(); + held.graphql.as_get = true; + let got = compose( + RequestKind::Graphql, + HttpMethod::Delete, + &held, + &inherit(&[]), + ) + .unwrap(); + held.graphql.variables = "[1]".to_string(); + let refused = compose( + RequestKind::Graphql, + HttpMethod::Delete, + &held, + &inherit(&[]), ); - let names = |next: &Hop| -> Vec { - next.headers.iter().map(|(name, _)| name.clone()).collect() - }; - let same = secret.after(302, &to("/me")).unwrap(); assert_eq!( - names(&same), - [ - "authorization", - "Cookie", - "Proxy-Authorization", - "Accept", - "Referer" - ] + ( + posted.method, + value(&posted, "Content-Type"), + posted.graphql + ), + (HttpMethod::Post, Some("application/json"), true) ); - // Its credentials are not in what it says it comes from. assert_eq!( - same.headers.last().map(|(_, value)| value.as_str()), - Some("https://api.exemple.fr/login") + posted.body, + OutgoingBody::Bytes( + br#"{"query":"{ me }","variables":{"a":1},"operationName":"Me"}"#.to_vec() + ) ); - - for elsewhere in [ - "https://autre.exemple.fr/me", - "https://api.exemple.fr:8443/me", - ] { - assert_eq!( - names(&secret.after(302, &to(elsewhere)).unwrap()), - ["Accept", "Referer"], - "{elsewhere}" - ); - } assert_eq!( - names(&secret.after(302, &to("http://api.exemple.fr/me")).unwrap()), - ["Accept"] + (got.method, value(&got, "Content-Type"), &got.body), + (HttpMethod::Get, None, &OutgoingBody::None) ); + assert_eq!( + got.url.as_str(), + "https://shop.test/graphql?v=2&query=%7B+me+%7D&variables=%7B%22a%22%3A1%7D&operationName=Me" + ); + assert!(matches!(refused, Err(SendError::GraphqlVariables(_)))); } #[test] - fn a_hop_carries_the_jar_s_line_for_its_own_url_unless_a_cookie_is_typed() { - let jar = vec![JarCookie { - name: "session".to_string(), - value: "abc".to_string(), - domain: "api.exemple.fr".to_string(), - host_only: true, - path: "/".to_string(), - expires: None, - secure: false, - http_only: false, - same_site: None, - created: None, - }]; - let get = |url: &str, headers: &[(&str, &str)]| hop(reqwest::Method::GET, url, headers); + fn a_graphql_get_names_no_operation_when_none_is_chosen() { + let mut held = document("https://shop.test/graphql"); + held.graphql.as_get = true; + held.graphql.query = "{me}".to_string(); + held.graphql.operation_name = Some(String::new()); + + let sent = compose(RequestKind::Graphql, HttpMethod::Get, &held, &inherit(&[])).unwrap(); assert_eq!( - get("https://api.exemple.fr/me", &[]).cookie(Some(&jar)), - Some("session=abc".to_string()) - ); - assert_eq!(get("https://autre.fr/", &[]).cookie(Some(&jar)), None); - assert_eq!( - get("https://api.exemple.fr/me", &[("cookie", "typed=1")]).cookie(Some(&jar)), - None + sent.url.as_str(), + "https://shop.test/graphql?query=%7Bme%7D" ); - // No jar: the request neither sends nor keeps a cookie. - assert_eq!(get("https://api.exemple.fr/me", &[]).cookie(None), None); } + /// Its own transport over what it inherits, and who set the delay and the redirects a send + /// can fail on. #[test] - fn a_user_agent_row_switched_off_sends_none_and_never_removes_one_set_above() { - let mut own = document("https://example.com"); - own.headers = vec![off("user-agent")]; - assert_eq!(header(&get(&own, ¬hing()), "user-agent"), None); - - let silent = Inherited { - user_agent_off: true, - ..nothing() - }; - let plain = document("https://example.com"); - assert_eq!(header(&get(&plain, &silent), "user-agent"), None); - assert_eq!(header(&get(&plain, &silent), "accept"), Some("*/*")); - - // Off here, set above: the inherited one still leaves, as any other header would. - let mut collection = nothing(); - collection.headers = vec![InheritedHeader { - header: row("User-Agent", "Équipe/1"), - from: from(HttpItemKind::Collection, "API"), - }]; + fn a_request_knows_its_transport_and_who_set_its_limits() { + let inherited = above(ContainerSettings { + transport: TransportSettings { + timeout_ms: Some(5_000), + max_redirects: Some(3), + ..TransportSettings::default() + }, + ..ContainerSettings::default() + }); + let mut own = document("https://shop.test/"); + own.transport.timeout_ms = Some(1_000); + + let sent = post(&own, &inherited).unwrap(); + assert_eq!( - header(&get(&own, &collection), "user-agent"), - Some("Équipe/1") + sent.timeout(), + Limit { + value: 1_000, + set_by: SetBy::Request + } + ); + assert_eq!( + sent.redirects(), + Limit { + value: 3, + set_by: SetBy::Above(origin("Shop")) + } ); + assert_eq!( + (sent.jar.is_none(), sent.secret_values.is_empty()), + (true, true) + ); + } + + fn implied_names( + kind: RequestKind, + held: &RequestDocument, + inherited: &Inherited, + ) -> Vec<(String, String, ImpliedSource)> { + implied(kind, held, inherited) + .into_iter() + .map(|header| (header.name, header.value, header.source)) + .collect() } - /// The editor's list is read from what `compose` writes: the same headers, less its own rows. + /// What leaves without a row of its own, with who put it there — the body, a level above, + /// the application, the URL — never a row of the request's own or its auth. #[test] fn what_leaves_without_a_row_is_listed_with_who_put_it_there() { - let api = from(HttpItemKind::Collection, "API"); - let mut inherited = nothing(); - inherited.auth = RequestAuth::Bearer { - token: "t".to_string(), - }; - inherited.headers = vec![ - InheritedHeader { - header: row("X-Client", "web"), - from: api.clone(), - }, - InheritedHeader { - header: row("X-Trace", "1"), - from: api.clone(), - }, - ]; - let mut posted = document("https://api.exemple.fr:8443/users"); - posted.headers = vec![row("x-trace", "2")]; - posted.body = RequestBody::Json { + let mut held = document("https://shop.test:8443/a"); + held.body = RequestBody::Json { text: "{}".to_string(), }; + held.headers = vec![row("X-Own", "1")]; + held.auth = RequestAuth::Bearer { + token: "t".to_string(), + }; - let listed = implied(RequestKind::Http, &posted, &inherited); + let listed = implied( + RequestKind::Http, + &held, + &headers_above(vec![row("X-Tenant", "acme")]), + ); - let seen: Vec<(&str, &str, ImpliedSource)> = listed + let shown: Vec<(&str, ImpliedSource)> = listed .iter() - .map(|header| (header.name.as_str(), header.value.as_str(), header.source)) + .map(|header| (header.name.as_str(), header.source)) .collect(); assert_eq!( - seen, - vec![ - ("Content-Type", "application/json", ImpliedSource::Body), - ("X-Client", "web", ImpliedSource::Above), - ("User-Agent", USER_AGENT, ImpliedSource::Default), - ("Accept", "*/*", ImpliedSource::Default), - ("Host", "api.exemple.fr:8443", ImpliedSource::Url), + shown, + [ + ("Content-Type", ImpliedSource::Body), + ("X-Tenant", ImpliedSource::Above), + ("User-Agent", ImpliedSource::Default), + ("Accept", ImpliedSource::Default), + ("Host", ImpliedSource::Url) ] ); - assert_eq!(listed[1].from, Some(api)); - - // Each one written by the request leaves the list; so does the default once switched off. - posted.headers = vec![ - row("Content-Type", "application/vnd.api+json"), - row("Accept", "text/csv"), - row("Host", "autre.exemple.fr"), - off("User-Agent"), - ]; - let names: Vec = implied(RequestKind::Http, &posted, &inherited) - .into_iter() - .map(|header| header.name) - .collect(); - assert_eq!(names, vec!["X-Client", "X-Trace"]); + assert_eq!(listed[1].from, Some(origin("Shop"))); + assert_eq!(listed[4].value, "shop.test:8443"); } + /// A `Host` from the URL only when it reads — not yet typed, a `{{name}}` for host, a row of + /// its own — the port only when not its scheme's; a socket read on its own scheme, and + /// neither it nor a GraphQL `GET` has a type. #[test] - fn a_url_that_does_not_read_yet_has_no_host_and_a_socket_or_a_graphql_get_no_type() { - let names = |kind, document: &RequestDocument| -> Vec { - implied(kind, document, ¬hing()) + fn the_host_is_listed_only_from_a_url_that_reads() { + let host = |kind: RequestKind, held: &RequestDocument| { + implied_names(kind, held, &inherit(&[])) .into_iter() - .map(|header| header.name) - .collect() + .find(|(name, ..)| name == "Host") + .map(|(_, value, _)| value) }; + let mut typed = document("https://shop.test/"); + typed.headers = vec![row("host", "other.test")]; + let mut graphql_get = document("https://shop.test/"); + graphql_get.graphql.as_get = true; - for unread in [ - "{{baseUrl}}/users", - "https://{{host}}.exemple.fr", - "", - "ftp://x", - ] { - assert_eq!( - names(RequestKind::Http, &document(unread)), - vec!["User-Agent", "Accept"] - ); - } assert_eq!( - names(RequestKind::Http, &document("https://example.com")), - vec!["User-Agent", "Accept", "Host"] + host(RequestKind::Http, &document("https://shop.test:443/")), + Some("shop.test".to_string()) ); - - let mut socket = document("wss://echo.exemple.fr/live"); - socket.body = RequestBody::Json { - text: "{}".to_string(), - }; - let listed = implied(RequestKind::Websocket, &socket, ¬hing()); + assert_eq!(host(RequestKind::Http, &document("")), None); assert_eq!( - listed.last().map(|header| header.value.as_str()), - Some("echo.exemple.fr") + host(RequestKind::Http, &document("https://{{base}}/a")), + None ); - assert!(listed.iter().all(|header| header.name != "Content-Type")); - - let mut query = document("https://example.com/graphql"); - query.graphql.query = "{ viewer { login } }".to_string(); + assert_eq!(host(RequestKind::Http, &typed), None); assert_eq!( - names(RequestKind::Graphql, &query), - vec!["Content-Type", "User-Agent", "Accept", "Host"] + host(RequestKind::Websocket, &document("wss://live.test:9000/")), + Some("live.test:9000".to_string()) ); - query.graphql.as_get = true; - assert_eq!( - names(RequestKind::Graphql, &query), - vec!["User-Agent", "Accept", "Host"] + assert!( + !implied_names( + RequestKind::Websocket, + &document("wss://live.test/"), + &inherit(&[]) + ) + .iter() + .any(|(name, ..)| name == "Content-Type") + ); + assert!( + !implied_names(RequestKind::Graphql, &graphql_get, &inherit(&[])) + .iter() + .any(|(name, ..)| name == "Content-Type") ); } + /// The request as it left, a secret variable's value written as its name; a body as text + /// up to what is shown, as its size when it is no text, as its fields' names for a form. #[test] - fn the_auth_inherited_or_its_own_becomes_a_header_or_a_query_pair() { - let mut inherited = nothing(); - inherited.auth = RequestAuth::Basic { - username: "ada".to_string(), - password: "lovelace".to_string(), + fn the_exchange_shows_what_left_with_its_secrets_as_their_names() { + let mut outgoing = post(&document("https://shop.test/?t=t0k3n"), &inherit(&[])).unwrap(); + outgoing.headers = vec![("X-Token".to_string(), "t0k3n".to_string())]; + outgoing.secret_values = vec![("token".to_string(), "t0k3n".to_string())]; + outgoing.body = + OutgoingBody::Bytes(format!("{}{}", "t0k3n ", "a".repeat(SHOWN_LIMIT)).into_bytes()); + + let text = exchange(&outgoing); + outgoing.body = OutgoingBody::Bytes(vec![0xff, 0xfe, 0x00]); + let bytes = exchange(&outgoing); + outgoing.body = + OutgoingBody::Multipart(vec![("title".to_string(), Part::Text("x".to_string()))]); + let form = exchange(&outgoing); + + assert_eq!(text.url, "https://shop.test/?t={{token}}"); + assert_eq!(text.headers[0].value, "{{token}}"); + let SentBody::Text { text: shown } = &text.body else { + panic!("no text") }; - let outgoing = compose( - RequestKind::Http, - HttpMethod::Get, - &document("https://example.com"), - &inherited, - ) - .unwrap(); + assert!(shown.starts_with("{{token}} ") && shown.chars().count() < SHOWN_LIMIT + 10); + assert_eq!(bytes.body, SentBody::Bytes { size: 3 }); assert_eq!( - header(&outgoing, "authorization"), - Some("Basic YWRhOmxvdmVsYWNl") + form.body, + SentBody::Multipart { + fields: vec!["title".to_string()] + } ); + } - let mut keyed = document("https://example.com/?a=1"); - keyed.auth = RequestAuth::ApiKey { - name: "key".to_string(), - value: "s e".to_string(), - place: KeyPlace::Query, - }; - let outgoing = compose(RequestKind::Http, HttpMethod::Get, &keyed, &inherited).unwrap(); - assert_eq!(outgoing.url.as_str(), "https://example.com/?a=1&key=s+e"); - assert_eq!(header(&outgoing, "authorization"), None); + #[derive(Debug)] + struct Wrapped( + &'static str, + Option>, + ); - let mut typed = document("https://example.com"); - typed.auth = RequestAuth::Bearer { - token: "t".to_string(), - }; - typed.headers = vec![row("Authorization", "Token mine")]; - let outgoing = compose(RequestKind::Http, HttpMethod::Get, &typed, ¬hing()).unwrap(); - assert_eq!(header(&outgoing, "authorization"), Some("Token mine")); + impl std::fmt::Display for Wrapped { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(self.0) + } + } + + impl std::error::Error for Wrapped { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + self.1 + .as_deref() + .map(|inner| inner as &(dyn std::error::Error + 'static)) + } } + /// One reading of a chain, for a request and a socket alike: refused, timed out when a delay + /// was waited, a name that does not resolve or a certificate, whatever wraps it — an + /// `io::Error` holding its cause where `source` does not look; nothing known, nothing said. #[test] - fn the_body_carries_its_type_unless_one_is_typed_and_a_form_is_encoded() { - let mut json = document("https://example.com"); - json.body = RequestBody::Json { - text: "{\"a\":1}".to_string(), + fn a_failure_is_read_off_the_chain_of_its_causes() { + use std::io::{Error, ErrorKind}; + let limit = Limit { + value: 5_000, + set_by: SetBy::Request, + }; + let wrap = |inner: Box| { + Wrapped("error sending request", Some(inner)) + }; + let kind_of = |error: &(dyn std::error::Error + 'static), limit: Option<&Limit>| { + cause_of(error, limit).map(|found| std::mem::discriminant(&found)) }; - let outgoing = compose(RequestKind::Http, HttpMethod::Post, &json, ¬hing()).unwrap(); - assert_eq!(header(&outgoing, "content-type"), Some("application/json")); - assert_eq!(outgoing.body, OutgoingBody::Bytes(b"{\"a\":1}".to_vec())); + let refused = SendError::Refused(String::new()); + let timeout = SendError::Timeout(limit.clone()); + let unresolved = SendError::Unresolved(String::new()); + let tls = SendError::Tls(String::new()); - json.headers = vec![row("Content-Type", "application/vnd.api+json")]; - let outgoing = compose(RequestKind::Http, HttpMethod::Post, &json, ¬hing()).unwrap(); assert_eq!( - header(&outgoing, "content-type"), - Some("application/vnd.api+json") + kind_of( + &wrap(Box::new(Error::from(ErrorKind::ConnectionRefused))), + None + ), + Some(std::mem::discriminant(&refused)) ); - - let mut form = document("https://example.com"); - form.body = RequestBody::Form { - fields: vec![row("q", "a b&c"), row("lang", "fr")], - }; - let outgoing = compose(RequestKind::Http, HttpMethod::Post, &form, ¬hing()).unwrap(); assert_eq!( - outgoing.body, - OutgoingBody::Bytes(b"q=a+b%26c&lang=fr".to_vec()) + kind_of(&Error::from(ErrorKind::TimedOut), Some(&limit)), + Some(std::mem::discriminant(&timeout)) + ); + assert_eq!(kind_of(&Error::from(ErrorKind::TimedOut), None), None); + for wording in [ + "dns error: failed to lookup address", + "failed to lookup address information", + "No such host is known.", + ] { + assert_eq!( + kind_of(&wrap(Box::new(Wrapped(wording, None))), None), + Some(std::mem::discriminant(&unresolved)), + "{wording}" + ); + } + assert_eq!( + kind_of( + &Error::other(Wrapped("invalid peer certificate: UnknownIssuer", None)), + None + ), + Some(std::mem::discriminant(&tls)) + ); + assert_eq!( + kind_of( + &Error::other(rustls::Error::General("handshake".to_string())), + None + ), + Some(std::mem::discriminant(&tls)) + ); + assert_eq!(kind_of(&Wrapped("something else", None), None), None); + assert_eq!( + innermost(&wrap(Box::new(Wrapped("the root", None)))), + "the root" ); } - /// Its own value is the request's; one left unset is whoever set it above, or nobody. + /// Windows words its errors in the system's language: the code names the failure. + #[cfg(windows)] #[test] - fn a_request_knows_who_set_its_timeout_and_its_redirects() { - use crate::http::model::HttpItemKind; - use crate::http::settings::HttpOrigin; - - let folder = SetBy::Above(HttpOrigin { - kind: HttpItemKind::Folder, - id: "f".to_string(), - name: "Auth".to_string(), + fn a_name_that_does_not_resolve_is_read_by_its_code_on_windows() { + for code in [11001, 11002, 11003, 11004] { + let error = std::io::Error::from_raw_os_error(code); + assert!( + matches!(cause_of(&error, None), Some(SendError::Unresolved(_))), + "{code}" + ); + } + for code in [11000, 11005, 10054] { + let error = std::io::Error::from_raw_os_error(code); + assert_eq!(cause_of(&error, None), None, "{code}"); + } + } + + /// A panic is no cancel: the history is still written. Private: a send has no input that + /// makes it panic. + #[test] + fn a_send_that_fell_is_not_told_as_cancelled() { + let runtime = tokio::runtime::Runtime::new().unwrap(); + let (fell, aborted) = runtime.block_on(async { + let fell = tokio::spawn(async { panic!("a send fell") }).await; + let waiting = tokio::spawn(std::future::pending::<()>()); + waiting.abort(); + (fell.unwrap_err(), waiting.await.unwrap_err()) }); - let above = Inherited { - transport: Transport { - timeout_ms: 2_000, - ..Transport::default() - }, - limits: Limits { - timeout: folder.clone(), - redirects: SetBy::Default, - }, - ..nothing() - }; - let mut own = document("https://api.exemple.fr"); - own.transport.max_redirects = Some(1); - let outgoing = compose(RequestKind::Http, HttpMethod::Get, &own, &above).unwrap(); + assert_eq!(ended(&fell), SendError::Fell); + assert_eq!(ended(&aborted), SendError::Cancelled); + } - assert_eq!( - outgoing.timeout(), - Limit { - value: 2_000, - set_by: folder - } - ); - assert_eq!( - outgoing.redirects(), - Limit { - value: 1, - set_by: SetBy::Request - } - ); + fn hop(method: reqwest::Method, url: &str, headers: &[(&str, &str)]) -> Hop { + Hop { + method, + url: Url::parse(url).unwrap(), + headers: headers + .iter() + .map(|(name, value)| ((*name).to_string(), (*value).to_string())) + .collect(), + body: OutgoingBody::Bytes(b"{}".to_vec()), + } + } + + fn location(to: &str) -> Vec { + vec![row("Location", to)] } + fn names(hop: &Hop) -> Vec<&str> { + hop.headers.iter().map(|(name, _)| name.as_str()).collect() + } + + /// The client's own rules, kept now that a hop is ours: a 301, 302 or 303 becomes a `GET` + /// without its body, a 307 or 308 keeps both; a `Location` read against what answered; any + /// other status, or no `Location`, or one off HTTP, is no redirect. Private: reached only + /// over the network. #[test] - fn a_file_is_read_when_sent_and_one_missing_is_named() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("avatar.png"); - std::fs::write(&path, [1, 2, 3]).unwrap(); - let path = path.to_string_lossy().into_owned(); - - let mut multipart = document("https://example.com"); - multipart.body = RequestBody::Multipart { - parts: vec![ - FormPart { - key: "name".to_string(), - value: "Ada".to_string(), - ..FormPart::default() - }, - FormPart { - key: "avatar".to_string(), - value: path.clone(), - file: true, - ..FormPart::default() - }, - ], - }; - let outgoing = - compose(RequestKind::Http, HttpMethod::Post, &multipart, ¬hing()).unwrap(); - assert_eq!( - outgoing.body, - OutgoingBody::Multipart(vec![ - ("name".to_string(), Part::Text("Ada".to_string())), - ( - "avatar".to_string(), - Part::File { - name: "avatar.png".to_string(), - bytes: vec![1, 2, 3] - } - ), - ]) + fn a_redirect_is_followed_by_its_status_and_its_location() { + let first = hop( + reqwest::Method::POST, + "https://shop.test/a/b", + &[("Content-Type", "application/json"), ("X-Keep", "1")], ); - assert_eq!(header(&outgoing, "content-type"), None); - let mut binary = document("https://example.com"); - let missing = directory - .path() - .join("gone.bin") - .to_string_lossy() - .into_owned(); - binary.body = RequestBody::Binary { - path: missing.clone(), - }; + let moved = first.after(303, &location("../c?x=1")).unwrap(); + let kept = first.after(307, &location("https://shop.test/d")).unwrap(); + let head = hop(reqwest::Method::HEAD, "https://shop.test/", &[]) + .after(301, &location("/e")) + .unwrap(); + assert_eq!( - compose(RequestKind::Http, HttpMethod::Put, &binary, ¬hing()), - Err(SendError::FileUnreadable(missing)) + (moved.method.clone(), moved.url.as_str(), &moved.body), + ( + reqwest::Method::GET, + "https://shop.test/c?x=1", + &OutgoingBody::None + ) + ); + assert_eq!(names(&moved), ["X-Keep", "Referer"]); + assert_eq!( + (kept.method.clone(), &kept.body), + (reqwest::Method::POST, &OutgoingBody::Bytes(b"{}".to_vec())) ); + assert!(names(&kept).contains(&"Content-Type")); + assert_eq!(head.method, reqwest::Method::HEAD); + for status in [301, 302, 303, 307, 308] { + assert!(first.after(status, &location("/x")).is_some(), "{status}"); + } + for (status, headers) in [ + (200, location("/x")), + (304, location("/x")), + (302, Vec::new()), + (302, location("ftp://shop.test/x")), + ] { + assert!(first.after(status, &headers).is_none(), "{status}"); + } } + /// Another host or port gets neither an auth nor a typed cookie; the page it comes from is + /// said without its credentials or fragment, never from a secure page to a plain one. #[test] - fn a_file_past_the_limit_is_refused_before_it_is_read() { - let directory = tempfile::tempdir().unwrap(); - let path = directory.path().join("dump.bin"); - // Sparse: its size is said, nothing is written. - std::fs::File::create(&path) - .unwrap() - .set_len(SENT_FILE_MEGABYTES * 1024 * 1024 + 1) + fn another_host_gets_no_secret_and_a_plain_page_no_referer_from_a_secure_one() { + let first = hop( + reqwest::Method::GET, + "https://ada:pw@shop.test/a#top", + &[ + ("Authorization", "Bearer t"), + ("Cookie", "sid=1"), + ("Proxy-Authorization", "x"), + ("Referer", "old"), + ("X-Keep", "1"), + ], + ); + + let same = first.after(302, &location("/b")).unwrap(); + let other_host = first.after(302, &location("https://cdn.test/b")).unwrap(); + let other_port = first + .after(302, &location("https://shop.test:8443/b")) .unwrap(); - let path = path.to_string_lossy().into_owned(); - let mut binary = document("https://example.com"); - binary.body = RequestBody::Binary { path: path.clone() }; + let plain = first.after(302, &location("http://shop.test/b")).unwrap(); assert_eq!( - compose(RequestKind::Http, HttpMethod::Put, &binary, ¬hing()), - Err(SendError::FileTooLarge(path)) + names(&same), + [ + "Authorization", + "Cookie", + "Proxy-Authorization", + "X-Keep", + "Referer" + ] ); + assert_eq!(same.headers.last().unwrap().1, "https://shop.test/a"); + assert_eq!(names(&other_host), ["X-Keep", "Referer"]); + assert_eq!(names(&other_port), ["X-Keep", "Referer"]); + assert_eq!(names(&plain), ["X-Keep"]); } + /// The jar's line for the hop's own URL, unless a cookie is typed: what is typed wins. #[test] - fn a_graphql_request_is_a_json_post_or_its_parts_in_the_query_of_a_get() { - let mut query = document("https://api.exemple.fr/graphql"); - query.body = RequestBody::Text { - text: "ignored".to_string(), - }; - query.graphql = GraphqlDocument { - query: "query A { a }".to_string(), - variables: "{\"n\": 1}".to_string(), - operation_name: Some("A".to_string()), - as_get: false, - }; + fn a_hop_carries_the_jar_s_line_for_its_url_unless_a_cookie_is_typed() { + let jar = [crate::http::cookies::JarCookie { + name: "sid".to_string(), + value: "1".to_string(), + domain: "shop.test".to_string(), + host_only: true, + path: "/".to_string(), + expires: None, + secure: false, + http_only: false, + same_site: None, + created: None, + }]; - let post = compose(RequestKind::Graphql, HttpMethod::Delete, &query, ¬hing()).unwrap(); - assert_eq!(post.method, HttpMethod::Post); - assert_eq!(header(&post, "content-type"), Some("application/json")); assert_eq!( - post.body, - OutgoingBody::Bytes( - br#"{"query":"query A { a }","variables":{"n": 1},"operationName":"A"}"#.to_vec() - ) + hop(reqwest::Method::GET, "https://shop.test/", &[]) + .cookie(Some(&jar)) + .as_deref(), + Some("sid=1") ); - assert!(post.graphql); - - query.graphql.as_get = true; - let get = compose(RequestKind::Graphql, HttpMethod::Post, &query, ¬hing()).unwrap(); assert_eq!( - (get.method, &get.body), - (HttpMethod::Get, &OutgoingBody::None) + hop(reqwest::Method::GET, "https://other.test/", &[]).cookie(Some(&jar)), + None ); assert_eq!( - get.url.as_str(), - "https://api.exemple.fr/graphql?query=query+A+%7B+a+%7D&variables=%7B%22n%22%3A+1%7D&operationName=A" + hop( + reqwest::Method::GET, + "https://shop.test/", + &[("cookie", "typed=1")] + ) + .cookie(Some(&jar)), + None + ); + assert_eq!( + hop(reqwest::Method::GET, "https://shop.test/", &[]).cookie(None), + None ); - - query.graphql.variables = "[1]".to_string(); - assert!(matches!( - compose(RequestKind::Graphql, HttpMethod::Post, &query, ¬hing()), - Err(SendError::GraphqlVariables(_)) - )); } + /// Text by its type, or failing one by its bytes reading as UTF-8. Private: an answer's body + /// is read over the network. #[test] fn a_body_is_text_by_its_type_or_failing_one_by_its_bytes() { - assert!(is_text(Some("application/json; charset=utf-8"), &[0xff])); - assert!(is_text(Some("application/problem+xml"), b"")); - assert!(!is_text(Some("image/png"), b"PNG")); - assert!(is_text(None, "héllo".as_bytes())); - assert!(!is_text(None, &[0xff, 0xfe, 0x00])); + let utf8 = "é".as_bytes(); + let binary = [0xff, 0x00]; + for (kind, bytes, text) in [ + (Some("TEXT/csv; charset=latin1"), &binary[..], true), + (Some("application/vnd.api+json"), &binary[..], true), + (Some("application/xml"), &binary[..], true), + (Some("application/x-www-form-urlencoded"), &binary[..], true), + (Some("image/png"), utf8, false), + (Some("application/pdf"), utf8, false), + (Some("application/zip"), utf8, false), + (Some("application/octet-stream"), utf8, false), + (Some("application/x-custom"), utf8, true), + (Some("application/x-custom"), &binary[..], false), + (None, utf8, true), + (None, &binary[..], false), + ] { + assert_eq!(is_text(kind, bytes), text, "{kind:?}"); + } } } diff --git a/crates/engine/tests/commands/http_send.rs b/crates/engine/tests/commands/http_send.rs index 248bb69b3..e5496816c 100644 --- a/crates/engine/tests/commands/http_send.rs +++ b/crates/engine/tests/commands/http_send.rs @@ -6,17 +6,30 @@ use std::sync::{Arc, mpsc}; use std::thread; use std::time::Duration; -use engine::error::ErrorCode; +use engine::error::{AppError, ErrorCode}; +use engine::http::codegen::{CodeOptions, CodeTarget}; +use engine::http::environments::{EnvironmentPatch, Variable, VariableKind}; +use engine::http::graphql::{GraphqlDocument, QueryFault}; +use engine::http::history::HistoryItem; use engine::http::model::{ - ContainerSettings, FormPart, HttpItem, HttpItemKind, HttpMethod, KeyValue, RequestAuth, - RequestBody, RequestDocument, RequestKind, + ContainerSettings, FormPart, HttpItem, HttpItemKind, HttpMethod, HttpRequestDraft, KeyPlace, + KeyValue, RequestAuth, RequestBody, RequestDocument, RequestKind, +}; +use engine::http::send::{ + ImpliedSource, KEPT_LIMIT, NoteText, SENT_FILE_MEGABYTES, SHOWN_LIMIT, SendRequest, SentBody, + SentResponse, USER_AGENT, }; -use engine::http::send::{ImpliedSource, SHOWN_LIMIT, SendRequest, SentBody, USER_AGENT}; use engine::http::transport::TransportSettings; +use engine::http::variables::VariableScope; use engine::http::{ - cancel_http_send, create_http_collection, forget_http_response, http_response_image, - http_response_note, implied_http_headers, save_http_response, save_http_settings, - send_http_request, + CodeRequestOf, VariablesRequest, add_graphql_variables, cancel_http_send, clear_http_cookies, + clear_http_history, count_http_cookies, count_http_history, create_http_collection, + create_http_environment, create_http_folder, create_http_request, delete_http_cookie, + delete_http_cookie_domain, delete_http_history_entry, delete_http_item, describe_graphql, + forget_http_response, generate_http_code, http_cookies, http_history, http_history_draft, + http_history_entry, http_history_onto_request, http_response_image, http_response_note, + http_variables, implied_http_headers, restore_http_history_entry, save_http_environment, + save_http_globals, save_http_response, save_http_settings, send_http_request, }; use engine::notes::language::Language; @@ -123,34 +136,189 @@ pub(super) fn request(url: &str) -> SendRequest { } } +fn send(session: &Session, request: SendRequest) -> Result { + session.wait(|e| send_http_request(e, request)) +} + +/// A `GET` of `path` on the loopback server, answered. +fn fetched(session: &Session, port: u16, path: &str) -> SentResponse { + send(session, request(&format!("http://127.0.0.1:{port}{path}"))).unwrap() +} + +fn row(key: &str, value: &str) -> KeyValue { + KeyValue { + key: key.to_string(), + value: value.to_string(), + ..KeyValue::default() + } +} + +fn off(key: &str) -> KeyValue { + KeyValue { + enabled: false, + ..row(key, "") + } +} + +/// A collection handing `settings` down, by its id. +fn collection_with(session: &Session, settings: ContainerSettings) -> String { + let id = session + .call(|e| create_http_collection(e, "API")) + .unwrap() + .id; + hand_down(session, HttpItemKind::Collection, &id, settings); + id +} + +fn hand_down(session: &Session, kind: HttpItemKind, id: &str, settings: ContainerSettings) { + let item = HttpItem { + kind, + id: id.to_string(), + }; + session + .call(|e| save_http_settings(e, &item, settings)) + .unwrap(); +} + +fn variables_of(variables: Vec) -> ContainerSettings { + ContainerSettings { + variables, + ..ContainerSettings::default() + } +} + +fn headers_of(headers: Vec) -> ContainerSettings { + ContainerSettings { + headers, + ..ContainerSettings::default() + } +} + +/// A port nothing listens on. +fn closed_port() -> u16 { + let closed = TcpListener::bind("127.0.0.1:0").unwrap(); + closed.local_addr().unwrap().port() +} + +/// A server that takes the connections and never answers. +fn silent(connections: usize) -> u16 { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + thread::spawn(move || { + let held: Vec<_> = listener.incoming().take(connections).collect(); + thread::sleep(Duration::from_secs(20)); + drop(held); + }); + port +} + +fn params(failed: &AppError) -> String { + failed + .params + .iter() + .map(|(key, value)| format!("{key}={value}")) + .collect::>() + .join(" ") +} + +/// The history, newest first. +fn history(session: &Session) -> Vec { + session + .call(|e| http_history(e, 0)) + .unwrap() + .into_iter() + .flat_map(|day| day.items) + .collect() +} + +fn jar(session: &Session) -> Vec { + let mut names: Vec = session + .call(http_cookies) + .unwrap() + .into_iter() + .flat_map(|domain| domain.cookies) + .map(|stored| stored.cookie.name) + .collect(); + names.sort_unstable(); + names +} + +#[test] +fn a_send_answers_locked_before_a_library_is_open() { + let session = Session::locked(); + + let answer = send(&session, request("http://127.0.0.1:9/")); + + assert_eq!(code(answer), ErrorCode::Locked); +} + #[test] -fn a_request_leaves_with_what_its_collection_hands_down_and_its_answer_comes_back() { +fn a_request_leaves_with_what_its_collection_hands_down_and_its_body() { let session = Session::open(); - let api = session.call(|e| create_http_collection(e, "API")).unwrap(); - let settings = ContainerSettings { - auth: RequestAuth::Bearer { - token: "s3cret".to_string(), + let api = collection_with( + &session, + ContainerSettings { + auth: RequestAuth::Bearer { + token: "s3cret".to_string(), + }, + ..headers_of(vec![row("Accept", "application/json")]) }, - headers: vec![KeyValue { - key: "Accept".to_string(), - value: "application/json".to_string(), - ..KeyValue::default() - }], - ..ContainerSettings::default() + ); + let (port, seen) = serve(1, |_, _| response("200 OK", &[], b"")); + let mut sent = request(&format!("http://127.0.0.1:{port}/users?page=1")); + sent.method = HttpMethod::Post; + sent.collection_id = Some(api); + sent.document.body = RequestBody::Json { + text: "{\"name\":\"Ada\"}".to_string(), }; - session - .call(|e| { - save_http_settings( - e, - &HttpItem { - kind: HttpItemKind::Collection, - id: api.id.clone(), - }, - settings, - ) - }) - .unwrap(); - let (port, seen) = serve(1, |_, _| { + + let answer = send(&session, sent).unwrap(); + + let seen = seen.recv().unwrap(); + assert!(seen.head.starts_with("POST /users?page=1 HTTP/1.1\r\n")); + for (name, value) in [ + ("authorization", "Bearer s3cret"), + ("accept", "application/json"), + ("content-type", "application/json"), + ] { + assert_eq!(header_of(&seen, name).as_deref(), Some(value), "{name}"); + } + assert_eq!(seen.body, b"{\"name\":\"Ada\"}"); + // The exchange says the same: what the timeline shows is what left. + assert_eq!(answer.exchange.method, HttpMethod::Post); + let shown = row("Authorization", "Bearer s3cret"); + assert!(answer.exchange.headers.contains(&shown)); + let text = "{\"name\":\"Ada\"}".to_string(); + assert_eq!(answer.exchange.body, SentBody::Text { text }); +} + +#[test] +fn every_method_leaves_as_itself() { + let session = Session::open(); + let methods = [ + (HttpMethod::Get, "GET"), + (HttpMethod::Post, "POST"), + (HttpMethod::Put, "PUT"), + (HttpMethod::Patch, "PATCH"), + (HttpMethod::Delete, "DELETE"), + (HttpMethod::Head, "HEAD"), + (HttpMethod::Options, "OPTIONS"), + ]; + let (port, seen) = serve(methods.len(), |_, _| response("204 No Content", &[], b"")); + + for (method, word) in methods { + let mut sent = request(&format!("http://127.0.0.1:{port}/a")); + sent.method = method; + send(&session, sent).unwrap(); + let head = seen.recv().unwrap().head; + assert!(head.starts_with(&format!("{word} /a ")), "{head}"); + } +} + +#[test] +fn an_answer_says_its_status_its_body_laid_out_and_its_cookies() { + let session = Session::open(); + let (port, _seen) = serve(1, |_, _| { response( "201 Created", &[ @@ -161,13 +329,7 @@ fn a_request_leaves_with_what_its_collection_hands_down_and_its_answer_comes_bac ) }); - let mut sent = request(&format!("http://127.0.0.1:{port}/users?page=1")); - sent.method = HttpMethod::Post; - sent.collection_id = Some(api.id.clone()); - sent.document.body = RequestBody::Json { - text: "{\"name\":\"Ada\"}".to_string(), - }; - let answer = session.wait(|e| send_http_request(e, sent)).unwrap(); + let answer = fetched(&session, port, "/"); assert_eq!((answer.status, answer.reason.as_str()), (201, "Created")); assert_eq!((answer.body.as_str(), answer.size), ("{\"id\":7}", 8)); @@ -176,80 +338,41 @@ fn a_request_leaves_with_what_its_collection_hands_down_and_its_answer_comes_bac assert_eq!(answer.pretty.as_deref(), Some("{\n \"id\": 7\n}")); assert_eq!(answer.cookies.len(), 1); assert!(answer.cookies[0].http_only); - assert_eq!(answer.exchange.method, HttpMethod::Post); - assert_eq!( - answer.exchange.body, - SentBody::Text { - text: "{\"name\":\"Ada\"}".to_string() - } - ); - assert!( - answer - .exchange - .headers - .iter() - .any(|header| header.key == "Authorization" && header.value == "Bearer s3cret") - ); - assert!( - answer - .headers - .iter() - .any(|header| header.key == "content-type" && header.value == "application/json") - ); + let typed = row("content-type", "application/json"); + assert!(answer.headers.contains(&typed)); +} - let seen = seen.recv().unwrap(); - assert!(seen.head.starts_with("POST /users?page=1 HTTP/1.1\r\n")); - let head = seen.head.to_ascii_lowercase(); - assert!(head.contains("authorization: bearer s3cret\r\n")); - assert!(head.contains("accept: application/json\r\n")); - assert!(head.contains("content-type: application/json\r\n")); - assert_eq!(seen.body, b"{\"name\":\"Ada\"}"); +#[test] +fn a_status_with_no_words_of_its_own_says_none() { + let session = Session::open(); + let (port, _seen) = serve(1, |_, _| response("299 Whatever", &[], b"")); + + let answer = fetched(&session, port, "/"); + + assert_eq!((answer.status, answer.reason.as_str()), (299, "")); } -fn variable(name: &str, value: &str) -> engine::http::environments::Variable { - engine::http::environments::Variable { +fn variable(name: &str, value: &str) -> Variable { + Variable { name: name.to_string(), value: value.to_string(), - ..Default::default() + ..Variable::default() } } /// A request in a folder of a collection, each level setting variables, sent with Staging /// over globals that would send it nowhere. fn layered(session: &Session, port: u16) -> SendRequest { - use engine::http::environments::{EnvironmentPatch, VariableKind}; - use engine::http::{ - create_http_environment, create_http_folder, save_http_environment, save_http_globals, - }; - - let api = session.call(|e| create_http_collection(e, "API")).unwrap(); + let api = collection_with( + session, + variables_of(vec![variable("tenant", "acme"), variable("page", "9")]), + ); let invoices = session - .call(|e| create_http_folder(e, &api.id, None, "Factures")) - .unwrap(); - for (kind, id, variables) in [ - ( - HttpItemKind::Collection, - &api.id, - vec![variable("tenant", "acme"), variable("page", "9")], - ), - ( - HttpItemKind::Folder, - &invoices.id, - vec![variable("page", "3")], - ), - ] { - let item = HttpItem { - kind, - id: id.clone(), - }; - let settings = ContainerSettings { - variables, - ..ContainerSettings::default() - }; - session - .call(|e| save_http_settings(e, &item, settings)) - .unwrap(); - } + .call(|e| create_http_folder(e, &api, None, "Factures")) + .unwrap() + .id; + let page = variables_of(vec![variable("page", "3")]); + hand_down(session, HttpItemKind::Folder, &invoices, page); let staging = session .call(|e| create_http_environment(e, "Staging")) .unwrap(); @@ -272,15 +395,11 @@ fn layered(session: &Session, port: u16) -> SendRequest { let mut sent = request("{{baseUrl}}/invoices?page={{page}}&size={{size}}"); sent.method = HttpMethod::Post; - sent.collection_id = Some(api.id); - sent.folder_id = Some(invoices.id); + sent.collection_id = Some(api); + sent.folder_id = Some(invoices); sent.environment_id = Some(staging.id); sent.document.variables = vec![variable("size", "50")]; - sent.document.headers = vec![KeyValue { - key: "X-Tenant".to_string(), - value: "{{tenant}}".to_string(), - ..KeyValue::default() - }]; + sent.document.headers = vec![row("X-Tenant", "{{tenant}}")]; sent.document.auth = RequestAuth::Bearer { token: "{{token}}".to_string(), }; @@ -290,32 +409,26 @@ fn layered(session: &Session, port: u16) -> SendRequest { sent } -/// #486: the nearest level wins — the request's own, a folder's, the collection's, the -/// environment chosen, the globals — in the URL, a header, the body and the auth. +/// The request's own, a folder's, the collection's, the environment chosen, the globals. #[test] -fn a_variable_is_sent_as_the_nearest_level_sets_it() { - use engine::http::variables::VariableScope; - use engine::http::{VariablesRequest, http_variables}; - +fn a_variable_is_listed_with_the_nearest_level_that_sets_it() { let session = Session::open(); - let (port, seen) = serve(1, |_, _| response("200 OK", &[], b"ok")); - let sent = layered(&session, port); - + let sent = layered(&session, 9); let asked = VariablesRequest { kind: RequestKind::Http, - document: sent.document.clone(), - collection_id: sent.collection_id.clone(), - folder_id: sent.folder_id.clone(), - environment_id: sent.environment_id.clone(), + document: sent.document, + collection_id: sent.collection_id, + folder_id: sent.folder_id, + environment_id: sent.environment_id, }; + let used = session.call(|e| http_variables(e, asked)).unwrap(); + let scopes: Vec<(&str, Option)> = used .iter() .map(|known| { - ( - known.name.as_str(), - known.resolved.as_ref().map(|found| found.scope), - ) + let scope = known.resolved.as_ref().map(|found| found.scope); + (known.name.as_str(), scope) }) .collect(); assert_eq!( @@ -329,70 +442,86 @@ fn a_variable_is_sent_as_the_nearest_level_sets_it() { ("token", Some(VariableScope::Environment)), ] ); +} + +#[test] +fn a_variable_is_sent_as_the_nearest_level_sets_it_everywhere_it_is_written() { + let session = Session::open(); + let (port, seen) = serve(1, |_, _| response("200 OK", &[], b"ok")); + let sent = layered(&session, port); + + send(&session, sent).unwrap(); - session.wait(|e| send_http_request(e, sent)).unwrap(); let seen = seen.recv().unwrap(); - assert!( - seen.head - .starts_with("POST /invoices?page=3&size=50 HTTP/1.1\r\n"), - "{}", - seen.head - ); + let line = "POST /invoices?page=3&size=50 HTTP/1.1\r\n"; + assert!(seen.head.starts_with(line), "{}", seen.head); assert_eq!(header_of(&seen, "x-tenant").as_deref(), Some("acme")); - assert_eq!( - header_of(&seen, "authorization").as_deref(), - Some("Bearer t0k3n") - ); + let auth = header_of(&seen, "authorization"); + assert_eq!(auth.as_deref(), Some("Bearer t0k3n")); assert_eq!(seen.body, br#"{"tenant":"acme"}"#); } -/// #487: the timeline and the history show a secret variable by its name — the server that -/// echoes the token included — and the history says which environment the send left with. #[test] -fn a_secret_variable_shows_by_its_name_once_the_request_left() { - use engine::http::{http_history, http_history_entry}; +fn an_environment_gone_since_leaves_the_globals_alone() { + let session = Session::open(); + let (port, seen) = serve(1, |_, _| response("200 OK", &[], b"")); + let base = variable("baseUrl", &format!("http://127.0.0.1:{port}")); + session.call(|e| save_http_globals(e, &[base])).unwrap(); + let staging = session + .call(|e| create_http_environment(e, "Staging")) + .unwrap(); + let elsewhere = EnvironmentPatch { + variables: Some(vec![variable("baseUrl", "http://nowhere.invalid")]), + ..EnvironmentPatch::default() + }; + session + .call(|e| save_http_environment(e, &staging.id, &elsewhere)) + .unwrap(); + let mut sent = request("{{baseUrl}}/a"); + sent.environment_id = Some("gone".to_string()); + + send(&session, sent).unwrap(); + + assert!(seen.recv().unwrap().head.starts_with("GET /a ")); +} +/// The server that echoes the token included. +#[test] +fn a_secret_variable_shows_by_its_name_once_the_request_left() { let session = Session::open(); - let (port, seen) = serve(1, |request, _| { - response("200 OK", &[], request.head.as_bytes()) - }); + let (port, seen) = serve(1, |seen, _| response("200 OK", &[], seen.head.as_bytes())); let sent = layered(&session, port); - let answer = session.wait(|e| send_http_request(e, sent)).unwrap(); - assert!(seen.recv().unwrap().head.contains("t0k3n")); - assert!( - answer - .exchange - .headers - .iter() - .any(|header| header.key == "Authorization" && header.value == "Bearer {{token}}") - ); + let answer = send(&session, sent).unwrap(); - let days = session.call(|e| http_history(e, 0)).unwrap(); - let item = &days[0].items[0]; - assert_eq!( - item.summary - .environment - .as_ref() - .map(|sent| sent.name.as_str()), - Some("Staging") - ); - let entry = session.call(|e| http_history_entry(e, &item.id)).unwrap(); + assert!(seen.recv().unwrap().head.contains("t0k3n")); + let shown = row("Authorization", "Bearer {{token}}"); + assert!(answer.exchange.headers.contains(&shown)); + let id = history(&session)[0].id.clone(); + let entry = session.call(|e| http_history_entry(e, &id)).unwrap(); let kept = format!("{entry:?}"); assert!(!kept.contains("t0k3n"), "{kept}"); assert!(kept.contains("{{token}}")); } -/// #488: the code a request writes resolves as a send does, a secret left as its name until it -/// is asked for in clear, and is saved as its target's language. #[test] -fn a_request_is_written_as_code_from_the_levels_a_send_resolves_from() { - use engine::http::codegen::{CodeOptions, CodeTarget}; - use engine::http::{CodeRequestOf, generate_http_code}; - +fn the_history_says_which_environment_a_send_left_with() { let session = Session::open(); - let sent = layered(&session, 8080); - let asked = |target: CodeTarget, include_secrets: bool| CodeRequestOf { + let (port, _seen) = serve(2, |_, _| response("200 OK", &[], b"")); + let sent = layered(&session, port); + + send(&session, sent).unwrap(); + fetched(&session, port, "/"); + + let names: Vec> = history(&session) + .into_iter() + .map(|item| item.summary.environment.map(|sent| sent.name)) + .collect(); + assert_eq!(names, [None, Some("Staging".to_string())]); +} + +fn code_of(sent: SendRequest, target: CodeTarget, include_secrets: bool) -> CodeRequestOf { + CodeRequestOf { target, options: CodeOptions { resolve_variables: true, @@ -402,229 +531,271 @@ fn a_request_is_written_as_code_from_the_levels_a_send_resolves_from() { }, kind: sent.kind, method: sent.method, - document: sent.document.clone(), - collection_id: sent.collection_id.clone(), - folder_id: sent.folder_id.clone(), - environment_id: sent.environment_id.clone(), - }; + document: sent.document, + collection_id: sent.collection_id, + folder_id: sent.folder_id, + environment_id: sent.environment_id, + } +} - let kept = session - .call(|e| generate_http_code(e, asked(CodeTarget::Curl, false))) - .unwrap(); - assert!( - kept.code.starts_with( - "curl --request POST --url 'http://127.0.0.1:8080/invoices?page=3&size=50'" - ), - "{}", - kept.code - ); - assert!(kept.code.contains("'Authorization: Bearer {{token}}'")); - assert!(kept.code.contains("'X-Tenant: acme'")); - assert_eq!(kept.secrets, ["token"]); - assert_eq!(kept.language, Language::Sh); +#[test] +fn a_request_is_written_as_code_from_the_levels_a_send_resolves_from() { + let session = Session::open(); + let sent = layered(&session, 8080); - let clear = session - .call(|e| generate_http_code(e, asked(CodeTarget::Powershell, true))) - .unwrap(); - assert!(clear.code.contains("'Bearer t0k3n'"), "{}", clear.code); - assert!(clear.secrets.is_empty()); - assert_eq!(clear.language, Language::Ps1); + let asked = code_of(sent, CodeTarget::Curl, false); + let written = session.call(|e| generate_http_code(e, asked)).unwrap(); + + let start = "curl --request POST --url 'http://127.0.0.1:8080/invoices?page=3&size=50'"; + assert!(written.code.starts_with(start), "{}", written.code); + assert!(written.code.contains("'Authorization: Bearer {{token}}'")); + assert!(written.code.contains("'X-Tenant: acme'")); + assert_eq!(written.secrets, ["token"]); + assert_eq!(written.language, Language::Sh); +} + +#[test] +fn a_secret_is_written_in_the_code_only_when_asked_for_in_clear() { + let session = Session::open(); + let sent = layered(&session, 8080); + + let asked = code_of(sent, CodeTarget::Powershell, true); + let written = session.call(|e| generate_http_code(e, asked)).unwrap(); + + assert!(written.code.contains("'Bearer t0k3n'"), "{}", written.code); + assert!(written.secrets.is_empty()); + assert_eq!(written.language, Language::Ps1); } -/// Fork C: a name no level sets is refused by name, and nothing leaves. #[test] -fn a_variable_set_nowhere_stops_the_send_by_its_name() { +fn a_variable_set_nowhere_stops_the_send_by_its_name_and_records_nothing() { let session = Session::open(); let mut sent = request("http://127.0.0.1:9/tenants/{{tenantId}}"); sent.document.variables = vec![variable("other", "1")]; - let answer = session.wait(|e| send_http_request(e, sent)); + let refused = send(&session, sent).unwrap_err(); - let name = answer - .as_ref() - .err() - .and_then(|error| error.params.get("name").cloned()); - assert_eq!(code(answer), ErrorCode::HttpVariable); - assert_eq!(name.as_deref(), Some("tenantId")); + assert_eq!(refused.code, ErrorCode::HttpVariable); + assert_eq!(params(&refused), "name=tenantId"); + assert!(history(&session).is_empty()); } -/// `api.github.com` answers 403 to a request that names no agent: none was sent. +/// `api.github.com` answers 403 to a request that names no agent. #[test] -fn a_request_names_the_application_unless_a_row_says_otherwise_or_switches_it_off() { +fn a_request_names_the_application_as_the_editor_lists_it() { let session = Session::open(); - let (port, seen) = serve(5, |_, _| response("200 OK", &[], b"ok")); - let url = format!("http://127.0.0.1:{port}/events"); - let agent = |seen: &Seen| { - seen.head.lines().find_map(|line| { - let (name, value) = line.split_once(':')?; - name.eq_ignore_ascii_case("user-agent") - .then(|| value.trim().to_string()) - }) - }; - let row = |value: &str, enabled: bool| KeyValue { - enabled, - key: "User-Agent".to_string(), - value: value.to_string(), - ..KeyValue::default() - }; - let hand_down = |id: &str, headers: Vec| { - let item = HttpItem { - kind: HttpItemKind::Collection, - id: id.to_string(), - }; - let settings = ContainerSettings { - headers, - ..ContainerSettings::default() - }; - session - .call(|e| save_http_settings(e, &item, settings)) - .unwrap(); - }; + let (port, seen) = serve(1, |_, _| response("200 OK", &[], b"ok")); + let plain = request(&format!("http://127.0.0.1:{port}/events")); - // Nothing said: the application and its version, as the editor lists them. - let answer = session - .wait(|e| send_http_request(e, request(&url))) - .unwrap(); - let left = seen.recv().unwrap(); - assert_eq!(agent(&left).as_deref(), Some(USER_AGENT)); - assert!(left.head.to_ascii_lowercase().contains("accept: */*\r\n")); - assert!( - answer - .exchange - .headers - .iter() - .any(|header| header.key == "User-Agent" && header.value == USER_AGENT) - ); let listed = session - .call(|e| implied_http_headers(e, RequestKind::Http, &request(&url).document, None, None)) + .call(|e| implied_http_headers(e, RequestKind::Http, &plain.document, None, None)) .unwrap(); + let answer = send(&session, plain).unwrap(); + + let listed: Vec<(String, String, ImpliedSource)> = listed + .into_iter() + .map(|header| (header.name, header.value, header.source)) + .collect(); + let host = format!("127.0.0.1:{port}"); + let expected = [ + ("User-Agent", USER_AGENT.to_string(), ImpliedSource::Default), + ("Accept", "*/*".to_string(), ImpliedSource::Default), + ("Host", host, ImpliedSource::Url), + ]; assert_eq!( - listed - .iter() - .map(|header| (header.name.as_str(), header.value.clone(), header.source)) - .collect::>(), - vec![ - ("User-Agent", USER_AGENT.to_string(), ImpliedSource::Default), - ("Accept", "*/*".to_string(), ImpliedSource::Default), - ("Host", format!("127.0.0.1:{port}"), ImpliedSource::Url), - ] + listed, + expected.map(|(name, value, by)| (name.to_string(), value, by)) ); - for header in &listed { - let line = format!("{}: {}\r\n", header.name, header.value).to_ascii_lowercase(); - assert!(left.head.to_ascii_lowercase().contains(&line), "{line}"); + let seen = seen.recv().unwrap(); + for (name, value, _) in listed { + assert_eq!(header_of(&seen, &name), Some(value), "{name}"); } + let shown = row("User-Agent", USER_AGENT); + assert!(answer.exchange.headers.contains(&shown)); +} + +#[test] +fn a_collection_names_another_agent_and_the_request_its_own_over_it() { + let session = Session::open(); + let (port, seen) = serve(2, |_, _| response("200 OK", &[], b"ok")); + let api = collection_with(&session, headers_of(vec![row("User-Agent", "Equipe/1")])); + let mut placed = request(&format!("http://127.0.0.1:{port}/")); + placed.collection_id = Some(api.clone()); + let mut own = placed.clone(); + own.document.headers = vec![row("User-Agent", "curl/8.5.0")]; - // Its collection names another, then the request its own over it. - let api = session.call(|e| create_http_collection(e, "API")).unwrap(); - hand_down(&api.id, vec![row("Equipe/1", true)]); - let mut placed = request(&url); - placed.collection_id = Some(api.id.clone()); - session - .wait(|e| send_http_request(e, placed.clone())) - .unwrap(); - assert_eq!(agent(&seen.recv().unwrap()).as_deref(), Some("Equipe/1")); let listed = session .call(|e| { - implied_http_headers( - e, - RequestKind::Http, - &placed.document, - Some(api.id.clone()), - None, - ) + let api = Some(api.clone()); + implied_http_headers(e, RequestKind::Http, &placed.document, api, None) }) .unwrap(); - assert_eq!( - listed - .iter() - .map(|header| (header.value.as_str(), header.source)) - .next(), - Some(("Equipe/1", ImpliedSource::Above)) - ); - assert_eq!( - listed[0].from.as_ref().map(|from| from.name.as_str()), - Some("API") - ); - - let mut own = placed.clone(); - own.document.headers = vec![row("curl/8.5.0", true)]; - session.wait(|e| send_http_request(e, own)).unwrap(); - assert_eq!(agent(&seen.recv().unwrap()).as_deref(), Some("curl/8.5.0")); - - // Switched off, in the request or above it: none at all. - let mut silent = request(&url); - silent.document.headers = vec![row("", false)]; - session.wait(|e| send_http_request(e, silent)).unwrap(); - assert_eq!(agent(&seen.recv().unwrap()), None); + send(&session, placed).unwrap(); + send(&session, own).unwrap(); + + assert_eq!(listed[0].source, ImpliedSource::Above); + assert_eq!(listed[0].from.as_ref().unwrap().name, "API"); + let agents = [seen.recv().unwrap(), seen.recv().unwrap()]; + let agents = agents.map(|seen| header_of(&seen, "user-agent").unwrap()); + assert_eq!(agents, ["Equipe/1", "curl/8.5.0"]); +} - hand_down(&api.id, vec![row("Equipe/1", false)]); - session.wait(|e| send_http_request(e, placed)).unwrap(); - assert_eq!(agent(&seen.recv().unwrap()), None); +#[test] +fn an_agent_switched_off_in_the_request_or_above_it_sends_none() { + let session = Session::open(); + let (port, seen) = serve(2, |_, _| response("200 OK", &[], b"ok")); + let api = collection_with(&session, headers_of(vec![off("User-Agent")])); + let mut own = request(&format!("http://127.0.0.1:{port}/")); + own.document.headers = vec![off("User-Agent")]; + let mut above = request(&format!("http://127.0.0.1:{port}/")); + above.collection_id = Some(api); + + send(&session, own).unwrap(); + send(&session, above).unwrap(); + + for _ in 0..2 { + assert_eq!(header_of(&seen.recv().unwrap(), "user-agent"), None); + } } #[test] -fn the_redirects_are_followed_and_recorded() { +fn a_body_past_what_is_shown_is_cut_and_its_size_is_whole() { let session = Session::open(); - let (port, _seen) = serve(2, |seen, port| { - if seen.head.starts_with("GET /old ") { - response( - "301 Moved Permanently", - &[("Location", &format!("http://127.0.0.1:{port}/new"))], - b"", - ) - } else { - response("200 OK", &[("Content-Type", "text/plain")], b"here") - } + // Cut on a character, never inside one: `é` is two bytes over the edge. + let served = format!("{}é tail", "a".repeat(SHOWN_LIMIT - 1)); + let size = served.len(); + let (port, _seen) = serve(1, move |_, _| { + response( + "200 OK", + &[("Content-Type", "text/plain")], + served.as_bytes(), + ) }); - let answer = session - .wait(|e| send_http_request(e, request(&format!("http://127.0.0.1:{port}/old")))) - .unwrap(); + let answer = fetched(&session, port, "/"); - assert_eq!(answer.body, "here"); - assert_eq!(answer.url, format!("http://127.0.0.1:{port}/new")); - assert_eq!(answer.redirects.len(), 1); - assert_eq!(answer.redirects[0].status, 301); + assert!(answer.cut && !answer.incomplete && !answer.binary); + assert_eq!(answer.body, "a".repeat(SHOWN_LIMIT - 1)); + assert_eq!(answer.size as usize, size); } #[test] -fn a_body_past_what_is_shown_is_cut_and_saved_whole_to_a_file() { +fn a_json_body_past_what_is_shown_is_not_laid_out() { let session = Session::open(); - let large = vec![b'a'; SHOWN_LIMIT + 10]; - let served = large.clone(); + let served = format!("\"{}\"", "a".repeat(SHOWN_LIMIT)); let (port, _seen) = serve(1, move |_, _| { - response("200 OK", &[("Content-Type", "text/plain")], &served) + let json = [("Content-Type", "application/json")]; + response("200 OK", &json, served.as_bytes()) }); - let answer = session - .wait(|e| send_http_request(e, request(&format!("http://127.0.0.1:{port}/")))) - .unwrap(); - assert!(answer.cut && !answer.incomplete); - assert_eq!(answer.body.len(), SHOWN_LIMIT); - assert_eq!(answer.size as usize, large.len()); + assert_eq!(fetched(&session, port, "/").pretty, None); +} + +#[test] +fn a_reading_stops_at_what_is_kept_and_says_so() { + let session = Session::open(); + let (port, _seen) = serve(1, |_, _| { + let text = [("Content-Type", "text/plain")]; + response("200 OK", &text, &vec![b'a'; KEPT_LIMIT + 1]) + }); + + let answer = fetched(&session, port, "/"); + + assert!(answer.cut && answer.incomplete); + assert_eq!(answer.size as usize, KEPT_LIMIT); +} +#[test] +fn a_body_is_saved_whole_to_a_file_until_its_tab_lets_it_go() { + let session = Session::open(); + let large = vec![b'a'; SHOWN_LIMIT + 10]; + let served = large.clone(); + let (port, _seen) = serve(1, move |_, _| response("200 OK", &[], &served)); let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("body.txt"); - let target = path.to_string_lossy().into_owned(); - assert!( - session - .wait(|e| save_http_response(e, "tab-1".to_string(), target.clone())) - .unwrap() - ); + let save = |id: &str| { + let (id, target) = (id.to_string(), path.to_string_lossy().into_owned()); + session.wait(|e| save_http_response(e, id, target)).unwrap() + }; + fetched(&session, port, "/"); + + assert!(!save("another-tab")); + assert!(save("tab-1")); assert_eq!(std::fs::read(&path).unwrap(), large); assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 1); session.call(|e| forget_http_response(e, "tab-1")).unwrap(); - assert!( - !session - .wait(|e| save_http_response(e, "tab-1".to_string(), target)) - .unwrap() - ); + assert!(!save("tab-1")); } -/// HHI-02: an echo service says the token back; the note made of the answer masks it. #[test] -fn a_note_made_of_an_answer_masks_the_auth_the_server_said_back() { +fn a_body_that_cannot_be_saved_names_why() { + let session = Session::open(); + let (port, _seen) = serve(1, |_, _| response("200 OK", &[], b"a")); + fetched(&session, port, "/"); + let nowhere = tempfile::tempdir().unwrap().path().join("gone").join("a"); + let target = nowhere.to_string_lossy().into_owned(); + + let blank = session.wait(|e| save_http_response(e, "tab-1".to_string(), " ".to_string())); + let failed = session.wait(|e| save_http_response(e, "tab-1".to_string(), target)); + + assert_eq!(code(blank), ErrorCode::InvalidInput); + assert_eq!(code(failed), ErrorCode::FileAccess); +} + +#[test] +fn an_image_is_kept_as_bytes_not_shown_as_text() { + let session = Session::open(); + let (port, _seen) = serve(1, |_, _| { + let typed = [("Content-Type", "image/png; q=1")]; + response("200 OK", &typed, &[0x89, b'P', b'N', b'G']) + }); + + let answer = fetched(&session, port, "/a.png"); + let image = session.wait(|e| http_response_image(e, "tab-1".to_string())); + + assert!(answer.binary && answer.cut); + assert_eq!((answer.body.as_str(), answer.size), ("", 4)); + let image = image.unwrap(); + assert_eq!(image.as_deref(), Some("data:image/png;base64,iVBORw==")); +} + +#[test] +fn an_answer_that_is_no_image_or_too_heavy_is_shown_as_none() { + let session = Session::open(); + let (port, _seen) = serve(3, |seen, _| { + if seen.head.starts_with("GET /heavy ") { + let png = [("Content-Type", "image/png")]; + response("200 OK", &png, &vec![0; 10 * 1024 * 1024 + 1]) + } else if seen.head.starts_with("GET /text ") { + response("200 OK", &[("Content-Type", "text/plain")], b"a") + } else { + response("200 OK", &[], b"a") + } + }); + let image = || { + let id = "tab-1".to_string(); + session.wait(|e| http_response_image(e, id)).unwrap() + }; + + assert_eq!(image(), None); + for path in ["/heavy", "/text", "/untyped"] { + fetched(&session, port, path); + assert_eq!(image(), None, "{path}"); + } +} + +fn note(session: &Session, id: Option<&str>, answer: &SentResponse, text: &str) -> NoteText { + let (id, exchange) = (id.map(str::to_string), answer.exchange.clone()); + session + .wait(|e| http_response_note(e, id, exchange, text.to_string())) + .unwrap() +} + +/// An echo service says the token back. A run's answer is kept under no id: its exchange says +/// what left. +#[test] +fn a_note_made_of_an_answer_masks_the_auth_the_server_said_back() { let session = Session::open(); let (port, _seen) = serve(1, |seen, _| { let auth = header_of(seen, "authorization").unwrap_or_default(); @@ -635,31 +806,46 @@ fn a_note_made_of_an_answer_masks_the_auth_the_server_said_back() { token: "jeton-collection".to_string(), }; - let answer = session.wait(|e| send_http_request(e, echo)).unwrap(); + let answer = send(&session, echo).unwrap(); + assert_eq!(answer.body, "Authorization: Bearer jeton-collection"); + for id in [Some("tab-1"), None] { + let kept = note(&session, id, &answer, &answer.body); + assert_eq!(kept.text, "Authorization: ••••••••"); + assert!(kept.masked); + } + assert!(!note(&session, None, &answer, "plain").masked); +} - let note = session - .wait(|e| { - http_response_note( - e, - Some("tab-1".to_string()), - answer.exchange.clone(), - answer.body.clone(), - ) - }) - .unwrap(); - assert_eq!(note.text, "Authorization: ••••••••"); - assert!(note.masked); +/// Its name is its own: only the send knows the header holds a key. +#[test] +fn a_note_made_of_an_answer_masks_an_api_key_of_any_name() { + let session = Session::open(); + let (port, _seen) = serve(1, |_, _| response("200 OK", &[], b"s3cret-key")); + let mut keyed = request(&format!("http://127.0.0.1:{port}/")); + keyed.document.auth = RequestAuth::ApiKey { + name: "X-Custom".to_string(), + value: "s3cret-key".to_string(), + place: KeyPlace::Header, + }; - // A run's answer, kept under no id: its exchange says what left. - let run = session - .wait(|e| http_response_note(e, None, answer.exchange.clone(), answer.body.clone())) - .unwrap(); - assert_eq!(run.text, "Authorization: ••••••••"); - let plain = session - .wait(|e| http_response_note(e, None, answer.exchange.clone(), "plain".to_string())) - .unwrap(); - assert!(!plain.masked); + let answer = send(&session, keyed).unwrap(); + + let kept = note(&session, Some("tab-1"), &answer, &answer.body); + assert_eq!(kept.text, "••••••••"); +} + +#[test] +fn a_note_made_of_an_answer_writes_a_secret_variable_as_its_name() { + let session = Session::open(); + let (port, _seen) = serve(1, |_, _| response("200 OK", &[], b"t0k3n")); + let mut sent = layered(&session, port); + sent.document.auth = RequestAuth::None; + + let answer = send(&session, sent).unwrap(); + + let kept = note(&session, Some("tab-1"), &answer, "is t0k3n"); + assert_eq!(kept.text, "is {{token}}"); } #[test] @@ -676,211 +862,430 @@ fn a_multipart_file_part_is_sent_with_the_type_of_its_file() { ..FormPart::default() } }; + let text = FormPart { + key: "title".to_string(), + value: "Facture".to_string(), + ..FormPart::default() + }; let (port, seen) = serve(1, |_, _| response("200 OK", &[], b"")); let mut upload = request(&format!("http://127.0.0.1:{port}/upload")); upload.method = HttpMethod::Post; upload.document.body = RequestBody::Multipart { - parts: vec![file("image-test.png"), file("notes.unknown")], + parts: vec![text, file("image-test.png"), file("notes.unknown")], }; - session.wait(|e| send_http_request(e, upload)).unwrap(); + let answer = send(&session, upload).unwrap(); - let body = String::from_utf8_lossy(&seen.recv().unwrap().body).into_owned(); - let type_of = |name: &str| { - let from = &body[body.find(&format!("filename=\"{name}\"")).unwrap()..]; + let body = String::from_utf8(seen.recv().unwrap().body).unwrap(); + let after = |named: &str| { + let from = &body[body.find(named).unwrap()..]; from.lines().nth(1).unwrap_or_default().to_string() }; - assert_eq!(type_of("image-test.png"), "Content-Type: image/png"); - assert_eq!( - type_of("notes.unknown"), - "Content-Type: application/octet-stream" - ); + let png = "Content-Type: image/png"; + assert_eq!(after("filename=\"image-test.png\""), png); + let unknown = "Content-Type: application/octet-stream"; + assert_eq!(after("filename=\"notes.unknown\""), unknown); + let title = "name=\"title\"\r\n\r\nFacture\r\n"; + assert!(body.contains(title), "{body}"); + let fields = ["title", "image-test.png", "notes.unknown"].map(str::to_string); + let fields = fields.to_vec(); + assert_eq!(answer.exchange.body, SentBody::Multipart { fields }); } +/// The client's hello answered in plain text. ⚠️ Closed before the client reads, the connection +/// is reset on Windows, and the reset is all the client sees. +fn plain_over_tls() -> u16 { + let plain = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = plain.local_addr().unwrap().port(); + thread::spawn(move || { + let (mut stream, _) = plain.accept().unwrap(); + let _ = stream.read(&mut [0; 4096]); + let _ = stream.write_all(b"HTTP/1.1 400 Bad Request\r\n\r\n"); + thread::sleep(Duration::from_secs(2)); + }); + port +} + +/// `.invalid` is reserved never to resolve. #[test] -fn an_image_is_kept_as_bytes_not_shown_as_text() { +fn a_send_that_fails_says_why_by_a_code() { let session = Session::open(); - let (port, _seen) = serve(1, |_, _| { - response( - "200 OK", - &[("Content-Type", "image/png")], - &[0x89, b'P', b'N', b'G'], - ) - }); + let closed = format!("http://127.0.0.1:{}/", closed_port()); + let plain = format!("https://127.0.0.1:{}/", plain_over_tls()); + for (url, expected) in [ + ("ftp://example.com", ErrorCode::HttpInvalidUrl), + ("http://devnotes.invalid/", ErrorCode::HttpUnresolved), + (&closed, ErrorCode::HttpRefused), + (&plain, ErrorCode::HttpTls), + ] { + assert_eq!(code(send(&session, request(url))), expected, "{url}"); + } +} - let answer = session - .wait(|e| send_http_request(e, request(&format!("http://127.0.0.1:{port}/a.png")))) - .unwrap(); +/// Closed without an answer: no known cause, so its own words are said. +#[test] +fn a_network_failure_of_no_known_kind_says_its_cause() { + let session = Session::open(); + let (port, _seen) = serve(1, |_, _| Vec::new()); - assert!(answer.binary && answer.cut); - assert_eq!((answer.body.as_str(), answer.size), ("", 4)); - assert_eq!( - session - .wait(|e| http_response_image(e, "tab-1".to_string())) - .unwrap() - .as_deref(), - Some("data:image/png;base64,iVBORw==") - ); + let failed = send(&session, request(&format!("http://127.0.0.1:{port}/"))).unwrap_err(); + + assert_eq!(failed.code, ErrorCode::HttpNetwork); + assert!(!failed.params["cause"].is_empty()); } #[test] -fn a_variable_a_bad_url_a_closed_port_and_a_plain_server_over_tls_each_fail_by_code() { +fn what_cannot_be_composed_is_refused_with_what_to_mend() { let session = Session::open(); - let failed = |url: &str| code(session.wait(|e| send_http_request(e, request(url)))); - - assert_eq!(failed("{{baseUrl}}/users"), ErrorCode::HttpVariable); - assert_eq!(failed("ftp://example.com"), ErrorCode::HttpInvalidUrl); - // `.invalid` is reserved never to resolve. - assert_eq!( - failed("http://devnotes.invalid/"), - ErrorCode::HttpUnresolved - ); + let directory = tempfile::tempdir().unwrap(); + let path = |name: &str| directory.path().join(name).to_string_lossy().into_owned(); + let (missing, heavy) = (path("missing.bin"), path("heavy.bin")); + let length = SENT_FILE_MEGABYTES * 1024 * 1024 + 1; + let file = std::fs::File::create(&heavy).unwrap(); + file.set_len(length).unwrap(); + let binary = |path: &str| { + let mut sent = request("http://127.0.0.1:9/"); + let path = path.to_string(); + sent.document.body = RequestBody::Binary { path }; + sent + }; + let header = |key: &str, value: &str| { + let mut sent = request("http://127.0.0.1:9/"); + sent.document.headers = vec![row(key, value)]; + sent + }; + let mut variables = request("http://127.0.0.1:9/"); + variables.kind = RequestKind::Graphql; + variables.document.graphql.variables = "[]".to_string(); - let closed = TcpListener::bind("127.0.0.1:0").unwrap(); - let port = closed.local_addr().unwrap().port(); - drop(closed); - assert_eq!( - failed(&format!("http://127.0.0.1:{port}/")), - ErrorCode::HttpRefused - ); + let unreadable = format!("path={missing}"); + let too_large = format!("limit=64 path={heavy}"); + for (sent, expected, said) in [ + ( + binary(&missing), + ErrorCode::HttpFileUnreadable, + unreadable.as_str(), + ), + (binary(&heavy), ErrorCode::HttpFileTooLarge, &too_large), + ( + header("X Bad", "1"), + ErrorCode::HttpHeaderName, + "header=X Bad source=request", + ), + ( + header("X-Id", "a\nb"), + ErrorCode::HttpHeaderValue, + "header=X-Id source=request", + ), + (variables, ErrorCode::HttpGraphqlVariables, ""), + ] { + let refused = send(&session, sent).unwrap_err(); + assert_eq!((refused.code, params(&refused).as_str()), (expected, said)); + } +} - // Reads the client's hello and answers it in plain text. ⚠️ Closed before the client reads, - // the connection is reset on Windows, and the reset is all the client sees. - let plain = TcpListener::bind("127.0.0.1:0").unwrap(); - let port = plain.local_addr().unwrap().port(); +/// An HTTPS server on the loopback, under a certificate it signed itself. +fn self_signed() -> u16 { + let certified = rcgen::generate_simple_self_signed(vec!["127.0.0.1".to_string()]).unwrap(); + let key = rustls::pki_types::PrivateKeyDer::Pkcs8(certified.signing_key.serialize_der().into()); + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let config = rustls::ServerConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .unwrap() + .with_no_client_auth() + .with_single_cert(vec![certified.cert.der().clone()], key) + .unwrap(); + let config = Arc::new(config); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); thread::spawn(move || { - let (mut stream, _) = plain.accept().unwrap(); - let _ = stream.read(&mut [0; 4096]); - let _ = stream.write_all(b"HTTP/1.1 400 Bad Request\r\n\r\n"); - thread::sleep(Duration::from_secs(2)); + for stream in listener.incoming().flatten() { + let connection = rustls::ServerConnection::new(Arc::clone(&config)).unwrap(); + let mut tls = rustls::StreamOwned::new(connection, stream); + if tls.read(&mut [0; 4096]).is_ok() { + let _ = tls.write_all(&response("200 OK", &[], b"inside")); + let _ = tls.flush(); + } + } }); - assert_eq!( - failed(&format!("https://127.0.0.1:{port}/")), - ErrorCode::HttpTls + port +} + +#[test] +fn a_self_signed_server_answers_only_with_the_check_off() { + let session = Session::open(); + let checked = request(&format!("https://127.0.0.1:{}/", self_signed())); + let mut unchecked = checked.clone(); + unchecked.document.transport.verify_tls = Some(false); + + assert_eq!(code(send(&session, checked)), ErrorCode::HttpTls); + assert_eq!(send(&session, unchecked).unwrap().body, "inside"); +} + +/// Stated with the value in force and who set it: it used to state the defaults. +#[test] +fn a_timeout_says_the_delay_in_force_and_who_set_it() { + let session = Session::open(); + let api = collection_with( + &session, + ContainerSettings { + transport: TransportSettings { + timeout_ms: Some(300), + ..TransportSettings::default() + }, + ..ContainerSettings::default() + }, ); + let mut inherited = request(&format!("http://127.0.0.1:{}/slow", silent(2))); + inherited.collection_id = Some(api); + let mut own = inherited.clone(); + own.document.transport.timeout_ms = Some(1_000); + + for (sent, said) in [ + (inherited, "amount=300 name=API source=collection unit=ms"), + (own, "amount=1 source=request unit=s"), + ] { + let failed = send(&session, sent).unwrap_err(); + assert_eq!(failed.code, ErrorCode::HttpTimeout); + assert_eq!(params(&failed), said); + } } -/// The sentence states the value in force and who set it: it used to state the defaults, -/// « 30 secondes » for a request cut after one. #[test] -fn a_timeout_and_a_redirect_too_many_say_the_value_in_force_and_who_set_it() { - use engine::http::http_history; +fn a_redirect_too_many_says_the_count_in_force_and_the_history_keeps_it() { + let session = Session::open(); + let again = [("Location", "/again")]; + let (port, _seen) = serve(13, move |_, _| response("302 Found", &again, b"")); + let around = request(&format!("http://127.0.0.1:{port}/around")); + let mut once = around.clone(); + once.document.transport.max_redirects = Some(1); + for (sent, said) in [ + (once, "count=1 source=request"), + (around, "count=10 source=default"), + ] { + let failed = send(&session, sent).unwrap_err(); + assert_eq!(failed.code, ErrorCode::HttpTooManyRedirects); + assert_eq!(params(&failed), said); + } + let last = &history(&session)[0].summary; + assert_eq!(last.failure, Some(ErrorCode::HttpTooManyRedirects)); + assert_eq!(last.failure_params["count"], "10"); +} + +#[test] +fn a_redirect_is_followed_and_recorded() { let session = Session::open(); - let api = session.call(|e| create_http_collection(e, "API")).unwrap(); - session - .call(|e| { - save_http_settings( - e, - &HttpItem { - kind: HttpItemKind::Collection, - id: api.id.clone(), - }, - ContainerSettings { - transport: TransportSettings { - timeout_ms: Some(300), - ..TransportSettings::default() - }, - ..ContainerSettings::default() - }, - ) - }) - .unwrap(); - let params = |failed: &engine::error::AppError| { - failed - .params - .iter() - .map(|(key, value)| format!("{key}={value}")) - .collect::>() - .join(" ") + let (port, _seen) = serve(2, |seen, port| { + if seen.head.starts_with("GET /old ") { + let to = format!("http://127.0.0.1:{port}/new"); + response("301 Moved Permanently", &[("Location", &to)], b"") + } else { + response("200 OK", &[("Content-Type", "text/plain")], b"here") + } + }); + + let answer = fetched(&session, port, "/old"); + + let old = format!("http://127.0.0.1:{port}/old"); + let new = format!("http://127.0.0.1:{port}/new"); + assert_eq!((answer.body.as_str(), &answer.url), ("here", &new)); + assert_eq!(answer.redirects.len(), 1); + let redirect = &answer.redirects[0]; + let met = (redirect.status, &redirect.from, &redirect.url); + assert_eq!(met, (301, &old, &new)); +} + +#[test] +fn a_request_set_not_to_follow_redirects_answers_the_redirect_itself() { + let session = Session::open(); + let new = [("Location", "/new")]; + let (port, _seen) = serve(1, move |_, _| response("302 Found", &new, b"")); + let mut sent = request(&format!("http://127.0.0.1:{port}/old")); + sent.document.transport.follow_redirects = Some(false); + + let answer = send(&session, sent).unwrap(); + + assert_eq!(answer.status, 302); + assert!(answer.redirects.is_empty()); +} + +#[test] +fn a_303_after_a_post_becomes_a_get_without_its_body_and_a_307_sends_it_again() { + let session = Session::open(); + let (port, seen) = serve(4, |seen, _| { + if seen.head.starts_with("POST /see-other ") { + response("303 See Other", &[("Location", "done")], b"") + } else if seen.head.starts_with("POST /temporary ") { + response("307 Temporary Redirect", &[("Location", "/kept")], b"") + } else { + response("200 OK", &[], b"ok") + } + }); + let landed = |path: &str| { + let mut sent = request(&format!("http://127.0.0.1:{port}/{path}")); + sent.method = HttpMethod::Post; + sent.document.body = RequestBody::Json { + text: "{\"a\":1}".to_string(), + }; + send(&session, sent).unwrap(); + assert_eq!(seen.recv().unwrap().body, b"{\"a\":1}"); + seen.recv().unwrap() }; - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let port = listener.local_addr().unwrap().port(); - // Accepts each connection and answers none of them until the test is over. - let silent = thread::spawn(move || listener.incoming().take(2).collect::, _>>()); - let slow = format!("http://127.0.0.1:{port}/slow"); - - let mut inherited = request(&slow); - inherited.collection_id = Some(api.id.clone()); - let failed = session - .wait(|e| send_http_request(e, inherited)) - .unwrap_err(); - assert_eq!(failed.code, ErrorCode::HttpTimeout); - assert_eq!( - params(&failed), - "amount=300 name=API source=collection unit=ms" - ); + let after = landed("see-other"); + assert!(after.head.starts_with("GET /done "), "{}", after.head); + assert!(after.body.is_empty()); + assert_eq!(header_of(&after, "content-type"), None); - let mut own = request(&slow); - own.collection_id = Some(api.id.clone()); - own.document.transport.timeout_ms = Some(1_000); - let failed = session.wait(|e| send_http_request(e, own)).unwrap_err(); - assert_eq!(failed.code, ErrorCode::HttpTimeout); - assert_eq!(params(&failed), "amount=1 source=request unit=s"); - drop(silent); + let after = landed("temporary"); + assert!(after.head.starts_with("POST /kept "), "{}", after.head); + assert_eq!(after.body, b"{\"a\":1}"); + let typed = header_of(&after, "content-type"); + assert_eq!(typed.as_deref(), Some("application/json")); +} - let (port, _seen) = serve(13, |_, port| { - response( - "302 Found", - &[("Location", &format!("http://127.0.0.1:{port}/again"))], - b"", - ) +#[test] +fn a_redirect_to_another_host_carries_neither_a_cookie_nor_the_authorization() { + let session = Session::open(); + let (elsewhere, landed) = serve(2, |_, _| response("200 OK", &[], b"there")); + let (port, seen) = serve(2, move |_, _| { + let to = format!("http://localhost:{elsewhere}/landing"); + let set = ("Set-Cookie", "session=abc; Path=/"); + response("302 Found", &[("Location", to.as_str()), set], b"") }); - let around = format!("http://127.0.0.1:{port}/around"); - let mut once = request(&around); - once.document.transport.max_redirects = Some(1); - let failed = session.wait(|e| send_http_request(e, once)).unwrap_err(); - assert_eq!(failed.code, ErrorCode::HttpTooManyRedirects); - assert_eq!(params(&failed), "count=1 source=request"); - - let failed = session - .wait(|e| send_http_request(e, request(&around))) - .unwrap_err(); - assert_eq!(failed.code, ErrorCode::HttpTooManyRedirects); - assert_eq!(params(&failed), "count=10 source=default"); - - // The history says the same sentence: it keeps the values with the code. - let days = session.call(|e| http_history(e, 0)).unwrap(); - let last = &days[0].items[0].summary; - assert_eq!(last.failure, Some(ErrorCode::HttpTooManyRedirects)); - assert_eq!( - last.failure_params.get("count").map(String::as_str), - Some("10") - ); + let login = format!("http://127.0.0.1:{port}/login"); + let mut sent = request(&login); + sent.document.headers = vec![row("Authorization", "Bearer t0ken"), row("X-Trace", "1")]; + let mut typed = request(&login); + typed.document.headers = vec![row("Cookie", "typed=1")]; + + send(&session, sent).unwrap(); + send(&session, typed).unwrap(); + + let here = [seen.recv().unwrap(), seen.recv().unwrap()]; + let there = [landed.recv().unwrap(), landed.recv().unwrap()]; + let auth = header_of(&here[0], "authorization"); + assert_eq!(auth.as_deref(), Some("Bearer t0ken")); + assert_eq!(header_of(&there[0], "authorization"), None); + assert_eq!(header_of(&there[0], "cookie"), None); + // What is not a secret travels, and the page says where it was sent from. + assert_eq!(header_of(&there[0], "x-trace").as_deref(), Some("1")); + assert_eq!(header_of(&there[0], "referer"), Some(login)); + // A `Cookie` typed wins over the jar's for the host it is typed for, and stays there too. + let cookie = header_of(&here[1], "cookie"); + assert_eq!(cookie.as_deref(), Some("typed=1")); + assert_eq!(header_of(&there[1], "cookie"), None); } #[test] -fn a_send_under_way_is_cancelled_by_its_id() { +fn the_delay_is_the_whole_chain_s() { let session = Session::open(); - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let port = listener.local_addr().unwrap().port(); - // Accepts, then answers nothing until the test is over. - let silent = thread::spawn(move || listener.accept().map(|(stream, _)| stream)); - - let sending = session.runtime.spawn(send_http_request( - Arc::clone(&session.engine), - request(&format!("http://127.0.0.1:{port}/slow")), - )); - // Polled from the test's own thread: the send is under way once there is one to cancel. - while !session.call(|e| cancel_http_send(e, "tab-1")).unwrap() { + // Each hop answers after 400 ms: within 600 ms a hop, not within 600 ms in all. + let (port, _seen) = serve(2, |seen, _| { + thread::sleep(Duration::from_millis(400)); + if seen.head.starts_with("GET /first ") { + response("302 Found", &[("Location", "/second")], b"") + } else { + response("200 OK", &[], b"late") + } + }); + let mut slow = request(&format!("http://127.0.0.1:{port}/first")); + slow.document.transport.timeout_ms = Some(600); + + assert_eq!(code(send(&session, slow)), ErrorCode::HttpTimeout); +} + +/// A send under way: its answer once it ends. +fn sending( + session: &Session, + request: SendRequest, +) -> tokio::task::JoinHandle> { + let sending = send_http_request(Arc::clone(&session.engine), request); + session.runtime.spawn(sending) +} + +/// Polled from the test's own thread: the send is under way once there is one to cancel. +fn cancel(session: &Session, id: &str) { + while !session.call(|e| cancel_http_send(e, id)).unwrap() { thread::sleep(Duration::from_millis(10)); } - let cancelled = session.runtime.block_on(sending).unwrap(); +} + +#[test] +fn a_send_under_way_is_cancelled_by_its_id_and_leaves_no_history() { + let session = Session::open(); + let slow = request(&format!("http://127.0.0.1:{}/slow", silent(1))); - assert_eq!(cancelled.unwrap_err().code, ErrorCode::HttpCancelled); + let under_way = sending(&session, slow); + cancel(&session, "tab-1"); + let cancelled = session.runtime.block_on(under_way).unwrap(); + + assert_eq!(code(cancelled), ErrorCode::HttpCancelled); + assert!(history(&session).is_empty()); assert!(!session.call(|e| cancel_http_send(e, "tab-1")).unwrap()); - drop(silent); } #[test] -fn every_send_that_left_is_recorded_masked_and_the_history_clears() { - use engine::http::model::KeyPlace; - use engine::http::{ - clear_http_history, count_http_history, http_history, http_history_draft, - http_history_entry, - }; +fn a_cancel_ends_a_chain_of_redirects_on_the_way() { + let session = Session::open(); + let (port, seen) = serve(2, |seen, _| { + if seen.head.starts_with("GET /first ") { + response("302 Found", &[("Location", "/second")], b"") + } else { + thread::sleep(Duration::from_secs(5)); + Vec::new() + } + }); + + let under_way = sending(&session, request(&format!("http://127.0.0.1:{port}/first"))); + seen.recv().unwrap(); + cancel(&session, "tab-1"); + let cancelled = session.runtime.block_on(under_way).unwrap(); + + assert_eq!(code(cancelled), ErrorCode::HttpCancelled); +} + +#[test] +fn a_second_send_under_one_id_replaces_the_first() { + let session = Session::open(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let slow = listener.local_addr().unwrap().port(); + let (asked, reached) = mpsc::channel(); + thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + asked.send(read_request(&mut stream)).unwrap(); + thread::sleep(Duration::from_secs(5)); + }); + let (port, _seen) = serve(1, |_, _| response("200 OK", &[], b"second")); + let first = sending(&session, request(&format!("http://127.0.0.1:{slow}/"))); + reached.recv().unwrap(); + let second = fetched(&session, port, "/"); + let first = session.runtime.block_on(first).unwrap(); + + assert_eq!(second.body, "second"); + assert_eq!(code(first), ErrorCode::HttpCancelled); +} + +#[test] +fn a_send_that_replaced_another_is_still_cancelled_by_its_id() { + let session = Session::open(); + let slow = request(&format!("http://127.0.0.1:{}/slow", silent(2))); + + let first = sending(&session, slow.clone()); + thread::sleep(Duration::from_millis(200)); + let second = sending(&session, slow); + let first = session.runtime.block_on(first).unwrap(); + cancel(&session, "tab-1"); + let second = session.runtime.block_on(second).unwrap(); + + assert_eq!(code(first), ErrorCode::HttpCancelled); + assert_eq!(code(second), ErrorCode::HttpCancelled); +} + +#[test] +fn a_send_that_left_is_recorded_masked_whether_or_not_it_was_answered() { let session = Session::open(); let (port, _seen) = serve(1, |_, _| { response("200 OK", &[("Content-Type", "text/plain")], b"pong") @@ -891,173 +1296,128 @@ fn every_send_that_left_is_recorded_masked_and_the_history_clears() { value: "s3cret".to_string(), place: KeyPlace::Query, }; - keyed.document.headers = vec![KeyValue { - key: "Authorization".to_string(), - value: "Bearer t0ken".to_string(), - ..KeyValue::default() - }]; - session.wait(|e| send_http_request(e, keyed)).unwrap(); + keyed.document.headers = vec![row("Authorization", "Bearer t0ken")]; + let refused = request(&format!("http://127.0.0.1:{}/", closed_port())); - let closed = TcpListener::bind("127.0.0.1:0").unwrap(); - let port = closed.local_addr().unwrap().port(); - drop(closed); - let refused = - session.wait(|e| send_http_request(e, request(&format!("http://127.0.0.1:{port}/")))); - assert!(refused.is_err()); - let never_left = session.wait(|e| send_http_request(e, request("{{baseUrl}}/x"))); - assert!(never_left.is_err()); - - let days = session.call(|e| http_history(e, 0)).unwrap(); - assert_eq!(days.len(), 1); - let items = &days[0].items; - assert_eq!(items.len(), 2); - assert_eq!( - (items[0].status, items[0].summary.failure), - (None, Some(ErrorCode::HttpRefused)) - ); - assert_eq!(items[1].status, Some(200)); - assert_eq!(items[1].summary.name, "Ping"); - assert!( - items[1] - .summary - .url - .ends_with("/ping?key=••••••••&key=••••••••") - ); + send(&session, keyed).unwrap(); + send(&session, refused).unwrap_err(); + let items = history(&session); + assert_eq!(items.len(), 2); + let failed = (items[0].status, items[0].summary.failure); + assert_eq!(failed, (None, Some(ErrorCode::HttpRefused))); + let answered = (items[1].status, items[1].summary.name.as_str()); + assert_eq!(answered, (Some(200), "Ping")); + let url = &items[1].summary.url; + assert!(url.ends_with("/ping?key=••••••••&key=••••••••"), "{url}"); let entry = session - .call(|e| http_history_entry(e, &items[1].id.clone())) + .call(|e| http_history_entry(e, &items[1].id)) .unwrap(); - let response = entry.record.response.unwrap(); - assert_eq!(response.body, "pong"); - assert!( - entry - .record - .exchange - .headers - .iter() - .any(|header| header.key == "Authorization" && header.value == "Bearer ••••••••") - ); + assert_eq!(entry.record.response.unwrap().body, "pong"); + let shown = row("Authorization", "Bearer ••••••••"); + assert!(entry.record.exchange.headers.contains(&shown)); +} + +#[test] +fn a_send_is_reopened_as_a_draft_without_what_was_masked() { + let session = Session::open(); + let (port, _seen) = serve(1, |_, _| response("200 OK", &[], b"")); + let mut sent = request(&format!("http://127.0.0.1:{port}/ping")); + sent.document.headers = vec![row("Authorization", "Bearer t0ken")]; + send(&session, sent).unwrap(); + + let id = history(&session)[0].id.clone(); + let draft = session.call(|e| http_history_draft(e, &id)).unwrap(); - let draft = session - .call(|e| http_history_draft(e, &items[1].id.clone())) - .unwrap(); assert!(draft.document.url.ends_with("/ping")); assert!(draft.document.headers.is_empty()); +} + +#[test] +fn the_history_is_counted_then_cleared() { + let session = Session::open(); + let (port, _seen) = serve(2, |_, _| response("200 OK", &[], b"")); + fetched(&session, port, "/a"); + fetched(&session, port, "/b"); assert_eq!(session.call(count_http_history).unwrap(), 2); assert_eq!(session.call(clear_http_history).unwrap(), 2); - assert!(session.call(|e| http_history(e, 0)).unwrap().is_empty()); + assert!(history(&session).is_empty()); } -/// « Vider l'historique » was the only way to remove the one send made with the wrong token, -/// and « Rouvrir » opened a stranger with no tie to the request the send came from. +/// Newest first, each URL in its two parts: the host, and what tells the two apart. #[test] -fn one_send_is_removed_and_put_back_and_goes_back_onto_the_request_it_came_from() { - use engine::http::model::HttpRequestDraft; - use engine::http::{ - create_http_request, delete_http_history_entry, delete_http_item, http_history, - http_history_onto_request, restore_http_history_entry, - }; - +fn one_send_is_removed_from_the_history_and_put_back_where_it_was() { let session = Session::open(); let (port, _seen) = serve(2, |_, _| response("200 OK", &[], b"ok")); - let api = session.call(|e| create_http_collection(e, "API")).unwrap(); - let token = KeyValue { - key: "Authorization".to_string(), - value: "Bearer t0ken".to_string(), - ..KeyValue::default() - }; - let held = session - .call(|e| { - create_http_request( - e, - &HttpRequestDraft { - collection_id: api.id.clone(), - folder_id: None, - name: "ma req".to_string(), - kind: RequestKind::Http, - method: HttpMethod::Get, - document: RequestDocument { - url: format!("http://127.0.0.1:{port}/now"), - headers: vec![token.clone()], - ..RequestDocument::default() - }, - }, - ) - }) - .unwrap(); - for path in ["first", "second?page=2"] { - let mut sent = request(&format!("http://127.0.0.1:{port}/{path}")); - sent.collection_id = Some(api.id.clone()); - sent.request_id = Some(held.id.clone()); - sent.document.headers = vec![token.clone()]; - session.wait(|e| send_http_request(e, sent)).unwrap(); - } - let listed = || { - let days = session.call(|e| http_history(e, 0)).unwrap(); - days.into_iter() - .flat_map(|day| day.items) - .collect::>() - }; - - // Newest first, each URL in its two parts: the host, and what tells the two apart. - let before = listed(); - assert_eq!( - before - .iter() - .map(|item| (item.url_head.clone(), item.url_tail.as_str())) - .collect::>(), - vec![ - (format!("127.0.0.1:{port}"), "/second?page=2"), - (format!("127.0.0.1:{port}"), "/first"), - ] - ); + fetched(&session, port, "/first"); + fetched(&session, port, "/second?page=2"); + let before = history(&session); + let host = format!("127.0.0.1:{port}"); + let parts = before + .iter() + .map(|item| (item.url_head.as_str(), item.url_tail.as_str())); + assert!(parts.eq([(host.as_str(), "/second?page=2"), (host.as_str(), "/first")])); let removed = session - .call(|e| delete_http_history_entry(e, &before[0].id.clone())) + .call(|e| delete_http_history_entry(e, &before[0].id)) .unwrap(); - assert_eq!(listed(), before[1..]); + assert_eq!(history(&session), before[1..]); + session .call(|e| restore_http_history_entry(e, &removed)) .unwrap(); - assert_eq!(listed(), before); - - // Back onto its request: the send's URL, and the request's own secret where the record - // holds a mask. - let onto = session - .call(|e| http_history_onto_request(e, &before[1].id.clone())) - .unwrap() - .unwrap(); - assert_eq!(onto.name, "ma req"); - assert_eq!(onto.document.url, format!("http://127.0.0.1:{port}/first")); - assert_eq!(onto.document.headers, vec![token]); + assert_eq!(history(&session), before); +} - // The request gone, there is nothing to go back onto: a draft it is. - session - .call(|e| { - delete_http_item( - e, - &HttpItem { - kind: HttpItemKind::Request, - id: held.id.clone(), - }, - ) - }) - .unwrap(); - assert_eq!( +/// The send's URL, and the request's own secret where the record holds a mask. +#[test] +fn a_send_goes_back_onto_the_request_it_came_from_until_it_is_deleted() { + let session = Session::open(); + let (port, _seen) = serve(1, |_, _| response("200 OK", &[], b"ok")); + let api = collection_with(&session, ContainerSettings::default()); + let token = row("Authorization", "Bearer t0ken"); + let draft = HttpRequestDraft { + collection_id: api.clone(), + folder_id: None, + name: "ma req".to_string(), + kind: RequestKind::Http, + method: HttpMethod::Get, + document: RequestDocument { + url: format!("http://127.0.0.1:{port}/now"), + headers: vec![token.clone()], + ..RequestDocument::default() + }, + }; + let held = session.call(|e| create_http_request(e, &draft)).unwrap(); + let mut sent = request(&format!("http://127.0.0.1:{port}/first")); + sent.collection_id = Some(api); + sent.request_id = Some(held.id.clone()); + sent.document.headers = vec![token.clone()]; + send(&session, sent).unwrap(); + let entry = history(&session)[0].id.clone(); + let onto = || { session - .call(|e| http_history_onto_request(e, &before[1].id.clone())) - .unwrap(), - None - ); + .call(|e| http_history_onto_request(e, &entry)) + .unwrap() + }; + + let back = onto().unwrap(); + assert_eq!(back.name, "ma req"); + let first = format!("http://127.0.0.1:{port}/first"); + assert_eq!(back.document.url, first); + assert_eq!(back.document.headers, [token]); + + let item = HttpItem { + kind: HttpItemKind::Request, + id: held.id, + }; + session.call(|e| delete_http_item(e, &item)).unwrap(); + assert_eq!(onto(), None); } #[test] fn a_graphql_request_is_posted_as_json_and_its_errors_read_apart_from_its_data() { - use engine::http::graphql::GraphqlDocument; - use engine::http::graphql::QueryFault; - use engine::http::{add_graphql_variables, describe_graphql}; - let session = Session::open(); let (port, seen) = serve(1, |_, _| { response( @@ -1073,9 +1433,8 @@ fn a_graphql_request_is_posted_as_json_and_its_errors_read_apart_from_its_data() operation_name: Some("Me".to_string()), ..GraphqlDocument::default() }; - let document = sent.document.graphql.clone(); - let answer = session.wait(|e| send_http_request(e, sent)).unwrap(); + let answer = send(&session, sent).unwrap(); let read = answer.graphql.unwrap(); assert_eq!(read.data.as_deref(), Some("{\n \"me\": null\n}")); @@ -1083,34 +1442,34 @@ fn a_graphql_request_is_posted_as_json_and_its_errors_read_apart_from_its_data() assert_eq!(read.errors[0].path.as_deref(), Some("me")); let seen = seen.recv().unwrap(); assert!(seen.head.starts_with("POST /graphql HTTP/1.1\r\n")); - assert!( - String::from_utf8(seen.body) - .unwrap() - .contains("\"operationName\":\"Me\"") - ); + let body = String::from_utf8(seen.body).unwrap(); + assert!(body.contains("\"operationName\":\"Me\""), "{body}"); +} - let described = describe_graphql(&document).unwrap(); - assert_eq!(described.operations, ["Me", "Other"]); - assert_eq!(described.query_problem, None); +#[test] +fn an_answer_is_read_as_graphql_for_a_graphql_request_alone() { + let session = Session::open(); + let (port, _seen) = serve(1, |_, _| response("200 OK", &[], b"{\"data\":{\"me\":1}}")); + + assert_eq!(fetched(&session, port, "/").graphql, None); +} - // What the editor says before a send: a brace left open, a variable without a value. +/// What the editor says before a send. +#[test] +fn a_graphql_document_is_described_and_its_missing_variables_added() { let open = GraphqlDocument { query: "query Country($code: ID!) { country(code: $code) { name }".to_string(), ..GraphqlDocument::default() }; + let described = describe_graphql(&open).unwrap(); + let added = add_graphql_variables(&open).unwrap(); + let problem = described.query_problem.unwrap(); - assert_eq!( - (problem.fault, problem.line, problem.column), - (QueryFault::UnclosedBrace, 1, 27) - ); + let at = (problem.fault, problem.line, problem.column); + assert_eq!(at, (QueryFault::UnclosedBrace, 1, 27)); assert_eq!(described.missing, ["code"]); - assert_eq!( - add_graphql_variables(&open).unwrap(), - "{ - \"code\": null -}" - ); + assert_eq!(added, "{\n \"code\": null\n}"); } /// Headers are read lossily: an expiry of any letters is no date, and the send is answered. @@ -1121,300 +1480,120 @@ fn a_cookie_whose_expiry_is_accented_letters_lives_the_session() { response("200 OK", &[("Set-Cookie", "a=1; Expires=éé")], b"") }); - let answer = - session.wait(|e| send_http_request(e, request(&format!("http://127.0.0.1:{port}/")))); - - assert_eq!(answer.unwrap().status, 200); + assert_eq!(fetched(&session, port, "/").status, 200); + assert_eq!(jar(&session), ["a"]); } +/// Two of one path length go back in the order they were set (#705). #[test] -fn an_answer_fills_the_jar_the_next_request_carries_it_and_the_manager_empties_it() { - use engine::http::{ - clear_http_cookies, count_http_cookies, delete_http_cookie, delete_http_cookie_domain, - http_cookies, - }; - +fn an_answer_fills_the_jar_and_the_next_request_carries_it() { let session = Session::open(); - let (port, seen) = serve(3, |seen, _| { + let (port, seen) = serve(2, |seen, _| { if seen.head.starts_with("GET /login ") { - response( - "200 OK", - &[ - ("Set-Cookie", "session=abc; Path=/; HttpOnly"), - ("Set-Cookie", "theme=dark; Path=/"), - ], - b"", - ) + let set = [ + ("Set-Cookie", "session=abc; Path=/; HttpOnly"), + ("Set-Cookie", "theme=dark; Path=/"), + ]; + response("200 OK", &set, b"") } else { response("200 OK", &[], b"") } }); - let base = format!("http://127.0.0.1:{port}"); - session - .wait(|e| send_http_request(e, request(&format!("{base}/login")))) - .unwrap(); - session - .wait(|e| send_http_request(e, request(&format!("{base}/me")))) - .unwrap(); - let mut alone = request(&format!("{base}/me")); - alone.document.transport.use_cookies = Some(false); - session.wait(|e| send_http_request(e, alone)).unwrap(); - - let heads: Vec = seen.iter().take(3).map(|seen| seen.head).collect(); - assert!(!heads[0].to_ascii_lowercase().contains("cookie:")); - let carried = heads[1].to_ascii_lowercase(); - // Two of one path length go back in the order they were set (#705). - assert!( - carried.contains("cookie: session=abc; theme=dark\r\n"), - "{carried}" - ); - assert!(!heads[2].to_ascii_lowercase().contains("cookie:")); + fetched(&session, port, "/login"); + let answer = fetched(&session, port, "/me"); - let domains = session.call(http_cookies).unwrap(); - assert_eq!(domains.len(), 1); - assert_eq!(domains[0].domain, "127.0.0.1"); - assert_eq!(domains[0].cookies.len(), 2); - let id = domains[0].cookies[0].id.clone(); - assert_eq!(session.call(|e| delete_http_cookie(e, &id)).unwrap(), 1); - assert_eq!(session.call(count_http_cookies).unwrap(), 1); - assert_eq!( - session - .call(|e| delete_http_cookie_domain(e, "127.0.0.1")) - .unwrap(), - 1 - ); - assert_eq!(session.call(clear_http_cookies).unwrap(), 0); + assert_eq!(header_of(&seen.recv().unwrap(), "cookie"), None); + let carried = header_of(&seen.recv().unwrap(), "cookie").unwrap(); + assert_eq!(carried, "session=abc; theme=dark"); + assert!(answer.exchange.headers.contains(&row("Cookie", &carried))); + assert_eq!(jar(&session), ["session", "theme"]); } -/// `/cookies/set?session=abc123` answers a 302 that sets the cookie and leads to a page that -/// echoes what it received: it received none, and the jar stayed empty. Nearly every login. #[test] -fn a_cookie_set_on_a_redirect_is_sent_to_the_hop_that_follows_and_kept_in_the_jar() { - use engine::http::{clear_http_cookies, count_http_cookies, http_cookies}; - +fn a_request_without_cookies_sends_none_and_keeps_none_at_any_hop() { let session = Session::open(); - let (port, seen) = serve(4, |seen, _| { - if seen.head.starts_with("GET /cookies/set ") { - response( - "302 Found", - &[ - ("Location", "/cookies"), - ("Set-Cookie", "session=abc123; Path=/"), - ], - b"", - ) + let (port, seen) = serve(2, |seen, _| { + let set = ("Set-Cookie", "session=abc; Path=/"); + if seen.head.starts_with("GET /first ") { + response("302 Found", &[("Location", "/second"), set], b"") } else { - let sent = header_of(seen, "cookie").unwrap_or_default(); - response( - "200 OK", - &[ - ("Content-Type", "text/plain"), - ("Set-Cookie", "seen=1; Path=/"), - ], - sent.as_bytes(), - ) + response("200 OK", &[set], b"") } }); - let set = format!("http://127.0.0.1:{port}/cookies/set"); - let landing = format!("http://127.0.0.1:{port}/cookies"); - - let answer = session - .wait(|e| send_http_request(e, request(&set))) - .unwrap(); - - assert_eq!(answer.body, "session=abc123"); - assert_eq!(answer.url, landing); - assert_eq!(header_of(&seen.recv().unwrap(), "cookie"), None); - assert_eq!( - header_of(&seen.recv().unwrap(), "cookie").as_deref(), - Some("session=abc123") - ); - // The answer lists what was set along the chain, the redirect's first, with who set it. - assert_eq!( - answer - .cookies - .iter() - .map(|cookie| (cookie.name.as_str(), cookie.from.clone())) - .collect::>(), - vec![("session", Some(set.clone())), ("seen", None)] - ); - assert_eq!(answer.redirects.len(), 1); - let redirect = &answer.redirects[0]; - assert_eq!( - ( - redirect.status, - redirect.from.as_str(), - redirect.url.as_str() - ), - (302, set.as_str(), landing.as_str()) - ); - assert_eq!(redirect.cookies.len(), 1); - assert_eq!(redirect.cookies[0].name, "session"); + let mut alone = request(&format!("http://127.0.0.1:{port}/first")); + alone.document.transport.use_cookies = Some(false); - let domains = session.call(http_cookies).unwrap(); - let mut kept: Vec<&str> = domains[0] - .cookies - .iter() - .map(|stored| stored.cookie.name.as_str()) - .collect(); - kept.sort_unstable(); - assert_eq!(kept, ["seen", "session"]); + let answer = send(&session, alone).unwrap(); - // « Envoyer et garder les cookies : Non »: none sent at any hop, none kept. - assert_eq!(session.call(clear_http_cookies).unwrap(), 2); - let mut alone = request(&set); - alone.document.transport.use_cookies = Some(false); - let answer = session.wait(|e| send_http_request(e, alone)).unwrap(); - assert_eq!(answer.body, ""); - assert_eq!(session.call(count_http_cookies).unwrap(), 0); + for _ in 0..2 { + assert_eq!(header_of(&seen.recv().unwrap(), "cookie"), None); + } + assert!(jar(&session).is_empty()); // What the answers set is still read, as it always was. assert_eq!(answer.cookies.len(), 2); } +/// Nearly every login: a 302 sets the cookie and leads to a page that reads it. #[test] -fn a_redirect_to_another_host_carries_neither_a_cookie_nor_the_authorization() { - let row = |key: &str, value: &str| KeyValue { - key: key.to_string(), - value: value.to_string(), - ..KeyValue::default() - }; - let session = Session::open(); - let (elsewhere, landed) = serve(2, |_, _| response("200 OK", &[], b"there")); - let (port, seen) = serve(2, move |_, _| { - response( - "302 Found", - &[ - ("Location", &format!("http://localhost:{elsewhere}/landing")), - ("Set-Cookie", "session=abc; Path=/"), - ], - b"", - ) - }); - let login = format!("http://127.0.0.1:{port}/login"); - - let mut sent = request(&login); - sent.document.headers = vec![row("Authorization", "Bearer t0ken"), row("X-Trace", "1")]; - let answer = session.wait(|e| send_http_request(e, sent)).unwrap(); - - assert_eq!(answer.body, "there"); - assert_eq!( - header_of(&seen.recv().unwrap(), "authorization").as_deref(), - Some("Bearer t0ken") - ); - let there = landed.recv().unwrap(); - assert_eq!(header_of(&there, "authorization"), None); - assert_eq!(header_of(&there, "cookie"), None); - // What is not a secret travels, and the page says where it was sent from. - assert_eq!(header_of(&there, "x-trace").as_deref(), Some("1")); - assert_eq!(header_of(&there, "referer"), Some(login.clone())); - - // A `Cookie` typed wins over the jar's for the host it is typed for, and stays there too. - let mut typed = request(&login); - typed.document.headers = vec![row("Cookie", "typed=1")]; - session.wait(|e| send_http_request(e, typed)).unwrap(); - assert_eq!( - header_of(&seen.recv().unwrap(), "cookie").as_deref(), - Some("typed=1") - ); - assert_eq!(header_of(&landed.recv().unwrap(), "cookie"), None); -} - -#[test] -fn a_303_after_a_post_becomes_a_get_without_its_body_and_a_307_sends_it_again() { +fn a_cookie_set_on_a_redirect_is_sent_to_the_hop_that_follows_and_kept_in_the_jar() { let session = Session::open(); - let (port, seen) = serve(4, |seen, _| { - if seen.head.starts_with("POST /see-other ") { - response("303 See Other", &[("Location", "done")], b"") - } else if seen.head.starts_with("POST /temporary ") { - response("307 Temporary Redirect", &[("Location", "/kept")], b"") + let (port, _seen) = serve(2, |seen, _| { + if seen.head.starts_with("GET /cookies/set ") { + let set = ("Set-Cookie", "session=abc123; Path=/"); + response("302 Found", &[("Location", "/cookies"), set], b"") } else { - response("200 OK", &[], b"ok") + let carried = header_of(seen, "cookie").unwrap_or_default(); + let set = [("Set-Cookie", "seen=1; Path=/")]; + response("200 OK", &set, carried.as_bytes()) } }); - let posting = |path: &str| { - let mut sent = request(&format!("http://127.0.0.1:{port}/{path}")); - sent.method = HttpMethod::Post; - sent.document.body = RequestBody::Json { - text: "{\"a\":1}".to_string(), - }; - session.wait(|e| send_http_request(e, sent)).unwrap() - }; - let answer = posting("see-other"); - assert_eq!(answer.url, format!("http://127.0.0.1:{port}/done")); - assert_eq!(seen.recv().unwrap().body, b"{\"a\":1}"); - let after = seen.recv().unwrap(); - assert!(after.head.starts_with("GET /done "), "{}", after.head); - assert!(after.body.is_empty()); - assert_eq!(header_of(&after, "content-type"), None); + let answer = fetched(&session, port, "/cookies/set"); - posting("temporary"); - seen.recv().unwrap(); - let after = seen.recv().unwrap(); - assert!(after.head.starts_with("POST /kept "), "{}", after.head); - assert_eq!(after.body, b"{\"a\":1}"); - assert_eq!( - header_of(&after, "content-type").as_deref(), - Some("application/json") - ); + assert_eq!(answer.body, "session=abc123"); + // The answer lists what was set along the chain, the redirect's first, with who set it. + let set = format!("http://127.0.0.1:{port}/cookies/set"); + let listed = answer + .cookies + .iter() + .map(|cookie| (cookie.name.as_str(), cookie.from.clone())); + assert!(listed.eq([("session", Some(set)), ("seen", None)])); + assert_eq!(answer.redirects[0].cookies[0].name, "session"); + assert_eq!(jar(&session), ["seen", "session"]); } +/// As a browser keeps the cookie of a login whose landing page did not load. #[test] -fn the_delay_is_the_whole_chain_s_and_a_cancel_ends_it_on_the_way() { +fn a_cookie_set_on_a_redirect_is_kept_though_the_chain_failed() { let session = Session::open(); - // Each hop answers after 400 ms: within 600 ms a hop, not within 600 ms in all. - let (port, _seen) = serve(2, |seen, _| { - thread::sleep(Duration::from_millis(400)); - if seen.head.starts_with("GET /first ") { - response("302 Found", &[("Location", "/second")], b"") - } else { - response("200 OK", &[], b"late") - } + let closed = closed_port(); + let (port, _seen) = serve(1, move |_, _| { + let to = format!("http://127.0.0.1:{closed}/"); + let set = ("Set-Cookie", "session=abc; Path=/"); + response("302 Found", &[("Location", to.as_str()), set], b"") }); - let mut slow = request(&format!("http://127.0.0.1:{port}/first")); - slow.document.transport.timeout_ms = Some(600); - assert_eq!( - code(session.wait(|e| send_http_request(e, slow))), - ErrorCode::HttpTimeout - ); - // Redirected at once, then never answered: cancelled once the first hop is behind. - let (port, seen) = serve(2, |seen, _| { - if seen.head.starts_with("GET /first ") { - response("302 Found", &[("Location", "/second")], b"") - } else { - thread::sleep(Duration::from_secs(5)); - Vec::new() - } - }); - let sending = session.runtime.spawn(send_http_request( - Arc::clone(&session.engine), - request(&format!("http://127.0.0.1:{port}/first")), - )); - seen.recv().unwrap(); - while !session.call(|e| cancel_http_send(e, "tab-1")).unwrap() { - thread::sleep(Duration::from_millis(10)); - } - let cancelled = session.runtime.block_on(sending).unwrap(); - assert_eq!(cancelled.unwrap_err().code, ErrorCode::HttpCancelled); + let failed = send(&session, request(&format!("http://127.0.0.1:{port}/login"))); + + assert_eq!(code(failed), ErrorCode::HttpRefused); + assert_eq!(jar(&session), ["session"]); } #[test] -fn a_request_set_not_to_follow_redirects_answers_the_redirect_itself() { +fn the_jar_s_manager_removes_a_cookie_then_a_domain() { let session = Session::open(); - let (port, _seen) = serve(1, |_, port| { - response( - "302 Found", - &[("Location", &format!("http://127.0.0.1:{port}/new"))], - b"", - ) + let (port, _seen) = serve(1, |_, _| { + let set = ["a=1", "b=2", "c=3"].map(|cookie| ("Set-Cookie", cookie)); + response("200 OK", &set, b"") }); - let mut sent = request(&format!("http://127.0.0.1:{port}/old")); - sent.document.transport.follow_redirects = Some(false); - - let answer = session.wait(|e| send_http_request(e, sent)).unwrap(); + fetched(&session, port, "/"); + let domains = session.call(http_cookies).unwrap(); + let id = domains[0].cookies[0].id.clone(); - assert_eq!(answer.status, 302); - assert!(answer.redirects.is_empty()); + assert_eq!(session.call(|e| delete_http_cookie(e, &id)).unwrap(), 1); + assert_eq!(session.call(count_http_cookies).unwrap(), 2); + let removed = session.call(|e| delete_http_cookie_domain(e, "127.0.0.1")); + assert_eq!(removed.unwrap(), 2); + assert_eq!(session.call(clear_http_cookies).unwrap(), 0); } From 6b3b95e3b5ce7720446f1cff81381f84044fc458 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 07:37:02 +0100 Subject: [PATCH 46/95] Drawings: a text emptied is saved and undone like a deletion (#1793) Co-authored-by: Claude Opus 5.5 --- crates/drawing/src/edit.rs | 5 ++--- crates/drawing/src/edit/tests.rs | 20 ++++++++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/crates/drawing/src/edit.rs b/crates/drawing/src/edit.rs index c18d58d56..18ac5dbca 100644 --- a/crates/drawing/src/edit.rs +++ b/crates/drawing/src/edit.rs @@ -828,7 +828,8 @@ impl Editor { self.revision += 1; } - /// A text left empty was a click: it goes, and the history never knew it. + /// A text left empty goes. Just clicked, the history never knew it; typed before, it is a + /// deletion like another. pub fn leave_text(&mut self) { let Some(index) = self.editing.take() else { return; @@ -841,8 +842,6 @@ impl Editor { { self.drawing.objects.remove(index); self.selected.clear(); - self.revision += 1; - return; } self.keep(); } diff --git a/crates/drawing/src/edit/tests.rs b/crates/drawing/src/edit/tests.rs index 62155d0ba..bae19af09 100644 --- a/crates/drawing/src/edit/tests.rs +++ b/crates/drawing/src/edit/tests.rs @@ -181,6 +181,26 @@ fn a_text_is_typed_where_clicked_and_left_empty_it_goes() { assert!(!editor.can_undo()); } +#[test] +fn a_text_emptied_is_saved_and_undone_like_a_deletion() { + let mut editor = editor(); + editor.set_tool(Tool::Text); + editor.press(at(10.0, 20.0), false); + editor.set_text("words"); + editor.leave_text(); + editor.take_unsaved(); + let inside = object(&editor, 0).centre(); + drag(&mut editor, inside, inside); + editor.set_text(" "); + + editor.leave_text(); + assert_eq!(editor.shapes(), 0); + assert!(editor.take_unsaved()); + + editor.undo(); + assert_eq!(object(&editor, 0).text(), Some("words")); +} + #[test] fn a_text_grows_with_its_lines_and_a_second_click_types_in_it_again() { let mut editor = editor(); From 51a1f176033da016d4d1b9147186c92da5d4fd70 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 07:37:12 +0100 Subject: [PATCH 47/95] Notes: a marker typed in its own list no longer undoes the list (#1789) Co-authored-by: Claude Opus 5.5 --- crates/richtext/src/edit.rs | 2 +- crates/richtext/src/rules.rs | 17 ++++++++++++++++- crates/richtext/src/rules/tests.rs | 27 +++++++++++++++++++++++++++ 3 files changed, 44 insertions(+), 2 deletions(-) diff --git a/crates/richtext/src/edit.rs b/crates/richtext/src/edit.rs index 43957d550..b377a1892 100644 --- a/crates/richtext/src/edit.rs +++ b/crates/richtext/src/edit.rs @@ -533,7 +533,7 @@ pub fn split(document: &mut Document, selection: &Selection) -> Selection { caret(next_path, 0) } -fn in_quote(document: &Document, path: &[usize]) -> bool { +pub(crate) fn in_quote(document: &Document, path: &[usize]) -> bool { path.len() >= 2 && matches!(document.blocks.get(path[0]), Some(Block::Quote(_))) } diff --git a/crates/richtext/src/rules.rs b/crates/richtext/src/rules.rs index c2771b211..449cfa8bb 100644 --- a/crates/richtext/src/rules.rs +++ b/crates/richtext/src/rules.rs @@ -124,9 +124,15 @@ fn apply_block( edit::set_heading(document, &cleared, Some(level)); cleared } + // Typed again in its own quote or list, a marker is only taken out. + BlockRule::Quote if edit::in_quote(document, &cleared.head.path) => cleared, BlockRule::Quote => edit::toggle_quote(document, &cleared), BlockRule::List(kind, checked) => { - let listed = edit::toggle_list(document, &cleared, kind); + let listed = if in_list(document, &cleared, kind) { + cleared + } else { + edit::toggle_list(document, &cleared, kind) + }; if checked && let Some((list, item, _)) = tree::innermost_item(document, &listed.head.path) { @@ -139,6 +145,15 @@ fn apply_block( } } +fn in_list(document: &Document, selection: &Selection, kind: ListKind) -> bool { + let list = tree::innermost_item(document, &selection.head.path); + let current = list.and_then(|(list, _, _)| match tree::block(document, &list) { + Some(Block::List { kind, .. }) => Some(std::mem::discriminant(kind)), + _ => None, + }); + current == Some(std::mem::discriminant(&kind)) +} + /// A mark closed at the end of `text`: the mark, where its opening delimiter starts, the inner /// range, and the closing delimiter's length — all in `char`s. fn mark_rule(text: &str) -> Option<(Mark, usize, std::ops::Range, usize)> { diff --git a/crates/richtext/src/rules/tests.rs b/crates/richtext/src/rules/tests.rs index ae013c2ac..d39627a70 100644 --- a/crates/richtext/src/rules/tests.rs +++ b/crates/richtext/src/rules/tests.rs @@ -54,3 +54,30 @@ fn marks_close_at_the_caret_and_spaced_emphasis_stays_as_typed() { "no italic inside a word" ); } + +/// Enter has opened the next item already: its marker typed by habit is not a second one. +#[test] +fn a_marker_typed_in_its_own_list_or_quote_is_only_taken_out() { + for (markdown, marker, after) in [ + ("- a\n- b", "- ", "- a\n- b\n- c"), + ("1. a\n2. b", "3. ", "1. a\n2. b\n3. c"), + ("- [ ] a", "[ ] ", "- [ ] a\n- [ ] c"), + ("- [ ] a", "[x] ", "- [ ] a\n- [x] c"), + ("> a", "> ", "> a\n>\n> c"), + ("- a", "[ ] ", "- [ ] a\n- [ ] c"), + ("- a", "1. ", "1. a\n2. c"), + ] { + let mut document = read(markdown); + let path = tree::leaves(&document).pop().unwrap(); + let end = Selection::caret(Position { path, offset: 1 }); + let mut selection = edit::split(&mut document, &end); + for glyph in format!("{marker}c").chars() { + let glyph = glyph.to_string(); + selection = edit::insert_text(&mut document, &selection, &glyph, &Marks::default()); + if let Some(applied) = after_typing(&mut document, &selection) { + selection = applied.selection; + } + } + assert_eq!(write(&document), after, "{marker:?} in {markdown:?}"); + } +} From 29ff7ef46618406b399c4d2cc38d1dfb9ab68dbf Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 07:37:22 +0100 Subject: [PATCH 48/95] Code editor: lines moved in a CRLF text keep their endings (#1779) Co-authored-by: Claude Opus 5.5 --- crates/text/src/buffer.rs | 75 +++++++++++++++------------------ crates/text/src/buffer/tests.rs | 28 ++++++++++++ crates/text/src/indent.rs | 8 +++- 3 files changed, 68 insertions(+), 43 deletions(-) diff --git a/crates/text/src/buffer.rs b/crates/text/src/buffer.rs index 9a890341a..ed38e678c 100644 --- a/crates/text/src/buffer.rs +++ b/crates/text/src/buffer.rs @@ -195,7 +195,8 @@ impl Buffer { Some(self.apply(&edit)) } - /// Alt+↑ / Alt+↓: the selected lines swap with the one above or below. + /// Alt+↑ / Alt+↓: the selected lines swap with the one above or below. The line ending + /// between them stays between them, whichever it is. pub fn move_lines(&mut self, direction: Direction) -> Option { let range = self.selection.range(); let first = self.line_of(range.start); @@ -203,44 +204,31 @@ impl Buffer { if range.end > range.start && range.end == self.line_start(last) && last > first { last -= 1; } - let lines: Vec = (first..=last).map(|line| self.line(line)).collect(); - let block = lines.join("\n"); - let shift = |at: usize, by: isize| at.saturating_add_signed(by); - match direction { - Direction::Backward if first > 0 => { - let above = self.line(first - 1); - let from = self.line_start(first - 1); - let to = self.line_end(last); - let moved = isize::try_from(above.chars().count() + 1).unwrap_or(0); - let selection = Selection { - anchor: shift(self.selection.anchor, -moved), - head: shift(self.selection.head, -moved), - }; - Some(self.replace( - from..to, - &format!("{block}\n{above}"), - selection, - Kind::Other, - )) - } + let (upper, lower) = match direction { + Direction::Backward if first > 0 => ((first - 1, first - 1), (first, last)), Direction::Forward if last + 1 < self.line_count() => { - let below = self.line(last + 1); - let from = self.line_start(first); - let to = self.line_end(last + 1); - let moved = isize::try_from(below.chars().count() + 1).unwrap_or(0); - let selection = Selection { - anchor: shift(self.selection.anchor, moved), - head: shift(self.selection.head, moved), - }; - Some(self.replace( - from..to, - &format!("{below}\n{block}"), - selection, - Kind::Other, - )) + ((first, last), (last + 1, last + 1)) } - _ => None, - } + _ => return None, + }; + let (from, upper_end) = (self.line_start(upper.0), self.line_end(upper.1)); + let (lower_start, to) = (self.line_start(lower.0), self.line_end(lower.1)); + let part = |range: Range| self.rope.slice(range).to_string(); + let swapped = [ + part(lower_start..to), + part(upper_end..lower_start), + part(from..upper_end), + ] + .concat(); + let shifted = |at: usize| match direction { + Direction::Backward => at.saturating_sub(lower_start - from), + Direction::Forward => at + (to - upper_end), + }; + let selection = Selection { + anchor: shifted(self.selection.anchor), + head: shifted(self.selection.head), + }; + Some(self.replace(from..to, &swapped, selection, Kind::Other)) } /// Ctrl+/: `token ` before every line of the selection, or off them all when each has it. @@ -510,18 +498,21 @@ impl Buffer { let class = crate::words::class; let char_at = |i: usize| self.rope.char(i); let len = self.len(); + let ends_line = |i: usize| { + char_at(i) == '\n' || (char_at(i) == '\r' && i + 1 < len && char_at(i + 1) == '\n') + }; let mut i = at; match direction { Direction::Forward => { - if i < len && char_at(i) == '\n' { - return i + 1; + if i < len && ends_line(i) { + return self.grapheme(i, Direction::Forward); } - while i < len && char_at(i) != '\n' && class(char_at(i)) == 0 { + while i < len && !ends_line(i) && class(char_at(i)) == 0 { i += 1; } - if i < len && char_at(i) != '\n' { + if i < len && !ends_line(i) { let run = class(char_at(i)); - while i < len && char_at(i) != '\n' && class(char_at(i)) == run { + while i < len && !ends_line(i) && class(char_at(i)) == run { i += 1; } } diff --git a/crates/text/src/buffer/tests.rs b/crates/text/src/buffer/tests.rs index 3667971b3..83a4520f0 100644 --- a/crates/text/src/buffer/tests.rs +++ b/crates/text/src/buffer/tests.rs @@ -108,6 +108,34 @@ fn lines_move_up_and_down_with_the_caret() { assert!(buffer.move_lines(Direction::Forward).is_none()); } +/// Joined with `\n` alone, they left the text with both endings and the caret one character off. +#[test] +fn lines_moved_in_a_crlf_text_keep_their_endings() { + let mut buffer = at("a\r\nbc\r\nd", 4); + + buffer.move_lines(Direction::Backward); + assert_eq!(buffer.text(), "bc\r\na\r\nd"); + assert_eq!(buffer.selection(), Selection::caret(1)); + + buffer.move_lines(Direction::Forward); + buffer.move_lines(Direction::Forward); + assert_eq!(buffer.text(), "a\r\nd\r\nbc"); + assert_eq!(buffer.selection(), Selection::caret(7)); +} + +#[test] +fn a_step_by_word_goes_past_a_line_ending_whole() { + for ending in ["\n", "\r\n"] { + let text = format!("ab {ending}cd"); + let buffer = Buffer::new(&text); + let after = 4 + ending.len(); + + assert_eq!(buffer.step(2, Direction::Forward, Unit::Word), 4); + assert_eq!(buffer.step(4, Direction::Forward, Unit::Word), after); + assert_eq!(buffer.step(after, Direction::Backward, Unit::Word), 4); + } +} + #[test] fn a_comment_goes_on_every_line_then_comes_off() { let mut buffer = Buffer::new("a\n b\n\nc"); diff --git a/crates/text/src/indent.rs b/crates/text/src/indent.rs index c47ba68db..335e21989 100644 --- a/crates/text/src/indent.rs +++ b/crates/text/src/indent.rs @@ -37,7 +37,12 @@ pub fn indent(text: &str, start: usize, end: usize, unit: &str) -> TextEdit { } edit_lines(&chars, start, end, |line| LineChange { remove: 0, - add: if line.is_empty() { "" } else { unit }.to_owned(), + add: if matches!(line, [] | ['\r']) { + "" + } else { + unit + } + .to_owned(), }) } @@ -218,6 +223,7 @@ mod tests { assert_eq!(tab("a\n[b\nc]\nd", " "), some("a\n[ b\n c]\nd")); assert_eq!(tab("let [x] = 1", " "), some(" let [x] = 1")); assert_eq!(tab("[a\n\nb\n]c", " "), some("[ a\n\n b\n]c")); + assert_eq!(tab("[a\r\n\r\nb]", " "), some("[ a\r\n\r\n b]")); } #[test] From fc3e4a88d7e481f4ac4ad203bfed5e66ea06a3e4 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 07:37:30 +0100 Subject: [PATCH 49/95] JSON explorer: a character after half a pair is shown (#1773) * Read what follows half a surrogate pair Co-Authored-By: Claude Opus 5.5 * Hold the half pairs as escapes Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/json/parse.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/crates/engine/src/json/parse.rs b/crates/engine/src/json/parse.rs index 1516c4de2..9a027cd0f 100644 --- a/crates/engine/src/json/parse.rs +++ b/crates/engine/src/json/parse.rs @@ -292,10 +292,12 @@ impl Parser<'_> { if self.bytes.get(self.at..self.at + 2) != Some(b"\\u") { return Ok(char::REPLACEMENT_CHARACTER); } + let after_first = (self.at, self.utf16); self.bump(); self.bump(); let second = self.hex4()?; if !(0xDC00..=0xDFFF).contains(&second) { + (self.at, self.utf16) = after_first; return Ok(char::REPLACEMENT_CHARACTER); } let code = 0x10000 + ((first - 0xD800) << 10) + (second - 0xDC00); @@ -394,6 +396,25 @@ mod tests { assert_eq!(root.value, Value::String("a\"b\\c/\né😀\u{fffd}".into())); } + /// What followed half a pair was dropped with it. + #[test] + fn half_a_surrogate_pair_is_one_replacement_and_what_follows_is_read() { + for (text, read) in [ + (r#""\ud83d""#, "\u{fffd}"), + (r#""\ud83db""#, "\u{fffd}b"), + (r#""\ud83d\u0041b""#, "\u{fffd}Ab"), + (r#""\ud83d\n""#, "\u{fffd}\n"), + (r#""\ud83d\ud83d\ude00""#, "\u{fffd}\u{1f600}"), + (r#""\ude00\u0041""#, "\u{fffd}A"), + ] { + assert_eq!( + parse(text).unwrap().value, + Value::String(read.into()), + "{text}" + ); + } + } + #[test] fn keeps_a_number_as_written() { assert_eq!( From 79f0400a96e1d40981c7d21a75b5b7b8d9ccf7ec Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 07:37:38 +0100 Subject: [PATCH 50/95] Request scripts: unit tests rewritten for the host, sends and runs (#1775) * Rewrite the tests of the request scripts' rules, their host, their network and the runs Co-Authored-By: Claude Opus 5.5 * A script of any kind alone, and a GraphQL body handed whole Co-Authored-By: Claude Opus 5.5 * A script's own sends under the request's rules, what a run says and keeps, each held Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/http/console.rs | 306 ++++-- crates/engine/src/http/scripts/around.rs | 483 ++++++++-- crates/engine/src/http/scripts/child.rs | 126 ++- crates/engine/src/http/scripts/model.rs | 434 +++++++-- crates/engine/tests/commands/http_runner.rs | 761 ++++++++++----- crates/engine/tests/commands/http_scripts.rs | 947 +++++++++++++------ crates/engine/tests/scripts.rs | 529 ++++++----- 7 files changed, 2566 insertions(+), 1020 deletions(-) diff --git a/crates/engine/src/http/console.rs b/crates/engine/src/http/console.rs index 6f0cebeec..eef316d7e 100644 --- a/crates/engine/src/http/console.rs +++ b/crates/engine/src/http/console.rs @@ -243,115 +243,261 @@ mod tests { } } - fn exchange(url: &str, headers: &[(&str, &str)]) -> Exchange { + fn scripts() -> [Script; 2] { + [ + script("s1", ScriptKind::Before, ScriptLevel::Collection, "API"), + script("s2", ScriptKind::Tests, ScriptLevel::Request, "Pay"), + ] + } + + fn origin(script: &Script) -> ConsoleOrigin { + ConsoleOrigin { + kind: script.kind, + level: script.level, + name: script.name.clone(), + } + } + + fn header(key: &str, value: &str) -> KeyValue { + KeyValue { + key: key.to_string(), + value: value.to_string(), + ..KeyValue::default() + } + } + + fn exchange(url: &str, headers: Vec) -> Exchange { Exchange { - method: HttpMethod::Get, + method: HttpMethod::Delete, url: url.to_string(), - headers: headers - .iter() - .map(|(key, value)| KeyValue { - key: (*key).to_string(), - value: (*value).to_string(), - ..KeyValue::default() - }) - .collect(), + headers, body: SentBody::None, } } + fn secrets() -> [(String, String); 1] { + [("token".to_string(), "s3cr3t".to_string())] + } + + /// Seconds after an instant. + fn at(seconds: i64) -> DateTime { + DateTime::from_timestamp(1_760_000_000 + seconds, 0).unwrap() + } + + fn log(text: &str, script: &str, seconds: i64) -> LogEntry { + LogEntry { + level: LogLevel::Warn, + text: text.to_string(), + script: Some(script.to_string()), + at: Some(at(seconds)), + } + } + + fn sent(answer: Result) -> ScriptSend { + ScriptSend { + script: Some("s1".to_string()), + exchange: exchange("https://auth/s3cr3t", Vec::new()), + started: at(1), + ended: at(3), + answer, + } + } + + fn lines(logs: Vec, sends: Vec, outcome: &Outcome) -> Vec { + phase(logs, sends, outcome, &scripts(), &secrets()) + .into_iter() + .map(|(_, line)| line) + .collect() + } + #[test] fn a_request_leaves_with_its_secrets_written_as_their_names_and_its_auth_masked() { - let secrets = [("token".to_string(), "s3cr3t".to_string())]; - let ConsoleLine::Out { url, headers, .. } = out( - &exchange( - "https://api.exemple.fr/me?key=s3cr3t", - &[("Authorization", "Bearer s3cr3t"), ("X-Trace", "s3cr3t-1")], - ), - &secrets, + let headers = vec![ + header("Authorization", "Bearer s3cr3t"), + header("X-Trace", "s3cr3t-1"), + ]; + + let line = out( + &exchange("https://shop.test/me?key=s3cr3t", headers), + &secrets(), None, - ) else { - panic!("not a request"); + ); + + let expected = ConsoleLine::Out { + method: "DELETE".to_string(), + url: "https://shop.test/me?key={{token}}".to_string(), + headers: vec![ + header("Authorization", "Bearer ••••••••"), + header("X-Trace", "{{token}}-1"), + ], + by: None, }; - assert_eq!(url, "https://api.exemple.fr/me?key={{token}}"); - assert_eq!(headers[0].value, "Bearer ••••••••"); - assert_eq!(headers[1].value, "{{token}}-1"); + assert_eq!(line, expected); } #[test] - fn a_phase_says_its_logs_and_sends_in_order_then_its_failed_tests_and_its_stop() { - let scripts = [ - script("s1", ScriptKind::Before, ScriptLevel::Collection, "API"), - script("s2", ScriptKind::Tests, ScriptLevel::Request, "Payer"), + fn what_came_back_is_its_status_its_time_and_its_size() { + let response: SentResponse = serde_json::from_value(serde_json::json!({ + "status": 201, "reason": "Created", "millis": 12, "size": 34, "url": "", "headers": [], + "body": "", "binary": false, "cut": false, "incomplete": false, "redirects": [], + "language": "json", "pretty": null, "cookies": [], "graphql": null, + "exchange": { "method": "GET", "url": "", "headers": [], "body": { "kind": "none" } }, + })) + .unwrap(); + + let expected = ConsoleLine::In { + status: 201, + reason: "Created".to_string(), + millis: 12, + size: 34, + by: Some(origin(&scripts()[0])), + }; + assert_eq!(answered(&response, Some(origin(&scripts()[0]))), expected); + assert_eq!( + lines(Vec::new(), vec![sent(Ok(response))], &Outcome::default())[1], + expected + ); + } + + /// The order it happened in: a script's send around what it logged meanwhile. + #[test] + fn a_phase_says_its_logs_and_its_sends_in_the_order_they_came() { + let logs = vec![log("s3cr3t between", "s1", 2), log("last", "gone", 4)]; + + let said = lines( + logs, + vec![sent(Err(SendError::Refused("down".to_string())))], + &Outcome::default(), + ); + + let by = Some(origin(&scripts()[0])); + let expected = [ + ConsoleLine::Out { + method: "DELETE".to_string(), + url: "https://auth/{{token}}".to_string(), + headers: Vec::new(), + by: by.clone(), + }, + ConsoleLine::Log { + level: LogLevel::Warn, + text: "{{token}} between".to_string(), + by: by.clone(), + }, + ConsoleLine::Failed { + code: ErrorCode::HttpRefused, + params: BTreeMap::new(), + by, + }, + ConsoleLine::Log { + level: LogLevel::Warn, + text: "last".to_string(), + by: None, + }, ]; - let at = |seconds: i64| DateTime::from_timestamp(1_760_000_000 + seconds, 0).unwrap(); - let logs = vec![LogEntry { - level: LogLevel::Log, - text: "token s3cr3t".to_string(), - script: Some("s1".to_string()), - at: Some(at(2)), - }]; - let sends = vec![ScriptSend { + assert_eq!(said, expected); + } + + #[test] + fn logs_of_one_instant_keep_their_order() { + let said = lines( + vec![log("a", "s1", 1), log("b", "s1", 1), log("c", "s1", 0)], + Vec::new(), + &Outcome::default(), + ); + + let texts: Vec<_> = said + .iter() + .map(|line| match line { + ConsoleLine::Log { text, .. } => text.as_str(), + _ => "", + }) + .collect(); + assert_eq!(texts, ["c", "a", "b"]); + } + + /// After what the phase logged: the tests that failed, then what stopped it. + #[test] + fn a_phase_ends_on_its_failed_tests_and_what_stopped_it() { + let test = |name: &str| TestResult { + name: name.to_string(), + script: Some("s2".to_string()), + ..TestResult::default() + }; + let failed = TestResult { + expected: Some("\"s3cr3t\"".to_string()), + actual: Some("\"usd\"".to_string()), + message: Some("not s3cr3t".to_string()), + ..test("currency s3cr3t") + }; + let failure = ScriptFailure { + kind: FailureKind::Error, script: Some("s1".to_string()), - exchange: exchange("https://auth/login", &[]), - started: at(1), - ended: at(3), - answer: Err(SendError::Refused("down".to_string())), - }]; + line: Some(4), + message: "boom".to_string(), + }; let outcome = Outcome { tests: vec![ TestResult { - name: "passes".to_string(), passed: true, - ..TestResult::default() + ..test("passes") }, TestResult { - name: "currency".to_string(), - expected: Some("\"eur\"".to_string()), - actual: Some("\"usd\"".to_string()), - script: Some("s2".to_string()), - ..TestResult::default() + skipped: true, + ..test("later") }, + failed, ], - failure: Some(ScriptFailure { - kind: FailureKind::Error, - script: Some("s1".to_string()), - line: Some(4), - message: "boom".to_string(), - }), + failure: Some(failure.clone()), ..Outcome::default() }; - let secrets = [("token".to_string(), "s3cr3t".to_string())]; - let lines = phase(logs, sends, &outcome, &scripts, &secrets); + let said = lines(vec![log("first", "s1", 0)], Vec::new(), &outcome); - let kinds: Vec<&str> = lines - .iter() - .map(|(_, line)| match line { - ConsoleLine::Out { .. } => "out", - ConsoleLine::In { .. } => "in", - ConsoleLine::Failed { .. } => "failed", - ConsoleLine::Log { .. } => "log", - ConsoleLine::Test { .. } => "test", - ConsoleLine::Stopped { .. } => "stopped", - ConsoleLine::Missed { .. } => "missed", - }) - .collect(); - assert_eq!(kinds, ["out", "log", "failed", "test", "stopped"]); - let ConsoleLine::Log { text, by, .. } = &lines[1].1 else { - panic!("not a log"); + let expected = ConsoleLine::Test { + name: "currency {{token}}".to_string(), + expected: Some("\"{{token}}\"".to_string()), + actual: Some("\"usd\"".to_string()), + message: Some("not {{token}}".to_string()), + by: Some(origin(&scripts()[1])), }; - assert_eq!(text, "token {{token}}"); + assert_eq!(said.len(), 3); + assert_eq!(said[1], expected); assert_eq!( - by.as_ref().map(|by| by.level), - Some(ScriptLevel::Collection) + said[2], + ConsoleLine::Stopped { + stop: ScriptStop::of(&failure, &scripts()) + } ); - let ConsoleLine::Failed { code, .. } = &lines[2].1 else { - panic!("not a failure"); - }; - assert_eq!(*code, ErrorCode::HttpRefused); - let ConsoleLine::Test { by, .. } = &lines[3].1 else { - panic!("not a test"); - }; - assert_eq!(by.as_ref().map(|by| by.kind), Some(ScriptKind::Tests)); + } + + #[test] + fn a_text_is_cut_where_a_secret_is_written_as_its_name() { + for (text, parts) in [ + ("", vec![]), + ("plain", vec![("plain", false)]), + ("{{token}}", vec![("{{token}}", true)]), + ( + "a {{b}} c {{d}}", + vec![ + ("a ", false), + ("{{b}}", true), + (" c ", false), + ("{{d}}", true), + ], + ), + ("open {{b", vec![("open {{b", false)]), + ("{{}} x", vec![("{{", false), ("}} x", false)]), + ( + "{{a{{b}}", + vec![("{{", false), ("a", false), ("{{b}}", true)], + ), + ] { + let cut = secret_segments(text); + let cut: Vec<(&str, bool)> = cut + .iter() + .map(|(part, secret)| (part.as_str(), *secret)) + .collect(); + assert_eq!(cut, parts, "{text}"); + } } } diff --git a/crates/engine/src/http/scripts/around.rs b/crates/engine/src/http/scripts/around.rs index 9be05f413..aab49d16a 100644 --- a/crates/engine/src/http/scripts/around.rs +++ b/crates/engine/src/http/scripts/around.rs @@ -248,156 +248,443 @@ mod tests { use crate::http::model::ContainerSettings; use crate::http::settings::{self, HttpOrigin}; - fn scripts(before: &str, after: &str) -> RequestScripts { + fn scripts(before: &str, after: &str, tests: &str) -> RequestScripts { RequestScripts { before: before.to_string(), after: after.to_string(), - tests: format!("{after}-tests"), + tests: tests.to_string(), } } - fn origin(kind: HttpItemKind, id: &str, name: &str) -> HttpOrigin { - HttpOrigin { + fn above( + kind: HttpItemKind, + id: &str, + name: &str, + held: RequestScripts, + ) -> (HttpOrigin, ContainerSettings) { + let origin = HttpOrigin { kind, id: id.to_string(), name: name.to_string(), + }; + ( + origin, + ContainerSettings { + scripts: held, + ..ContainerSettings::default() + }, + ) + } + + /// The collection `API` over the folder `Invoices`, each with its scripts, and the request's. + fn around(collection: RequestScripts, folder: RequestScripts, own: &RequestScripts) -> Around { + let inherited = settings::inherit(&[ + above(HttpItemKind::Collection, "c1", "API", collection), + above(HttpItemKind::Folder, "f1", "Invoices", folder), + ]); + Around::of(own, "Pay", &inherited) + } + + fn ids(list: &[Script]) -> Vec<&str> { + list.iter().map(|script| script.id.as_str()).collect() + } + + #[test] + fn the_scripts_before_run_from_the_collection_down() { + let all = || scripts("a()", "", ""); + + let around = around(all(), all(), &all()); + + assert_eq!( + ids(&around.before), + [ + "collection:c1:before", + "folder:f1:before", + "request:request:before" + ] + ); + } + + #[test] + fn the_scripts_after_run_back_up_then_every_test_back_up() { + let all = || scripts("", "a()", "t()"); + + let around = around(all(), all(), &all()); + + assert_eq!( + ids(&around.answered()), + [ + "request:request:after", + "folder:f1:after", + "collection:c1:after", + "request:request:tests", + "folder:f1:tests", + "collection:c1:tests", + ] + ); + } + + #[test] + fn a_blank_script_is_not_run() { + let around = around( + scripts(" \n", "", ""), + scripts("a()", "\t", ""), + &scripts("", "b()", " "), + ); + + assert_eq!(ids(&around.before), ["folder:f1:before"]); + assert_eq!(ids(&around.answered()), ["request:request:after"]); + assert!(Around::of(&scripts(" ", "", ""), "Pay", &settings::inherit(&[])).is_empty()); + } + + #[test] + fn a_request_with_a_script_of_any_kind_is_not_without_one() { + for own in [ + scripts("a()", "", ""), + scripts("", "a()", ""), + scripts("", "", "a()"), + ] { + assert!( + !Around::of(&own, "Pay", &settings::inherit(&[])).is_empty(), + "{own:?}" + ); + } + } + + #[test] + fn a_script_says_who_holds_it() { + let around = around( + scripts("c()", "", ""), + scripts("f()", "", ""), + &scripts("r()", "", ""), + ); + + let held: Vec<_> = around + .before + .iter() + .map(|script| { + ( + script.level, + script.name.as_str(), + script.owner.as_deref(), + script.source.as_str(), + ) + }) + .collect(); + assert_eq!( + held, + [ + (ScriptLevel::Collection, "API", Some("c1"), "c()"), + (ScriptLevel::Folder, "Invoices", Some("f1"), "f()"), + (ScriptLevel::Request, "Pay", None, "r()"), + ] + ); + assert!( + around + .before + .iter() + .all(|script| script.kind == ScriptKind::Before) + ); + } + + fn variable(name: &str, value: &str) -> Variable { + Variable { + name: name.to_string(), + value: value.to_string(), + ..Variable::default() + } + } + + fn secret(name: &str, value: &str) -> Variable { + Variable { + kind: VariableKind::Secret, + ..variable(name, value) + } + } + + fn level(scope: VariableScope, variables: Vec) -> VariableLayer { + VariableLayer { + scope, + from: "Staging".to_string(), + variables, } } - fn set(scope: WriteScope, name: &str, value: Option<&str>, secret: bool) -> VariableWrite { + #[test] + fn a_script_reads_every_level_but_the_dynamic_one() { + let scopes = [ + VariableScope::Request, + VariableScope::Folder, + VariableScope::Collection, + VariableScope::Environment, + VariableScope::Dynamic, + VariableScope::Globals, + ]; + + let read = layers_of(&scopes.map(|scope| level(scope, vec![variable("a", "1")]))); + + let scopes: Vec = read.iter().map(|layer| layer.scope).collect(); + assert_eq!( + scopes, + [ + LayerScope::Request, + LayerScope::Folder, + LayerScope::Collection, + LayerScope::Environment, + LayerScope::Globals + ] + ); + assert!( + read.iter() + .all(|layer| layer.from == "Staging" && layer.values["a"] == "1") + ); + } + + /// As the send resolves them. + #[test] + fn a_row_switched_off_unnamed_or_at_fault_is_no_value_a_script_reads() { + let off = Variable { + enabled: false, + ..variable("off", "x") + }; + let number = Variable { + kind: VariableKind::Number, + ..variable("count", "many") + }; + let rows = vec![ + variable(" token ", "first"), + variable("token", "second"), + off, + variable(" ", "x"), + variable("not a name", "x"), + number, + ]; + + let read = layers_of(&[level(VariableScope::Environment, rows)]); + + assert_eq!( + read[0].values, + [("token".to_string(), "first".to_string())].into() + ); + } + + fn set(scope: WriteScope, name: &str, value: &str) -> VariableWrite { VariableWrite { scope, name: name.to_string(), - value: value.map(str::to_string), - secret, + value: Some(value.to_string()), + secret: false, } } + fn unset(name: &str) -> VariableWrite { + VariableWrite { + scope: WriteScope::Environment, + name: name.to_string(), + ..VariableWrite::default() + } + } + + fn set_secret(name: &str, value: &str) -> VariableWrite { + VariableWrite { + secret: true, + ..set(WriteScope::Environment, name, value) + } + } + + fn rows(table: &[Variable]) -> Vec<(&str, &str, VariableKind)> { + table + .iter() + .map(|row| (row.name.as_str(), row.value.as_str(), row.kind)) + .collect() + } + #[test] - fn the_scripts_run_from_the_collection_down_before_and_back_up_after() { - let inherited = settings::inherit(&[ - ( - origin(HttpItemKind::Collection, "c1", "API Paiements"), - ContainerSettings { - scripts: scripts("collection()", "collection()"), - ..ContainerSettings::default() - }, - ), - ( - origin(HttpItemKind::Folder, "f1", "Factures"), - ContainerSettings { - scripts: scripts(" \n", "folder()"), - ..ContainerSettings::default() - }, - ), - ]); - let around = Around::of(&scripts("request()", ""), "Payer", &inherited); - let order = |list: &[Script]| -> Vec { - list.iter() - .map(|script| format!("{} {}", script.id, script.name)) - .collect() - }; + fn a_value_set_changes_its_row_and_a_secret_stays_one() { + let table = [secret(" token ", "old"), variable("page", "1")]; + let writes = [ + set(WriteScope::Environment, "token", "new"), + set_secret("page", "2"), + ]; + + let after = written(&table, &writes, None); + assert_eq!( - order(&around.before), + rows(&after), [ - "collection:c1:before API Paiements", - "request:request:before Payer" + (" token ", "new", VariableKind::Secret), + ("page", "2", VariableKind::Secret) ] ); + } + + #[test] + fn a_value_set_under_a_new_name_is_a_row_at_the_end() { + let writes = [ + set(WriteScope::Environment, " page ", "2"), + set_secret("key", "k"), + ]; + + let after = written(&[variable("first", "1")], &writes, None); + assert_eq!( - order(&around.after), + rows(&after), [ - "folder:f1:after Factures", - "collection:c1:after API Paiements" + ("first", "1", VariableKind::Text), + ("page", "2", VariableKind::Text), + ("key", "k", VariableKind::Secret) ] ); + assert!(after.iter().all(|row| row.enabled)); + } + + #[test] + fn a_value_unset_takes_every_row_of_its_name_and_the_writes_go_in_order() { + let table = [ + variable("gone", "1"), + variable("kept", "2"), + variable(" gone ", "3"), + ]; + + let after = written( + &table, + &[unset("gone"), set(WriteScope::Environment, "gone", "4")], + None, + ); + assert_eq!( - order(&around.answered()), + rows(&after), [ - "folder:f1:after Factures", - "collection:c1:after API Paiements", - "request:request:tests Payer", - "folder:f1:tests Factures", - "collection:c1:tests API Paiements", + ("kept", "2", VariableKind::Text), + ("gone", "4", VariableKind::Text) ] ); - assert_eq!(around.before[0].owner.as_deref(), Some("c1")); - assert!(Around::of(&RequestScripts::default(), "x", &settings::inherit(&[])).is_empty()); } #[test] - fn a_write_changes_its_row_keeps_a_secret_secret_adds_or_removes() { - let table = vec![ - Variable { - name: "token".to_string(), - value: "old".to_string(), - kind: VariableKind::Secret, - ..Variable::default() - }, - Variable { - name: "gone".to_string(), - value: "1".to_string(), - ..Variable::default() - }, - ]; + fn a_row_set_says_which_request_filled_it_and_another_keeps_who_did() { + let login = FilledBy { + request_id: Some("r1".to_string()), + name: "Login".to_string(), + }; + let earlier = FilledBy { + request_id: None, + name: "Earlier".to_string(), + }; + let held = |name: &str| Variable { + filled_by: Some(earlier.clone()), + ..variable(name, "1") + }; let writes = [ - set(WriteScope::Environment, "token", Some("new"), false), - set(WriteScope::Environment, "gone", None, false), - set(WriteScope::Environment, "key", Some("k"), true), - set(WriteScope::Environment, "page", Some("2"), false), + set(WriteScope::Environment, "set", "2"), + set(WriteScope::Environment, "new", "3"), ]; - let table = written(&table, &writes, None); - let rows: Vec<(&str, &str, VariableKind)> = table + + let named = written(&[held("set"), held("left")], &writes, Some(&login)); + let unnamed = written(&[held("set")], &writes[..1], None); + + let by: Vec<_> = named .iter() - .map(|variable| { - ( - variable.name.as_str(), - variable.value.as_str(), - variable.kind, - ) - }) + .map(|row| row.filled_by.as_ref().unwrap().name.as_str()) .collect(); - assert_eq!( - rows, - [ - ("token", "new", VariableKind::Secret), - ("key", "k", VariableKind::Secret), - ("page", "2", VariableKind::Text), - ] - ); + assert_eq!(by, ["Login", "Earlier", "Login"]); + assert_eq!(unnamed[0].filled_by, Some(earlier)); } #[test] fn what_a_phase_wrote_is_what_the_send_resolves_from() { - let mut layers = vec![ - VariableLayer { - scope: VariableScope::Environment, - from: "Staging".to_string(), - variables: Vec::new(), - }, - VariableLayer { - scope: VariableScope::Globals, - from: String::new(), - variables: Vec::new(), - }, + let mut layers = [ + level(VariableScope::Collection, Vec::new()), + level(VariableScope::Environment, Vec::new()), + level(VariableScope::Globals, Vec::new()), ]; + apply( &mut layers, &[ - set(WriteScope::Environment, "token", Some("abc"), true), - set(WriteScope::Globals, "tenant", Some("acme"), false), - set(WriteScope::Collection, "nowhere", Some("1"), false), + set_secret("token", "t0k3n"), + set(WriteScope::Globals, "tenant", "acme"), + set(WriteScope::Collection, "page", "2"), ], ); + let resolver = variables::Resolver::new(&layers); - assert_eq!(resolver.fill("{{token}}/{{tenant}}"), "abc/acme"); + assert_eq!( + resolver.fill("{{token}}/{{tenant}}/{{page}}"), + "t0k3n/acme/2" + ); assert_eq!( resolver.secrets(), - [("token".to_string(), "abc".to_string())] + [("token".to_string(), "t0k3n".to_string())] ); + } + + /// With « Aucun », there is no environment to write to: the rest is still applied. + #[test] + fn a_write_to_a_level_the_send_has_not_changes_nothing_else() { + let mut layers = [level(VariableScope::Globals, vec![variable("kept", "1")])]; - let scripted = layers_of(&layers); - assert_eq!(scripted[0].scope, LayerScope::Environment); - assert_eq!(scripted[0].values["token"], "abc"); + apply( + &mut layers, + &[ + set(WriteScope::Collection, "nowhere", "1"), + set(WriteScope::Data, "row", "1"), + ], + ); + + assert_eq!( + rows(&layers[0].variables), + [("kept", "1", VariableKind::Text)] + ); + } + + #[test] + fn local_variables_are_nearer_than_the_request_s_own() { + let locals = locals_layer(&[("path".to_string(), "orders".to_string())].into()); + + let resolver = variables::Resolver::new(&[ + locals, + level(VariableScope::Request, vec![variable("path", "own")]), + ]); + + assert_eq!(resolver.fill("/{{path}}"), "/orders"); + } + + #[test] + fn a_test_is_shown_in_its_script_with_its_secrets_as_their_names() { + let script = Script { + id: "request:request:tests".to_string(), + kind: ScriptKind::Tests, + name: "Pay".to_string(), + source: "const a = 1;\n expect('t0k3n').toBe(a);".to_string(), + ..Script::default() + }; + let say = |text: &str| Some(format!("{text} t0k3n")); + let test = TestResult { + name: "holds t0k3n".to_string(), + message: say("message"), + expected: say("expected"), + actual: say("actual"), + script: Some(script.id.clone()), + line: Some(2), + ..TestResult::default() + }; + + let shown = shown_tests( + vec![test], + &[script], + &[("token".to_string(), "t0k3n".to_string())], + ); + + let test = &shown[0]; + assert_eq!(test.name, "holds {{token}}"); + assert_eq!(test.message.as_deref(), Some("message {{token}}")); + assert_eq!(test.expected.as_deref(), Some("expected {{token}}")); + assert_eq!(test.actual.as_deref(), Some("actual {{token}}")); + assert_eq!(test.code.as_deref(), Some("expect('{{token}}').toBe(a);")); + assert_eq!( + (test.kind, test.holder.as_deref()), + (Some(ScriptKind::Tests), Some("Pay")) + ); } } diff --git a/crates/engine/src/http/scripts/child.rs b/crates/engine/src/http/scripts/child.rs index d8b8291a4..6029e40cb 100644 --- a/crates/engine/src/http/scripts/child.rs +++ b/crates/engine/src/http/scripts/child.rs @@ -181,6 +181,19 @@ mod tests { } } + /// An application gone: nothing can be written to it. + struct Gone; + + impl Write for Gone { + fn write(&mut self, _: &[u8]) -> std::io::Result { + Err(std::io::ErrorKind::BrokenPipe.into()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + fn run_message(source: &str) -> String { let job = Job { phase: Phase::Before, @@ -198,55 +211,102 @@ mod tests { .unwrap() } - fn written(output: &Shared) -> Vec { + fn reply(id: u64) -> String { + let answer = serde_json::json!({ "ok": [] }).to_string(); + serde_json::to_string(&ToHost::Reply { id, answer }).unwrap() + } + + /// What the host wrote for these lines, and the code it ended with. + fn served(lines: &[String]) -> (Vec, i32) { + let output = Shared::default(); + let code = serve_on( + Cursor::new(format!("{}\n", lines.join("\n"))), + output.clone(), + ); let bytes = output.0.lock().unwrap().clone(); - String::from_utf8(bytes) + let messages = String::from_utf8(bytes) .unwrap() .lines() .map(|line| serde_json::from_str(line).unwrap()) - .collect() + .collect(); + (messages, code) + } + + fn outcome(message: &FromHost) -> &Outcome { + match message { + FromHost::Done { outcome } => outcome, + other => panic!("{other:?}"), + } } + const JAR: &str = + "pm.cookies.jar().getAll('https://x.y', (e, all) => env.set('n', all.length));"; + #[test] fn a_job_is_answered_with_its_logs_its_calls_and_its_outcome_then_the_host_ends() { - let reply = serde_json::to_string(&ToHost::Reply { - id: 1, - answer: serde_json::json!({ "ok": [] }).to_string(), - }) - .unwrap(); - let input = format!( - "{}\nnot json\n{reply}\n", - run_message( - "console.log('hi'); pm.cookies.jar().getAll('https://x.y', (e, all) => env.set('n', all.length));" - ) - ); - let output = Shared::default(); - assert_eq!(serve_on(Cursor::new(input), output.clone()), 0); + let (messages, code) = + served(&[run_message(&format!("console.log('hi'); {JAR}")), reply(1)]); - let messages = written(&output); + assert_eq!((messages.len(), code), (3, 0)); assert!(matches!(&messages[0], FromHost::Log { entry } if entry.text == "hi")); assert!(matches!(&messages[1], FromHost::Call { id: 1, kind, .. } if kind == "jarAll")); - let FromHost::Done { outcome } = &messages[2] else { - panic!("{messages:?}"); - }; - assert_eq!(outcome.failure, None); - assert_eq!(outcome.writes[0].value.as_deref(), Some("0")); + let outcome = outcome(&messages[2]); + assert_eq!( + (&outcome.failure, outcome.writes[0].value.as_deref()), + (&None, Some("0")) + ); + } + + #[test] + fn a_line_that_does_not_read_and_an_answer_to_another_call_are_passed_over() { + let lines = [ + "not json".to_string(), + reply(9), + run_message(JAR), + "{}".to_string(), + reply(7), + reply(1), + ]; + + let (messages, code) = served(&lines); + + assert_eq!((messages.len(), code), (2, 0)); + assert_eq!(outcome(&messages[1]).failure, None); + } + + /// One host a request: what the phase before left is there for the one after. + #[test] + fn two_jobs_are_answered_in_turn_by_the_same_engine() { + let first = run_message("pm.variables.set('kept', 'yes');"); + let second = run_message("env.set('read', pm.variables.get('kept'));"); + + let (messages, _) = served(&[first, second]); + + assert_eq!(messages.len(), 2); + assert_eq!( + outcome(&messages[1]).writes[0].value.as_deref(), + Some("yes") + ); } #[test] fn a_call_left_unanswered_fails_the_script_rather_than_hanging() { - let input = format!("{}\n", run_message("await pm.sendRequest('https://x.y');")); - let output = Shared::default(); - serve_on(Cursor::new(input), output.clone()); - let messages = written(&output); - let Some(FromHost::Done { outcome }) = messages.last() else { - panic!("{messages:?}"); - }; + let (messages, _) = served(&[run_message("await pm.sendRequest('https://x.y');")]); + + let failure = outcome(messages.last().unwrap()).failure.clone().unwrap(); assert!( - outcome - .failure - .as_ref() - .is_some_and(|failure| failure.message.contains("stopped answering")) + failure.message.contains("stopped answering"), + "{}", + failure.message ); } + + #[test] + fn a_host_whose_application_is_gone_ends_as_failed() { + let input = |source: &str| Cursor::new(format!("{}\n", run_message(source))); + + assert_eq!(serve_on(input(""), Gone), 1); + assert_eq!(serve_on(input(JAR), Gone), 1); + assert_eq!(serve_on(Cursor::new(String::new()), Gone), 0); + } } diff --git a/crates/engine/src/http/scripts/model.rs b/crates/engine/src/http/scripts/model.rs index 0e0510079..d3f415ffa 100644 --- a/crates/engine/src/http/scripts/model.rs +++ b/crates/engine/src/http/scripts/model.rs @@ -639,32 +639,165 @@ mod tests { use crate::http::graphql::GraphqlDocument; #[test] - fn a_test_is_counted_by_its_call_alone() { - let source = "test('a', () => {});\npm.test('b', () => {});\ntest.skip('c');"; - assert_eq!(tests_declared(source), 2); - assert_eq!( - tests_declared("const latest = 1; env.test('x'); attest(1);"), - 0 - ); + fn a_tab_counts_the_tests_its_script_declares() { + for (source, count) in [ + ("", 0), + ("test('a', () => {});", 1), + ("pm.test('a', f);\ntest ('b', f);", 2), + ("test.skip('c');", 0), + ( + "const latest = 1; env.test('x'); attest(1); _test(1); my9test(1);", + 0, + ), + ("test", 0), + ] { + assert_eq!(tests_declared(source), count, "{source}"); + } + } + + fn params(pairs: &[(&str, &str)]) -> BTreeMap { + pairs + .iter() + .map(|(key, value)| ((*key).to_string(), (*value).to_string())) + .collect() } #[test] fn a_stop_is_read_back_from_what_its_error_carries() { - let params = [ + let carried = [ ("failure", "syntax"), ("level", "folder"), ("name", "Auth"), + ("owner", "f1"), ("line", "3"), ("message", "oops"), - ] - .map(|(key, value)| (key.to_owned(), value.to_owned())) - .into(); - let stop = ScriptStop::of_params(¶ms); + ]; + + let stop = ScriptStop::of_params(¶ms(&carried)); + + let expected = ScriptStop { + kind: FailureKind::Syntax, + level: Some(ScriptLevel::Folder), + script: Some(ScriptKind::Before), + name: Some("Auth".to_string()), + owner: Some("f1".to_string()), + line: Some(3), + message: "oops".to_string(), + }; + assert_eq!(stop, expected); + } + + #[test] + fn a_stop_read_from_an_error_that_says_little_says_as_little() { + let stop = ScriptStop::of_params(¶ms(&[("failure", "unheard of"), ("line", "many")])); + + assert_eq!( + (stop.kind, stop.level, stop.line), + (FailureKind::Error, None, None) + ); + assert_eq!( + (stop.name, stop.owner, stop.message.as_str()), + (None, None, "") + ); + } + + fn script(id: &str, name: &str) -> Script { + Script { + id: id.to_string(), + level: ScriptLevel::Folder, + kind: ScriptKind::Tests, + name: name.to_string(), + owner: Some("f1".to_string()), + source: "const a = 1;\n expect(a).toBe(2); ".to_string(), + } + } + + fn failure(script: Option<&str>) -> ScriptFailure { + ScriptFailure { + kind: FailureKind::Memory, + script: script.map(str::to_string), + line: Some(2), + message: "boom".to_string(), + } + } + + #[test] + fn a_stop_names_the_script_its_failure_names() { + let stop = ScriptStop::of( + &failure(Some("s2")), + &[script("s1", "First"), script("s2", "Second")], + ); + + assert_eq!( + (stop.kind, stop.line, stop.message.as_str()), + (FailureKind::Memory, Some(2), "boom") + ); + assert_eq!( + (stop.level, stop.script), + (Some(ScriptLevel::Folder), Some(ScriptKind::Tests)) + ); + assert_eq!( + (stop.name.as_deref(), stop.owner.as_deref()), + (Some("Second"), Some("f1")) + ); + } + + /// A timeout names no script: with one alone to blame it is that one, with several none. + #[test] + fn a_stop_of_no_named_script_is_the_only_one_there_is() { + let one = ScriptStop::of(&failure(None), &[script("s1", "First")]); + let several = ScriptStop::of( + &failure(Some("gone")), + &[script("s1", "First"), script("s2", "Second")], + ); + + assert_eq!(one.name.as_deref(), Some("First")); + assert_eq!((several.name, several.level), (None, None)); + } + + #[test] + fn a_test_is_placed_in_the_script_that_wrote_it_with_its_line_of_code() { + let test = TestResult { + script: Some("s1".to_string()), + line: Some(2), + ..TestResult::default() + }; + + let placed = test.placed(&[script("s0", "Other"), script("s1", "Auth")]); - assert_eq!(stop.kind, FailureKind::Syntax); - assert_eq!(stop.level, Some(ScriptLevel::Folder)); - assert_eq!(stop.line, Some(3)); - assert_eq!(stop.script, Some(ScriptKind::Before)); + assert_eq!( + (placed.kind, placed.level), + (Some(ScriptKind::Tests), Some(ScriptLevel::Folder)) + ); + assert_eq!( + (placed.holder.as_deref(), placed.owner.as_deref()), + (Some("Auth"), Some("f1")) + ); + assert_eq!(placed.code.as_deref(), Some("expect(a).toBe(2);")); + } + + #[test] + fn a_test_of_no_known_script_or_line_stays_without_its_code() { + let on = |script: &str, line: Option| TestResult { + script: Some(script.to_string()), + line, + ..TestResult::default() + }; + let scripts = [script("s1", "Auth")]; + + for line in [None, Some(0), Some(9)] { + let placed = on("s1", line).placed(&scripts); + assert_eq!( + (placed.holder.as_deref(), placed.code), + (Some("Auth"), None), + "{line:?}" + ); + } + assert_eq!(on("gone", Some(2)).placed(&scripts), on("gone", Some(2))); + assert_eq!( + TestResult::default().placed(&scripts), + TestResult::default() + ); } fn header(key: &str, value: &str) -> KeyValue { @@ -676,96 +809,263 @@ mod tests { } } + fn handed(document: &RequestDocument) -> ScriptRequest { + ScriptRequest::of(RequestKind::Http, HttpMethod::Post, document) + } + #[test] - fn a_request_goes_to_a_script_and_comes_back_with_what_it_changed() { + fn what_a_script_changed_is_what_the_request_sends() { let mut document = RequestDocument { url: "{{baseUrl}}/pay".to_string(), - headers: vec![header("Accept", "application/json")], - body: RequestBody::Json { - text: "{\"amount\":1}".to_string(), - }, ..RequestDocument::default() }; - let mut request = ScriptRequest::of(RequestKind::Http, HttpMethod::Post, &document); - assert_eq!(request.body.mode, "raw"); - assert_eq!(request.body.language, "json"); - - request.method = "put".to_string(); + let mut request = handed(&document); + request.method = " put ".to_string(); request.url.push_str("?retry=1"); request.headers.push(row("X-Signature", "3f9a", true)); - request.body.raw = "{\"amount\":2}".to_string(); + request.headers.push(row("X-Off", "1", false)); + let method = request.onto(RequestKind::Http, &mut document).unwrap(); - assert_eq!(method, HttpMethod::Put); - assert_eq!(document.url, "{{baseUrl}}/pay?retry=1"); - assert_eq!(document.headers[0].description, "about Accept"); - assert_eq!(document.headers[1].key, "X-Signature"); assert_eq!( - document.body, - RequestBody::Json { - text: "{\"amount\":2}".to_string() - } + (method, document.url.as_str()), + (HttpMethod::Put, "{{baseUrl}}/pay?retry=1") ); + let sent: Vec<_> = document + .headers + .iter() + .map(|row| (row.key.as_str(), row.value.as_str(), row.enabled)) + .collect(); + assert_eq!(sent, [("X-Signature", "3f9a", true), ("X-Off", "1", false)]); } + /// A script's rows have no description: each keeps the one of the row of its name. #[test] - fn a_method_rust_does_not_send_is_refused_by_its_name() { - let mut document = RequestDocument::default(); - let mut request = ScriptRequest::of(RequestKind::Http, HttpMethod::Get, &document); - request.method = "PURGE".to_string(); + fn a_row_a_script_hands_back_keeps_its_description() { + let mut document = RequestDocument { + headers: vec![header("Accept", "application/json")], + body: RequestBody::Form { + fields: vec![header("q", "1")], + }, + ..RequestDocument::default() + }; + let mut request = handed(&document); + request.headers[0].value = "text/csv".to_string(); + request.body.urlencoded.push(row("new", "2", true)); + + request.onto(RequestKind::Http, &mut document).unwrap(); + assert_eq!( - request.onto(RequestKind::Http, &mut document), - Err(RequestFault::Method("PURGE".to_string())) + ( + document.headers[0].value.as_str(), + document.headers[0].description.as_str() + ), + ("text/csv", "about Accept") ); + let RequestBody::Form { fields } = &document.body else { + panic!("no form") + }; + let described: Vec<_> = fields.iter().map(|row| row.description.as_str()).collect(); + assert_eq!(described, ["about q", ""]); } + #[test] + fn a_method_rust_does_not_send_is_refused_by_its_name_and_changes_nothing() { + let mut document = RequestDocument { + url: "https://shop.test".to_string(), + ..RequestDocument::default() + }; + let mut request = handed(&document); + request.method = "PURGE".to_string(); + request.url = "https://other.test".to_string(); + + let refused = request.onto(RequestKind::Http, &mut document); + + assert_eq!(refused, Err(RequestFault::Method("PURGE".to_string()))); + assert_eq!(document.url, "https://shop.test"); + } + + /// Each body by the mode a Postman script knows it by, then back as it was. #[test] fn every_body_reads_by_its_postman_mode_and_back() { - let bodies = [ - RequestBody::None, - RequestBody::Text { - text: "hello".to_string(), - }, - RequestBody::Form { - fields: vec![header("q", "1")], - }, - RequestBody::Multipart { - parts: vec![FormPart { - key: "file".to_string(), - value: "/tmp/a.png".to_string(), - file: true, - ..FormPart::default() - }], - }, - RequestBody::Binary { - path: "/tmp/a.bin".to_string(), - }, - ]; - for body in bodies { + let text = |text: &str| text.to_string(); + let part = |key: &str, file: bool| FormPart { + key: key.to_string(), + value: "/tmp/a.png".to_string(), + file, + ..FormPart::default() + }; + for (body, mode, language) in [ + (RequestBody::None, "none", "text"), + ( + RequestBody::Text { + text: text("hello"), + }, + "raw", + "text", + ), + (RequestBody::Json { text: text("{}") }, "raw", "json"), + ( + RequestBody::Form { + fields: vec![header("q", "1")], + }, + "urlencoded", + "text", + ), + ( + RequestBody::Multipart { + parts: vec![part("file", true), part("text", false)], + }, + "formdata", + "text", + ), + ( + RequestBody::Binary { + path: text("/tmp/a.bin"), + }, + "file", + "text", + ), + ] { let mut document = RequestDocument { body: body.clone(), ..RequestDocument::default() }; - let request = ScriptRequest::of(RequestKind::Http, HttpMethod::Post, &document); + let request = handed(&document); + assert_eq!( + (request.body.mode.as_str(), request.body.language.as_str()), + (mode, language) + ); + request.onto(RequestKind::Http, &mut document).unwrap(); + assert_eq!(document.body, body); } } #[test] - fn a_graphql_request_hands_its_query_and_keeps_its_kind() { + fn a_body_of_a_mode_rust_has_no_kind_for_stays_the_one_it_was() { let mut document = RequestDocument { + body: RequestBody::Text { + text: "kept".to_string(), + }, + ..RequestDocument::default() + }; + let mut request = handed(&document); + request.body.mode = "graphql".to_string(); + + request.onto(RequestKind::Http, &mut document).unwrap(); + + assert_eq!( + document.body, + RequestBody::Text { + text: "kept".to_string() + } + ); + } + + fn graphql() -> RequestDocument { + RequestDocument { graphql: GraphqlDocument { query: "{ me { id } }".to_string(), + variables: "{}".to_string(), ..GraphqlDocument::default() }, ..RequestDocument::default() - }; + } + } + + #[test] + fn a_graphql_request_hands_its_query_and_takes_it_back() { + let mut document = graphql(); let mut request = ScriptRequest::of(RequestKind::Graphql, HttpMethod::Post, &document); assert_eq!(request.body.mode, "graphql"); + let handed = &request.body.graphql; + assert_eq!( + (handed.query.as_str(), handed.variables.as_str()), + ("{ me { id } }", "{}") + ); request.body.graphql.query = "{ me { name } }".to_string(); + request.body.graphql.variables = "{\"a\":1}".to_string(); + request.onto(RequestKind::Graphql, &mut document).unwrap(); - assert_eq!(document.graphql.query, "{ me { name } }"); - assert_eq!(document.body, RequestBody::None); + + assert_eq!( + ( + document.graphql.query.as_str(), + document.graphql.variables.as_str() + ), + ("{ me { name } }", "{\"a\":1}") + ); + } + + #[test] + fn a_graphql_request_given_another_body_keeps_its_kind() { + let mut document = graphql(); + let mut request = ScriptRequest::of(RequestKind::Graphql, HttpMethod::Post, &document); + request.body.mode = "raw".to_string(); + request.body.raw = "x".to_string(); + request.body.graphql.query = "{ other }".to_string(); + + request.onto(RequestKind::Graphql, &mut document).unwrap(); + + assert_eq!(document, graphql()); + } + + #[test] + fn a_request_a_script_sends_by_itself_is_made_of_its_url_headers_and_body() { + let request = ScriptRequest { + method: "POST".to_string(), + url: "https://auth.test/login".to_string(), + headers: vec![row("X-Trace", "1", true)], + body: ScriptBody { + mode: "raw".to_string(), + raw: "{}".to_string(), + language: "JSON".to_string(), + ..ScriptBody::default() + }, + }; + + let document = request.document(); + + assert_eq!(document.url, "https://auth.test/login"); + assert_eq!( + ( + document.headers[0].key.as_str(), + document.headers[0].value.as_str() + ), + ("X-Trace", "1") + ); + assert_eq!( + document.body, + RequestBody::Json { + text: "{}".to_string() + } + ); + } + + #[test] + fn a_cookie_an_answer_set_reaches_a_script_whole() { + let cookie = Cookie { + name: "sid".to_string(), + value: "1".to_string(), + domain: Some("shop.test".to_string()), + path: Some("/a".to_string()), + expires: Some("Wed, 21 Oct 2026 07:28:00 GMT".to_string()), + http_only: true, + secure: true, + ..Cookie::default() + }; + + let read = ScriptCookie::from(&cookie); + + assert_eq!( + (read.name, read.value, read.domain, read.path), + (cookie.name, cookie.value, cookie.domain, cookie.path) + ); + assert_eq!( + (read.expires, read.http_only, read.secure), + (cookie.expires, true, true) + ); } } diff --git a/crates/engine/tests/commands/http_runner.rs b/crates/engine/tests/commands/http_runner.rs index 1c2b82bbb..42bbdfac3 100644 --- a/crates/engine/tests/commands/http_runner.rs +++ b/crates/engine/tests/commands/http_runner.rs @@ -3,23 +3,27 @@ use std::path::PathBuf; use std::sync::Arc; +use std::sync::mpsc::Receiver; use std::time::Duration; use engine::EngineEvent; +use engine::error::ErrorCode; +use engine::http::console::ConsoleLine; +use engine::http::environments::Variable; use engine::http::model::{ ContainerSettings, HttpItem, HttpItemKind, HttpMethod, HttpRequestDraft, RequestDocument, RequestKind, RequestScripts, RunEntry, }; -use engine::http::runner::{RunData, RunRequest, RunStep}; +use engine::http::runner::{RunData, RunRequest, RunResult, RunStep}; use engine::http::scripts::process::host_from; use engine::http::{ - cancel_http_run, create_http_collection, create_http_environment, create_http_request, - http_environments, http_history, http_run_order, read_http_run_data, run_http_collection, - save_http_run_order, save_http_settings, + cancel_http_run, count_http_cookies, create_http_collection, create_http_request, + delete_http_item, http_environments, http_history, http_run_order, read_http_run_data, + run_http_collection, save_http_globals, save_http_run_order, save_http_settings, }; use super::Session; -use super::http_send::{response, serve}; +use super::http_send::{Seen, response, serve}; fn hosted() -> Session { host_from(PathBuf::from(env!("CARGO_BIN_EXE_script-host"))); @@ -39,44 +43,110 @@ fn steps(session: &Session) -> Vec { .collect() } -/// A collection of the requests given, `(name, path, scripts)`: its id and theirs. +fn results(session: &Session) -> Vec { + steps(session) + .into_iter() + .filter_map(|step| match step { + RunStep::Ended { result } => Some(*result), + _ => None, + }) + .collect() +} + +/// The iteration and the name of each request that ended. +fn ended(session: &Session) -> Vec<(u32, String)> { + let results = results(session).into_iter(); + results + .map(|result| (result.iteration, result.name)) + .collect() +} + +fn names(session: &Session) -> Vec { + ended(session).into_iter().map(|(_, name)| name).collect() +} + +/// Whether the last run was cancelled, and whether it was capped. +fn finished(session: &Session) -> (bool, bool) { + match steps(session).pop() { + Some(RunStep::Finished { + cancelled, capped, .. + }) => (cancelled, capped), + other => panic!("{other:?}"), + } +} + +fn no_script() -> RequestScripts { + RequestScripts::default() +} + +fn before(source: &str) -> RequestScripts { + RequestScripts { + before: source.to_string(), + ..no_script() + } +} + +fn after(source: &str) -> RequestScripts { + RequestScripts { + after: source.to_string(), + ..no_script() + } +} + +fn failing() -> RequestScripts { + RequestScripts { + tests: "test('never', () => expect(res.status).toBe(500));".to_string(), + ..no_script() + } +} + +fn draft(collection: &str, name: &str, url: String, scripts: RequestScripts) -> HttpRequestDraft { + HttpRequestDraft { + collection_id: collection.to_string(), + folder_id: None, + name: name.to_string(), + kind: RequestKind::Http, + method: HttpMethod::Get, + document: RequestDocument { + url, + scripts, + ..RequestDocument::default() + }, + } +} + +/// A collection of requests to the loopback, each named as its path, and their ids. fn collection( session: &Session, port: u16, - requests: &[(&str, &str, RequestScripts)], + requests: Vec<(&str, RequestScripts)>, ) -> (String, Vec) { let api = session .call(|e| create_http_collection(e, "Run")) .unwrap() .id; let ids = requests - .iter() - .map(|(name, path, scripts)| { - let draft = HttpRequestDraft { - collection_id: api.clone(), - folder_id: None, - name: (*name).to_string(), - kind: RequestKind::Http, - method: HttpMethod::Get, - document: RequestDocument { - url: format!("http://127.0.0.1:{port}{path}"), - scripts: scripts.clone(), - ..RequestDocument::default() - }, - }; + .into_iter() + .map(|(name, scripts)| { + let url = format!("http://127.0.0.1:{port}/{name}"); + let draft = draft(&api, name, url, scripts); session.call(|e| create_http_request(e, &draft)).unwrap().id }) .collect(); (api, ids) } -fn run(id: &str, api: &str, order: Vec) -> RunRequest { +fn item(api: &str) -> HttpItem { + HttpItem { + kind: HttpItemKind::Collection, + id: api.to_string(), + } +} + +fn run_of(api: &str, order: Vec) -> RunRequest { RunRequest { - id: id.to_string(), - item: HttpItem { - kind: HttpItemKind::Collection, - id: api.to_string(), - }, + id: "run-1".to_string(), + item: item(api), order, iterations: 1, delay_ms: 0, @@ -89,284 +159,488 @@ fn run(id: &str, api: &str, order: Vec) -> RunRequest { } } -fn ended(steps: &[RunStep]) -> Vec<(u32, String, bool)> { - steps - .iter() - .filter_map(|step| match step { - RunStep::Ended { result } => { - Some((result.iteration, result.name.clone(), result.failed())) - } - _ => None, - }) - .collect() +fn run(session: &Session, asked: RunRequest) { + session.wait(|e| run_http_collection(e, asked)).unwrap(); } fn ok() -> Vec { response("200 OK", &[("Content-Type", "application/json")], b"{}") } +/// A server for as many requests, each answered `{}`. +fn server(requests: usize) -> (u16, Receiver) { + serve(requests, |_, _| ok()) +} + +/// The path of each request the server read, as many as there were. +fn paths(seen: &Receiver, count: usize) -> Vec { + (0..count) + .map(|_| { + let read = seen.recv_timeout(Duration::from_secs(5)).unwrap().head; + read.split(' ').nth(1).unwrap().to_string() + }) + .collect() +} + +fn data(values: &[&str]) -> RunData { + let row = |value: &&str| [("customer".to_string(), (*value).to_string())].into(); + RunData { + columns: vec!["customer".to_string()], + rows: values.iter().map(row).collect(), + } +} + #[test] -fn a_run_sends_its_requests_over_the_rows_of_its_data_and_writes_no_history() { +fn a_run_sends_its_requests_in_the_order_given_and_says_each_step() { + let session = Session::open(); + let (port, seen) = server(2); + let (api, ids) = collection(&session, port, vec![("A", no_script()), ("B", no_script())]); + let order = vec![ids[1].clone(), "gone".to_string(), ids[0].clone()]; + + run(&session, run_of(&api, order)); + + assert_eq!(paths(&seen, 2), ["/B", "/A"]); + let said: Vec = steps(&session) + .into_iter() + .map(|step| match step { + RunStep::Started { + iteration, + index, + name, + } => format!("{iteration}.{index} {name}"), + RunStep::Ended { result } => format!("{} {:?}", result.name, result.status), + RunStep::Finished { cancelled, .. } => format!("finished {cancelled}"), + }) + .collect(); + let expected = [ + "0.0 B", + "B Some(200)", + "0.1 A", + "A Some(200)", + "finished false", + ]; + assert_eq!(said, expected); + assert!(results(&session).iter().all(|result| !result.failed())); +} + +#[test] +fn a_run_of_nothing_is_over_at_once() { + let session = Session::open(); + let (api, _) = collection(&session, 9, Vec::new()); + + run(&session, run_of(&api, Vec::new())); + + assert_eq!(steps(&session).len(), 1); + assert_eq!(finished(&session), (false, false)); +} + +#[test] +fn a_run_goes_through_its_iterations_once_at_least() { + for (asked, expected) in [(0, vec![0]), (1, vec![0]), (3, vec![0, 1, 2])] { + let session = Session::open(); + let (port, _seen) = server(expected.len()); + let (api, ids) = collection(&session, port, vec![("A", no_script())]); + let mut several = run_of(&api, ids); + several.iterations = asked; + + run(&session, several); + + let iterations: Vec = ended(&session).into_iter().map(|(at, _)| at).collect(); + assert_eq!(iterations, expected); + } +} + +/// A row an iteration, whatever the number asked for: its values in the URL, and what a script +/// reads of them. +#[test] +fn a_run_over_a_data_file_goes_through_its_rows() { let session = hosted(); - let staging = session - .call(|e| create_http_environment(e, "Staging")) - .unwrap() - .id; - let (port, seen) = serve(4, |_, _| ok()); + let (port, seen) = server(4); + let seeing = before("pm.variables.set('seen', pm.iterationData.get('customer'));"); let (api, ids) = collection( &session, port, - &[ - ( - "Login", - "/login", - RequestScripts { - before: "env.set('seen', pm.iterationData.get('customer'));".to_string(), - tests: "test('ok', () => expect(res.status).toBe(200));".to_string(), - ..RequestScripts::default() - }, - ), - ( - "Client", - "/c/{{customer}}?i={{seen}}", - RequestScripts::default(), - ), + vec![ + ("login", no_script()), + ("c/{{customer}}?i={{seen}}", seeing), ], ); - let mut asked = run("run-1", &api, ids); - asked.data = Some(RunData { - columns: vec!["customer".to_string()], - rows: vec![ - [("customer".to_string(), "cus_1".to_string())].into(), - [("customer".to_string(), "cus_2".to_string())].into(), - ], - }); - asked.keep_variables = false; - asked.environment_id = Some(staging.clone()); + let mut asked = run_of(&api, ids); + asked.data = Some(data(&["cus_1", "cus_2"])); + asked.iterations = 9; - session.wait(|e| run_http_collection(e, asked)).unwrap(); + run(&session, asked); + + let expected = ["/login", "/c/cus_1?i=cus_1", "/login", "/c/cus_2?i=cus_2"]; + assert_eq!(paths(&seen, 4), expected); +} + +#[test] +fn a_run_writes_no_history() { + let session = Session::open(); + let (port, _seen) = server(1); + let (api, ids) = collection(&session, port, vec![("A", no_script())]); + + run(&session, run_of(&api, ids)); - let paths: Vec = (0..4) - .map(|_| { - let read = seen.recv_timeout(Duration::from_secs(5)).unwrap().head; - read.lines().next().unwrap().to_string() - }) - .collect(); - assert_eq!( - paths, - [ - "GET /login HTTP/1.1", - "GET /c/cus_1?i=cus_1 HTTP/1.1", - "GET /login HTTP/1.1", - "GET /c/cus_2?i=cus_2 HTTP/1.1", - ] - ); - assert_eq!( - ended(&steps(&session)), - [ - (0, "Login".to_string(), false), - (0, "Client".to_string(), false), - (1, "Login".to_string(), false), - (1, "Client".to_string(), false), - ] - ); - assert!(matches!( - steps(&session).last(), - Some(RunStep::Finished { - cancelled: false, - .. - }) - )); - // A run keeps its report, not the history; and what it wrote was for it alone. assert!(session.call(|e| http_history(e, 0)).unwrap().is_empty()); - let sets = session.call(http_environments).unwrap(); - assert!(sets.environments[0].variables.is_empty()); } +/// Either way the requests after resolve from it. #[test] -fn a_run_stops_at_its_first_failure_when_asked() { - let session = hosted(); - let (port, _seen) = serve(2, |_, _| ok()); - let failing = RequestScripts { - tests: "test('never', () => expect(res.status).toBe(500));".to_string(), - ..RequestScripts::default() +fn what_a_run_s_scripts_write_is_kept_only_when_asked() { + for keep in [true, false] { + let session = hosted(); + let (port, seen) = server(2); + let writing = before("env.set('path', 'written');"); + let (api, ids) = collection( + &session, + port, + vec![("A", writing), ("{{path}}", no_script())], + ); + let mut asked = run_of(&api, ids); + asked.keep_variables = keep; + + run(&session, asked); + + assert_eq!(paths(&seen, 2), ["/A", "/written"]); + let globals = session.call(http_environments).unwrap().globals; + assert_eq!(globals.len(), usize::from(keep)); + } +} + +#[test] +fn a_row_of_data_is_nearer_than_a_variable_of_its_name() { + let session = Session::open(); + let (port, seen) = server(1); + let global = Variable { + name: "customer".to_string(), + value: "global".to_string(), + ..Variable::default() }; + session.call(|e| save_http_globals(e, &[global])).unwrap(); + let (api, ids) = collection(&session, port, vec![("{{customer}}", no_script())]); + let mut asked = run_of(&api, ids); + asked.data = Some(data(&["row"])); + + run(&session, asked); + + assert_eq!(paths(&seen, 1), ["/row"]); +} + +#[test] +fn a_run_stops_at_its_first_failure_only_when_asked() { + for (stop, expected) in [(true, vec!["A"]), (false, vec!["A", "B"])] { + let session = hosted(); + let (port, _seen) = server(2); + let (api, ids) = collection(&session, port, vec![("A", failing()), ("B", no_script())]); + let mut asked = run_of(&api, ids); + asked.stop_on_failure = stop; + + run(&session, asked); + + assert_eq!(names(&session), expected); + assert!(results(&session)[0].failed()); + assert_eq!(finished(&session), (false, false)); + } +} + +#[test] +fn an_answer_is_kept_with_its_result_only_when_asked() { + for keep in [true, false] { + let session = Session::open(); + let (port, _seen) = server(1); + let (api, ids) = collection(&session, port, vec![("A", no_script())]); + let mut asked = run_of(&api, ids); + asked.keep_responses = keep; + + run(&session, asked); + + assert_eq!(results(&session)[0].response.is_some(), keep); + } +} + +#[test] +fn a_script_names_the_request_a_run_goes_to_and_null_ends_it() { + let session = hosted(); + let (port, _seen) = server(2); let (api, ids) = collection( &session, port, - &[("A", "/a", failing), ("B", "/b", RequestScripts::default())], + vec![ + ("A", after("pm.execution.setNextRequest('C');")), + ("B", no_script()), + ("C", after("pm.execution.setNextRequest(null);")), + ("D", no_script()), + ], ); - let mut asked = run("run-2", &api, ids); - asked.stop_on_failure = true; - asked.keep_responses = true; + let mut asked = run_of(&api, ids); + asked.iterations = 2; - session.wait(|e| run_http_collection(e, asked)).unwrap(); + run(&session, asked); - assert_eq!(ended(&steps(&session)), [(0, "A".to_string(), true)]); - let kept = steps(&session).iter().any( - |step| matches!(step, RunStep::Ended { result } if result.response.as_ref().is_some_and(|response| response.status == 200)), - ); - assert!(kept, "the answer kept with its result"); + assert_eq!(names(&session), ["A", "C"]); } #[test] -fn a_script_names_the_request_a_run_goes_to_and_null_ends_it() { +fn a_script_before_its_send_names_the_next_request_too() { let session = hosted(); - let (port, _seen) = serve(3, |_, _| ok()); - let to_c = RequestScripts { - after: "pm.execution.setNextRequest('C');".to_string(), - ..RequestScripts::default() - }; - let end = RequestScripts { - after: "pm.execution.setNextRequest(null);".to_string(), - ..RequestScripts::default() - }; + let (port, _seen) = server(2); + let to_c = before("pm.execution.setNextRequest('C');"); let (api, ids) = collection( &session, port, - &[ - ("A", "/a", to_c), - ("B", "/b", RequestScripts::default()), - ("C", "/c", end), - ("D", "/d", RequestScripts::default()), - ], + vec![("A", to_c), ("B", no_script()), ("C", no_script())], ); - session - .wait(|e| run_http_collection(e, run("run-3", &api, ids))) - .unwrap(); + run(&session, run_of(&api, ids)); + + assert_eq!(names(&session), ["A", "C"]); +} + +/// Counted from 0 for the script, from 1 in the console. +#[test] +fn a_script_and_the_console_know_the_iteration() { + let session = hosted(); + let (port, _seen) = server(2); + let saying = before("console.log(pm.info.iteration, pm.info.iterationCount);"); + let (api, ids) = collection(&session, port, vec![("A", saying)]); + let mut asked = run_of(&api, ids); + asked.iterations = 2; - let names: Vec = ended(&steps(&session)) + run(&session, asked); + + let said: Vec<(String, Option)> = session + .heard + .events() .into_iter() - .map(|(_, name, _)| name) + .filter_map(|event| match event { + EngineEvent::Console(event) => match event.line { + ConsoleLine::Log { text, .. } => Some((text, event.iteration)), + _ => None, + }, + _ => None, + }) .collect(); - assert_eq!(names, ["A", "C"]); + let expected = [("0 2".to_string(), Some(1)), ("1 2".to_string(), Some(2))]; + assert_eq!(said, expected); } +/// The report is the run's; the jar is the library's. #[test] -fn a_run_is_cancelled_between_two_requests() { +fn a_run_keeps_the_cookies_its_answers_set() { + let session = Session::open(); + let (port, _seen) = serve(1, |_, _| { + response("200 OK", &[("Set-Cookie", "sid=1; Path=/")], b"") + }); + let (api, ids) = collection(&session, port, vec![("A", no_script())]); + + run(&session, run_of(&api, ids)); + + assert_eq!(session.call(count_http_cookies).unwrap(), 1); +} + +#[test] +fn a_request_a_script_skips_is_not_a_failure() { let session = hosted(); - let (port, _seen) = serve(2, |_, _| ok()); + let (port, _seen) = server(1); + let skipping = before("pm.execution.skipRequest();"); + let (api, ids) = collection(&session, port, vec![("A", skipping), ("B", no_script())]); + let mut asked = run_of(&api, ids); + asked.stop_on_failure = true; + + run(&session, asked); + + assert_eq!(names(&session), ["A", "B"]); + let skipped = &results(&session)[0]; + assert!(skipped.skipped && !skipped.failed()); +} + +/// Deleted while the run goes: the next step says so, and the run goes on. +#[test] +fn a_request_deleted_while_the_run_goes_is_said_gone() { + let session = Session::open(); + let (engine, gone) = ( + Arc::clone(&session.engine), + Arc::new(std::sync::OnceLock::new()), + ); + let deleted: Arc> = Arc::clone(&gone); + let (port, _seen) = serve(2, move |seen, _| { + if seen.head.starts_with("GET /A ") { + let request = HttpItem { + kind: HttpItemKind::Request, + id: deleted.get().unwrap().clone(), + }; + engine::db::run_here(&engine, |e| delete_http_item(e, &request)).unwrap(); + } + ok() + }); let (api, ids) = collection( &session, port, - &[ - ("A", "/a", RequestScripts::default()), - ("B", "/b", RequestScripts::default()), - ], - ); - let mut asked = run("run-4", &api, ids); - asked.delay_ms = 20_000; - let (engine, runtime) = ( - Arc::clone(&session.engine), - session.runtime.handle().clone(), + vec![("A", no_script()), ("B", no_script()), ("C", no_script())], ); - let running = std::thread::spawn(move || runtime.block_on(run_http_collection(engine, asked))); + gone.set(ids[1].clone()).unwrap(); + + run(&session, run_of(&api, ids)); + + assert_eq!(names(&session), ["A", "B", "C"]); + let gone = &results(&session)[1]; + let code = gone.error.as_ref().unwrap().code; + assert_eq!(code, ErrorCode::HttpItemNotFound); + assert!(gone.failed()); +} + +/// No question halfway through a run. +#[test] +fn a_file_a_script_asks_to_send_fails_its_step() { + let session = hosted(); + let (port, _seen) = server(1); + let file = before("pm.request.body.update({ mode: 'file', file: { src: '/etc/passwd' } });"); + let (api, ids) = collection(&session, port, vec![("A", file)]); + + run(&session, run_of(&api, ids)); + + let refused = results(&session)[0].error.clone().unwrap(); + assert_eq!(refused.code, ErrorCode::HttpScriptFile); +} + +/// A run started on a thread of its own. +fn running(session: &Session, asked: RunRequest) -> std::thread::JoinHandle<()> { + let engine = Arc::clone(&session.engine); + let runtime = session.runtime.handle().clone(); + std::thread::spawn(move || { + runtime + .block_on(run_http_collection(engine, asked)) + .unwrap(); + }) +} + +fn eventually(what: &str, mut holds: impl FnMut() -> bool) { let waited = std::time::Instant::now(); - while ended(&steps(&session)).is_empty() { - assert!( - waited.elapsed() < Duration::from_secs(10), - "the first request never ended" - ); + while !holds() { + assert!(waited.elapsed() < Duration::from_secs(10), "{what}"); std::thread::sleep(Duration::from_millis(20)); } +} - assert!(session.call(|e| cancel_http_run(e, "run-4")).unwrap()); - running.join().unwrap().unwrap(); +#[test] +fn a_run_is_cancelled_between_two_requests() { + let session = Session::open(); + let (port, _seen) = server(2); + let (api, ids) = collection(&session, port, vec![("A", no_script()), ("B", no_script())]); + let mut asked = run_of(&api, ids); + asked.delay_ms = 20_000; - assert_eq!(ended(&steps(&session)).len(), 1); - assert!(matches!( - steps(&session).last(), - Some(RunStep::Finished { - cancelled: true, - .. - }) - )); - assert!(!session.call(|e| cancel_http_run(e, "run-4")).unwrap()); + let running = running(&session, asked); + eventually("the first request ended", || !ended(&session).is_empty()); + assert!(session.call(|e| cancel_http_run(e, "run-1")).unwrap()); + running.join().unwrap(); + + assert_eq!(names(&session), ["A"]); + assert_eq!(finished(&session), (true, false)); + assert!(!session.call(|e| cancel_http_run(e, "run-1")).unwrap()); } -fn block_on(future: F) -> F::Output { - tokio::runtime::Runtime::new().unwrap().block_on(future) +#[test] +fn a_run_cancelled_while_a_request_is_under_way_ends_without_its_result() { + let session = Session::open(); + let (port, _seen) = serve(1, |_, _| { + std::thread::sleep(Duration::from_secs(5)); + ok() + }); + let (api, ids) = collection(&session, port, vec![("A", no_script()), ("B", no_script())]); + + let running = running(&session, run_of(&api, ids)); + eventually("the first request left", || !steps(&session).is_empty()); + eventually("the run ended", || { + let _ = session.call(|e| cancel_http_run(e, "run-1")).unwrap(); + running.is_finished() + }); + running.join().unwrap(); + + assert!(ended(&session).is_empty()); + assert_eq!(finished(&session), (true, false)); } #[test] -fn a_data_file_is_read_as_a_csv_or_says_why_not() { +fn a_data_file_is_read_as_a_csv() { let directory = tempfile::tempdir().unwrap(); let csv = directory.path().join("clients.csv"); std::fs::write(&csv, "customer,amount\ncus_1,12\ncus_2,8\n").unwrap(); - let data = block_on(read_http_run_data(csv.display().to_string())).unwrap(); + let session = Session::locked(); + + let data = session.wait(|_| read_http_run_data(csv.display().to_string())); + + let data = data.unwrap(); assert_eq!(data.columns, ["customer", "amount"]); assert_eq!(data.rows.len(), 2); - - let empty = directory.path().join("empty.csv"); - std::fs::write(&empty, "customer\n").unwrap(); - let error = block_on(read_http_run_data(empty.display().to_string())).unwrap_err(); - assert_eq!(error.params["fault"], "empty"); - assert!( - block_on(read_http_run_data( - directory.path().join("nowhere.csv").display().to_string() - )) - .is_err() - ); } #[test] -fn the_order_arranged_is_kept_and_a_request_added_goes_at_its_end() { - let session = Session::open(); - let (api, ids) = collection( - &session, - 9, - &[ - ("A", "/a", RequestScripts::default()), - ("B", "/b", RequestScripts::default()), - ], - ); - let item = || HttpItem { - kind: HttpItemKind::Collection, - id: api.clone(), +fn a_data_file_that_gives_nothing_says_why() { + let directory = tempfile::tempdir().unwrap(); + let session = Session::locked(); + let read = |name: &str| { + let path = directory.path().join(name).display().to_string(); + session.wait(|_| read_http_run_data(path)).unwrap_err() }; - let entry = |id: &str, enabled: bool| RunEntry { + for (name, text, fault) in [ + ( + "empty.csv", + "customer +", + "empty", + ), + ("broken.json", "[{", "unreadable"), + ] { + std::fs::write(directory.path().join(name), text).unwrap(); + let error = read(name); + assert_eq!(error.code, ErrorCode::HttpRunData); + assert_eq!(error.params["fault"], fault); + } + assert_eq!(read("nowhere.csv").code, ErrorCode::FileAccess); +} + +fn entry(id: &str, enabled: bool) -> RunEntry { + RunEntry { id: id.to_string(), enabled, - }; + } +} + +#[test] +fn the_order_arranged_is_kept_and_a_request_added_goes_at_its_end() { + let session = Session::open(); + let (api, ids) = collection(&session, 9, vec![("A", no_script()), ("B", no_script())]); + let arranged = vec![entry(&ids[1], true), entry(&ids[0], false)]; + session - .call(|e| { - save_http_run_order( - e, - &item(), - vec![entry(&ids[1], true), entry(&ids[0], false)], - ) - }) + .call(|e| save_http_run_order(e, &item(&api), arranged.clone())) .unwrap(); - let added = session - .call(|e| { - create_http_request( - e, - &HttpRequestDraft { - collection_id: api.clone(), - folder_id: None, - name: "C".to_string(), - kind: RequestKind::Http, - method: HttpMethod::Get, - document: RequestDocument::default(), - }, - ) - }) - .unwrap() - .id; - // The settings dialog saves what it holds, which has no run order. + let draft = draft(&api, "C", String::new(), no_script()); + let added = session.call(|e| create_http_request(e, &draft)).unwrap().id; + + let order = session.call(|e| http_run_order(e, &item(&api))).unwrap(); + assert_eq!(order, [&arranged[..], &[entry(&added, true)]].concat()); +} + +/// The settings dialog saves what it holds, which has no run order. +#[test] +fn the_order_arranged_survives_the_settings_being_saved() { + let session = Session::open(); + let (api, ids) = collection(&session, 9, vec![("A", no_script()), ("B", no_script())]); + let arranged = vec![entry(&ids[1], true), entry(&ids[0], true)]; session - .call(|e| save_http_settings(e, &item(), ContainerSettings::default())) + .call(|e| save_http_run_order(e, &item(&api), arranged.clone())) .unwrap(); - assert_eq!( - session.call(|e| http_run_order(e, &item())).unwrap(), - [ - entry(&ids[1], true), - entry(&ids[0], false), - entry(&added, true) - ] - ); + session + .call(|e| save_http_settings(e, &item(&api), ContainerSettings::default())) + .unwrap(); + + let order = session.call(|e| http_run_order(e, &item(&api))).unwrap(); + assert_eq!(order, arranged); } /// A request whose script names itself again: the run stops at the cap and says so, where it @@ -377,21 +651,12 @@ fn the_order_arranged_is_kept_and_a_request_added_goes_at_its_end() { fn a_run_that_loops_on_one_request_stops_at_the_cap() { let session = hosted(); let cap = engine::http::runner::MAX_STEPS as usize; - let (port, _seen) = serve(cap, |_, _| ok()); - let again = RequestScripts { - after: "pm.execution.setNextRequest('Poll');".to_string(), - ..RequestScripts::default() - }; - let (api, ids) = collection(&session, port, &[("Poll", "/poll", again)]); + let (port, _seen) = server(cap); + let again = after("pm.execution.setNextRequest('Poll');"); + let (api, ids) = collection(&session, port, vec![("Poll", again)]); - session - .wait(|e| run_http_collection(e, run("run-loop", &api, ids))) - .unwrap(); + run(&session, run_of(&api, ids)); - let steps = steps(&session); - assert_eq!(ended(&steps).len(), cap); - assert!(matches!( - steps.last(), - Some(RunStep::Finished { capped: true, .. }) - )); + assert_eq!(ended(&session).len(), cap); + assert_eq!(finished(&session), (false, true)); } diff --git a/crates/engine/tests/commands/http_scripts.rs b/crates/engine/tests/commands/http_scripts.rs index fa5026246..ca0b60cf5 100644 --- a/crates/engine/tests/commands/http_scripts.rs +++ b/crates/engine/tests/commands/http_scripts.rs @@ -3,53 +3,66 @@ //! them says where. use std::path::PathBuf; - +use std::sync::Arc; +use std::sync::mpsc::Receiver; use std::time::Duration; use engine::EngineEvent; -use engine::error::ErrorCode; -use engine::http::console::{ConsoleEvent, ConsoleLine}; +use engine::error::{AppError, ErrorCode}; +use engine::http::console::ConsoleLine; use engine::http::environments::{EnvironmentPatch, FilledBy, Variable, VariableKind}; use engine::http::model::{ ContainerSettings, Extraction, HttpItem, HttpItemKind, HttpMethod, RequestScripts, }; -use engine::http::scripts::model::{FailureKind, ScriptKind, ScriptLevel}; +use engine::http::scripts::model::{FailureKind, ScriptKind, ScriptLevel, TestResult}; use engine::http::scripts::process::host_from; +use engine::http::send::{SendRequest, SentResponse}; use engine::http::{ - create_http_collection, create_http_environment, http_environments, http_history, - http_history_entry, http_settings, save_http_environment, save_http_settings, - send_http_request, + cancel_http_send, create_http_collection, create_http_environment, delete_http_environment, + http_cookies, http_environments, http_history, http_history_entry, http_settings, + save_http_environment, save_http_settings, send_http_request, }; use super::Session; -use super::http_send::{header_of, request, response, serve}; +use super::http_send::{Seen, header_of, request, response, serve}; + +fn hosted() -> Session { + host_from(PathBuf::from(env!("CARGO_BIN_EXE_script-host"))); + Session::open() +} -/// The console's lines as they cross, for the session of the test. -fn console(session: &Session) -> Vec { +fn send(session: &Session, request: SendRequest) -> Result { + session.wait(|e| send_http_request(e, request)) +} + +/// The console's lines, as they crossed. +fn console(session: &Session) -> Vec { session .heard .events() .into_iter() .filter_map(|event| match event { - EngineEvent::Console(event) => Some(event), + EngineEvent::Console(event) => Some(event.line), _ => None, }) .collect() } -fn logs(heard: &[ConsoleEvent]) -> Vec { - heard - .iter() - .filter_map(|event| match &event.line { - ConsoleLine::Log { text, .. } => Some(text.clone()), +fn logs(session: &Session) -> Vec { + console(session) + .into_iter() + .filter_map(|line| match line { + ConsoleLine::Log { text, .. } => Some(text), _ => None, }) .collect() } -fn hosted() -> Session { - host_from(PathBuf::from(env!("CARGO_BIN_EXE_script-host"))); - Session::open() +fn not_kept_said(session: &Session) -> bool { + let events = session.heard.events(); + events + .iter() + .any(|event| matches!(event, EngineEvent::SendNotKept)) } fn scripts(before: &str, after: &str) -> RequestScripts { @@ -60,20 +73,54 @@ fn scripts(before: &str, after: &str) -> RequestScripts { } } +fn tests(source: &str) -> RequestScripts { + RequestScripts { + tests: source.to_string(), + ..RequestScripts::default() + } +} + +/// A server answering `{"id":7}`, and a request to it with these scripts. +fn scripted(scripts: RequestScripts) -> (SendRequest, Receiver) { + let (port, seen) = serve(1, |_, _| ok()); + let mut sent = request(&format!("http://127.0.0.1:{port}/")); + sent.document.scripts = scripts; + (sent, seen) +} + +fn ok() -> Vec { + response( + "200 OK", + &[("Content-Type", "application/json")], + b"{\"id\":7}", + ) +} + +fn never_left(seen: &Receiver) -> bool { + seen.recv_timeout(Duration::from_millis(300)).is_err() +} + +fn variable(name: &str, value: &str) -> Variable { + Variable { + name: name.to_string(), + value: value.to_string(), + ..Variable::default() + } +} + /// An environment holding `token`, a secret. fn environment(session: &Session, name: &str, protected: bool) -> String { let id = session .call(|e| create_http_environment(e, name)) .unwrap() .id; + let token = Variable { + kind: VariableKind::Secret, + ..variable("token", "s3cr3t-value") + }; let patch = EnvironmentPatch { protected: Some(protected), - variables: Some(vec![Variable { - name: "token".to_string(), - value: "s3cr3t-value".to_string(), - kind: VariableKind::Secret, - ..Variable::default() - }]), + variables: Some(vec![token]), ..EnvironmentPatch::default() }; session @@ -82,337 +129,587 @@ fn environment(session: &Session, name: &str, protected: bool) -> String { id } -fn ok() -> Vec { - response( - "200 OK", - &[("Content-Type", "application/json")], - b"{\"id\":7}", - ) +/// A row of an environment as it is kept. +fn row_of(session: &Session, environment: &str, name: &str) -> Option { + let sets = session.call(http_environments).unwrap(); + sets.environments + .into_iter() + .find(|known| known.id == environment) + .unwrap() + .variables + .into_iter() + .find(|row| row.name == name) +} + +fn collection_item(id: &str) -> HttpItem { + HttpItem { + kind: HttpItemKind::Collection, + id: id.to_string(), + } +} + +/// The collection `API` with its scripts, by its id. +fn collection(session: &Session, scripts: RequestScripts) -> String { + let id = session + .call(|e| create_http_collection(e, "API")) + .unwrap() + .id; + let settings = ContainerSettings { + scripts, + ..ContainerSettings::default() + }; + session + .call(|e| save_http_settings(e, &collection_item(&id), settings)) + .unwrap(); + id } #[test] -fn a_script_before_changes_what_leaves_and_what_the_scripts_write_is_kept() { +fn what_a_script_before_changes_is_what_leaves() { let session = hosted(); - let staging = environment(&session, "Staging", false); - let (port, seen) = serve(1, |_, _| ok()); - let mut sent = request(&format!("http://127.0.0.1:{port}/{{{{path}}}}")); - sent.environment_id = Some(staging.clone()); - sent.document.scripts = scripts( + let (mut sent, seen) = scripted(scripts( "pm.variables.set('path', 'orders');\n\ - pm.request.headers.add({ key: 'X-Signed', value: 'yes' });\n\ - console.log('token', env.get('token'));", - "env.set('orderId', String(res.json().id));", - ); - let answer = session.wait(|e| send_http_request(e, sent)).unwrap(); + pm.request.headers.add({ key: 'X-Signed', value: 'yes' });", + "", + )); + sent.document.url.push_str("{{path}}"); + + send(&session, sent).unwrap(); let seen = seen.recv().unwrap(); assert!(seen.head.starts_with("GET /orders "), "{}", seen.head); assert_eq!(header_of(&seen, "X-Signed").as_deref(), Some("yes")); - assert!(answer.scripts.failure.is_none()); +} + +#[test] +fn what_a_script_writes_is_kept_in_the_active_environment() { + let session = hosted(); + let staging = environment(&session, "Staging", false); + let (mut sent, _seen) = scripted(scripts( + "env.unset('token');", + "env.set('orderId', res.json().id);", + )); + sent.environment_id = Some(staging.clone()); + + let answer = send(&session, sent).unwrap(); + + assert!(answer.scripts.wrote && answer.scripts.failure.is_none()); + let order = row_of(&session, &staging, "orderId").unwrap(); + assert_eq!(order.value, "7"); + assert_eq!(row_of(&session, &staging, "token"), None); +} + +#[test] +fn with_no_environment_chosen_a_script_writes_the_globals() { + let session = hosted(); + let (sent, _seen) = scripted(scripts("env.set('tenant', 'acme');", "")); + + let answer = send(&session, sent).unwrap(); + assert!(answer.scripts.wrote); - // A secret in force is never shown in clear, not even in what a script logged. - assert_eq!(logs(&console(&session)), ["token {{token}}"]); - let traffic: Vec = console(&session) + let globals = session.call(http_environments).unwrap().globals; + let kept = (globals[0].name.as_str(), globals[0].value.as_str()); + assert_eq!(kept, ("tenant", "acme")); +} + +#[test] +fn a_script_writes_the_globals_beside_the_active_environment() { + let session = hosted(); + let (mut sent, _seen) = scripted(scripts("pm.globals.set('g', '1');", "")); + sent.environment_id = Some(environment(&session, "Staging", false)); + + assert!(send(&session, sent).unwrap().scripts.wrote); + + let sets = session.call(http_environments).unwrap(); + assert_eq!(sets.globals[0].name, "g"); + assert_eq!(sets.environments[0].variables.len(), 1); +} + +#[test] +fn a_script_knows_which_request_it_runs_for() { + let session = hosted(); + let (mut sent, _seen) = scripted(scripts( + "console.log(pm.info.requestName, pm.info.requestId, pm.info.iteration);", + "", + )); + sent.request_id = Some("request-1".to_string()); + + send(&session, sent).unwrap(); + + assert_eq!(logs(&session), ["Ping request-1 0"]); +} + +#[test] +fn a_send_whose_scripts_write_nothing_says_so() { + let session = hosted(); + let (sent, _seen) = scripted(scripts("console.log(1);", "")); + + assert!(!send(&session, sent).unwrap().scripts.wrote); +} + +/// Not even in what a script logged. +#[test] +fn a_secret_in_force_is_never_shown_in_clear_in_the_console() { + let session = hosted(); + let (mut sent, _seen) = scripted(scripts("console.log('token', env.get('token'));", "")); + sent.environment_id = Some(environment(&session, "Staging", false)); + + send(&session, sent).unwrap(); + + assert_eq!(logs(&session), ["token {{token}}"]); +} + +#[test] +fn the_console_says_what_left_what_came_back_and_for_which_send() { + let session = hosted(); + let (sent, _seen) = scripted(scripts("console.log('before');", "console.log('after');")); + let url = sent.document.url.clone(); + + send(&session, sent).unwrap(); + + let said: Vec = console(&session) .iter() - .filter_map(|event| match &event.line { - ConsoleLine::Out { method, url, .. } => Some(format!("→ {method} {url}")), - ConsoleLine::In { status, .. } => Some(format!("← {status}")), - _ => None, + .map(|line| match line { + ConsoleLine::Out { method, url, .. } => format!("→ {method} {url}"), + ConsoleLine::In { status, .. } => format!("← {status}"), + ConsoleLine::Log { text, .. } => text.clone(), + other => format!("{other:?}"), }) .collect(); assert_eq!( - traffic, - [ - format!("→ GET http://127.0.0.1:{port}/orders"), - "← 200".to_string() - ] - ); - assert!(console(&session).iter().all(|event| event.id == "tab-1")); - let sets = session.call(http_environments).unwrap(); - let kept = sets - .environments - .iter() - .find(|environment| environment.id == staging) - .unwrap(); - assert!( - kept.variables - .iter() - .any(|variable| variable.name == "orderId" && variable.value == "7") + said, + ["before", format!("→ GET {url}").as_str(), "← 200", "after"] ); + for event in session.heard.events() { + if let EngineEvent::Console(event) = event { + assert_eq!((event.id.as_str(), event.iteration), ("tab-1", None)); + assert_eq!(event.request, "Ping"); + } + } +} + +#[test] +fn a_failed_send_is_said_in_the_console_by_its_code() { + let session = hosted(); + + send(&session, request("http://devnotes.invalid/")).unwrap_err(); + + let said = console(&session); + assert!(matches!( + said.last().unwrap(), + ConsoleLine::Failed { + code: ErrorCode::HttpUnresolved, + by: None, + .. + } + )); } #[test] fn a_script_that_throws_before_the_send_keeps_the_request_in_and_says_whose_it_is() { let session = hosted(); - let api = session.call(|e| create_http_collection(e, "API")).unwrap(); - let settings = ContainerSettings { - scripts: scripts("const a = 1;\nthrow new Error('no token');", ""), - ..ContainerSettings::default() - }; - let item = HttpItem { - kind: HttpItemKind::Collection, - id: api.id.clone(), - }; - session - .call(|e| save_http_settings(e, &item, settings)) - .unwrap(); - let (port, seen) = serve(1, |_, _| ok()); - let mut sent = request(&format!("http://127.0.0.1:{port}/")); - sent.collection_id = Some(api.id.clone()); + let throws = scripts("const a = 1;\nthrow new Error('no token');", ""); + let api = collection(&session, throws); + let (mut sent, seen) = scripted(RequestScripts::default()); + sent.collection_id = Some(api.clone()); - let error = session.wait(|e| send_http_request(e, sent)).unwrap_err(); + let error = send(&session, sent).unwrap_err(); assert_eq!(error.code, ErrorCode::HttpScript); - assert_eq!(error.params["failure"], FailureKind::Error.to_string()); - assert_eq!(error.params["level"], ScriptLevel::Collection.to_string()); - assert_eq!(error.params["name"], "API"); - assert_eq!(error.params["owner"], api.id); - assert_eq!(error.params["line"], "2"); - assert!(error.params["message"].contains("no token")); - assert!(seen.recv_timeout(Duration::from_millis(300)).is_err()); + for (name, value) in [ + ("failure", FailureKind::Error.to_string()), + ("level", ScriptLevel::Collection.to_string()), + ("name", "API".to_string()), + ("owner", api), + ("line", "2".to_string()), + ("message", "Error: no token".to_string()), + ] { + assert_eq!(error.params[name], value, "{name}"); + } + assert!(never_left(&seen)); + assert!(session.call(|e| http_history(e, 0)).unwrap().is_empty()); } #[test] -fn a_script_after_the_answer_that_fails_leaves_the_answer_shown() { +fn a_script_that_does_not_read_keeps_the_request_in() { let session = hosted(); - let api = session.call(|e| create_http_collection(e, "API")).unwrap(); - let (port, _seen) = serve(1, |_, _| ok()); - let mut sent = request(&format!("http://127.0.0.1:{port}/")); - sent.collection_id = Some(api.id.clone()); - sent.document.scripts = scripts( + let (sent, seen) = scripted(scripts("if (", "")); + + let error = send(&session, sent).unwrap_err(); + + assert_eq!(error.code, ErrorCode::HttpScript); + assert_eq!(error.params["failure"], FailureKind::Syntax.to_string()); + assert!(!error.params["message"].is_empty()); + assert!(never_left(&seen)); +} + +#[test] +fn a_script_after_the_answer_that_fails_leaves_the_answer_shown_and_keeps_what_it_wrote() { + let session = hosted(); + let api = collection(&session, RequestScripts::default()); + let (mut sent, _seen) = scripted(scripts( "", "pm.collectionVariables.set('lastId', res.json().id);\nres.json().missing.field;", - ); + )); + sent.collection_id = Some(api.clone()); - let answer = session.wait(|e| send_http_request(e, sent)).unwrap(); + let answer = send(&session, sent).unwrap(); assert_eq!(answer.status, 200); let failure = answer.scripts.failure.unwrap(); - assert_eq!(failure.kind, FailureKind::Error); + assert_eq!((failure.kind, failure.line), (FailureKind::Error, Some(2))); assert_eq!(failure.script, Some(ScriptKind::After)); assert_eq!(failure.level, Some(ScriptLevel::Request)); - assert_eq!(failure.line, Some(2)); - // What it wrote before it failed is kept. - let item = HttpItem { - kind: HttpItemKind::Collection, - id: api.id, - }; - let held = session.call(|e| http_settings(e, &item)).unwrap(); - assert_eq!(held.variables[0].name, "lastId"); - assert_eq!(held.variables[0].value, "7"); + let held = session.call(|e| http_settings(e, &collection_item(&api))); + assert!(answer.scripts.wrote); + let kept = &held.unwrap().variables[0]; + assert_eq!((kept.name.as_str(), kept.value.as_str()), ("lastId", "7")); } #[test] -fn a_protected_environment_refuses_what_the_script_made_a_change_unless_confirmed() { +fn a_protected_environment_refuses_what_a_script_made_a_change_until_confirmed() { let session = hosted(); - let production = environment(&session, "Production", true); - let (port, seen) = serve(1, |_, _| ok()); - let mut sent = request(&format!("http://127.0.0.1:{port}/")); - sent.environment_id = Some(production); - sent.document.scripts = scripts("pm.request.method = 'post';", ""); + let (mut sent, seen) = scripted(scripts("pm.request.method = 'post';", "")); + sent.environment_id = Some(environment(&session, "Production", true)); - let error = session - .wait(|e| send_http_request(e, sent.clone())) - .unwrap_err(); + let error = send(&session, sent.clone()).unwrap_err(); assert_eq!(error.code, ErrorCode::HttpScriptProtected); assert_eq!(error.params["method"], HttpMethod::Post.to_string()); assert_eq!(error.params["environment"], "Production"); - assert!(seen.recv_timeout(Duration::from_millis(300)).is_err()); + assert!(never_left(&seen)); sent.confirmed = true; - session.wait(|e| send_http_request(e, sent)).unwrap(); + send(&session, sent).unwrap(); + assert!(seen.recv().unwrap().head.starts_with("POST / ")); +} + +#[test] +fn an_environment_that_is_not_protected_lets_a_script_change_the_method() { + let session = hosted(); + let (mut sent, seen) = scripted(scripts("pm.request.method = 'post';", "")); + sent.environment_id = Some(environment(&session, "Staging", false)); + + send(&session, sent).unwrap(); + assert!(seen.recv().unwrap().head.starts_with("POST / ")); } +/// What a script sends by itself is asked about as the request is. +#[test] +fn a_protected_environment_refuses_a_change_a_script_sends_by_itself() { + let session = hosted(); + let (port, seen) = serve(2, |_, _| ok()); + let mut sent = request(&format!("http://127.0.0.1:{port}/own")); + sent.environment_id = Some(environment(&session, "Production", true)); + sent.document.scripts = scripts( + &format!("await pm.sendRequest({{ url: 'http://127.0.0.1:{port}/pay', method: 'POST' }});"), + "", + ); + + let error = send(&session, sent.clone()).unwrap_err(); + assert_eq!(error.code, ErrorCode::HttpScript); + assert!(error.params["message"].contains("protected")); + assert!(never_left(&seen)); + + sent.confirmed = true; + send(&session, sent).unwrap(); + assert!(seen.recv().unwrap().head.starts_with("POST /pay ")); +} + #[test] -fn a_script_can_skip_its_request_or_name_a_method_that_does_not_exist() { +fn a_script_s_send_goes_under_the_request_s_own_delay() { let session = hosted(); + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); let mut sent = request("http://127.0.0.1:9/"); - sent.document.scripts = scripts("pm.execution.skipRequest();", ""); - let skipped = session.wait(|e| send_http_request(e, sent.clone())); - assert_eq!(skipped.unwrap_err().code, ErrorCode::HttpScriptSkipped); + sent.document.transport.timeout_ms = Some(300); + sent.document.scripts = scripts( + &format!("await pm.sendRequest('http://127.0.0.1:{port}/silent');"), + "", + ); - sent.document.scripts = scripts("pm.request.method = 'PURGE';", ""); - let error = session.wait(|e| send_http_request(e, sent)).unwrap_err(); - assert_eq!(error.code, ErrorCode::HttpScriptMethod); - assert_eq!(error.params["method"], "PURGE"); + let error = send(&session, sent).unwrap_err(); + + let message = &error.params["message"]; + assert!(message.contains("within 300 ms"), "{message}"); } #[test] -fn with_no_environment_chosen_a_script_writes_the_globals() { +fn a_protected_environment_lets_a_request_that_changes_nothing_leave() { let session = hosted(); - let (port, _seen) = serve(1, |_, _| ok()); - let mut sent = request(&format!("http://127.0.0.1:{port}/")); - sent.document.scripts = scripts("env.set('tenant', 'acme');", ""); + let (mut sent, seen) = scripted(scripts("pm.request.headers.add('X-A: 1');", "")); + sent.environment_id = Some(environment(&session, "Production", true)); - let answer = session.wait(|e| send_http_request(e, sent)).unwrap(); + send(&session, sent).unwrap(); - assert!(answer.scripts.wrote); - let sets = session.call(http_environments).unwrap(); - assert_eq!(sets.globals[0].name, "tenant"); - assert_eq!(sets.globals[0].value, "acme"); + assert!(seen.recv().unwrap().head.starts_with("GET / ")); } #[test] -fn the_tests_run_after_the_scripts_and_say_what_was_expected_and_what_came() { +fn a_script_can_skip_its_request() { let session = hosted(); - let staging = environment(&session, "Staging", false); - let api = session.call(|e| create_http_collection(e, "API")).unwrap(); - let settings = ContainerSettings { - scripts: RequestScripts { - tests: - "test('trace', () => {\n expect(res.headers).toHaveProperty('x-request-id');\n});" - .to_string(), - ..RequestScripts::default() - }, - ..ContainerSettings::default() - }; - let item = HttpItem { - kind: HttpItemKind::Collection, - id: api.id.clone(), - }; - session - .call(|e| save_http_settings(e, &item, settings)) - .unwrap(); - let (port, _seen) = serve(1, |_, _| ok()); - let mut sent = request(&format!("http://127.0.0.1:{port}/")); - sent.collection_id = Some(api.id.clone()); - sent.environment_id = Some(staging); - sent.document.scripts = RequestScripts { - before: String::new(), - after: "pm.test('from after', () => pm.response.to.have.status(200));".to_string(), - tests: "test('status', () => {\n expect(res.status).toBe(200);\n});\n\ - pm.test('token', () => {\n pm.expect(env.get('token')).to.equal('other');\n});" - .to_string(), - }; + let (sent, seen) = scripted(scripts("pm.execution.skipRequest();", "")); + + let skipped = send(&session, sent).unwrap_err(); + + assert_eq!(skipped.code, ErrorCode::HttpScriptSkipped); + assert!(never_left(&seen)); +} + +#[test] +fn a_method_no_request_is_sent_with_is_refused_by_its_name() { + let session = hosted(); + let (sent, seen) = scripted(scripts("pm.request.method = 'PURGE';", "")); + + let error = send(&session, sent).unwrap_err(); + + assert_eq!(error.code, ErrorCode::HttpScriptMethod); + assert_eq!(error.params["method"], "PURGE"); + assert!(never_left(&seen)); +} + +/// The request's, then those of what holds it, and the tests a script after the answer wrote +/// first of all. +#[test] +fn the_tests_run_after_the_scripts_from_the_request_up() { + let session = hosted(); + let api = collection(&session, tests("test('trace', () => {});")); + let (mut sent, _seen) = scripted(RequestScripts { + after: "pm.test('from after', () => {});".to_string(), + ..tests("test('status', () => expect(res.status).toBe(404));") + }); + sent.collection_id = Some(api); - let answer = session.wait(|e| send_http_request(e, sent)).unwrap(); + let answer = send(&session, sent).unwrap(); - let tests = &answer.scripts.tests; - let names: Vec<(&str, bool)> = tests + let ran: Vec<(&str, bool)> = answer + .scripts + .tests .iter() .map(|test| (test.name.as_str(), test.passed)) .collect(); assert_eq!( - names, - [ - ("from after", true), - ("status", true), - ("token", false), - ("trace", false) - ] - ); - let token = &tests[2]; - assert_eq!(token.kind, Some(ScriptKind::Tests)); - assert_eq!(token.level, Some(ScriptLevel::Request)); - assert_eq!(token.line, Some(5)); - assert_eq!(token.expected.as_deref(), Some("\"other\"")); - // The secret it compared is never shown in clear. - assert_eq!(token.actual.as_deref(), Some("\"{{token}}\"")); - assert_eq!( - token.code.as_deref(), - Some("pm.expect(env.get('token')).to.equal('other');") + ran, + [("from after", true), ("status", false), ("trace", true)] ); - let trace = &tests[3]; - assert_eq!(trace.level, Some(ScriptLevel::Collection)); - assert_eq!(trace.holder.as_deref(), Some("API")); - assert_eq!(trace.owner.as_deref(), Some(api.id.as_str())); - assert_eq!(trace.line, Some(2)); +} +/// The secret it compared is never shown in clear. +#[test] +fn a_test_that_failed_says_where_and_hides_the_secret_it_compared() { + let session = hosted(); + let api = collection( + &session, + tests("pm.test('token', () => {\n pm.expect(env.get('token')).to.equal('other');\n});"), + ); + let (mut sent, _seen) = scripted(RequestScripts::default()); + sent.collection_id = Some(api.clone()); + sent.environment_id = Some(environment(&session, "Staging", false)); + + let answer = send(&session, sent).unwrap(); + + let code = "pm.expect(env.get('token')).to.equal('other');"; + let test = &answer.scripts.tests[0]; + let expected = TestResult { + name: "token".to_string(), + expected: Some("\"other\"".to_string()), + actual: Some("\"{{token}}\"".to_string()), + kind: Some(ScriptKind::Tests), + level: Some(ScriptLevel::Collection), + holder: Some("API".to_string()), + owner: Some(api), + line: Some(2), + code: Some(code.to_string()), + script: test.script.clone(), + message: test.message.clone(), + ..TestResult::default() + }; + assert_eq!(test, &expected); + let message = test.message.as_deref().unwrap(); + assert!(!message.contains("s3cr3t"), "{message}"); // Kept with the history entry. - let day = &session.call(|e| http_history(e, 0)).unwrap()[0]; - let entry = session - .call(|e| http_history_entry(e, &day.items[0].id.clone())) - .unwrap(); + let id = session.call(|e| http_history(e, 0)).unwrap()[0].items[0] + .id + .clone(); + let entry = session.call(|e| http_history_entry(e, &id)).unwrap(); let kept = entry.record.response.unwrap().scripts.tests; - assert_eq!(kept.len(), 4); - assert_eq!(kept[2].actual.as_deref(), Some("\"{{token}}\"")); + assert_eq!(kept, answer.scripts.tests); +} + +fn extraction(path: &str, variable: &str) -> Extraction { + Extraction { + path: path.to_string(), + variable: variable.to_string(), + secret: false, + } } #[test] -fn an_extraction_writes_the_value_after_the_scripts_and_says_which_request_filled_it() { +fn an_extraction_writes_over_what_a_script_set_and_says_which_request_filled_it() { let session = hosted(); let staging = environment(&session, "Staging", false); - let patch = EnvironmentPatch { - variables: Some(vec![ - Variable { - name: "refresh".to_string(), - value: "kept".to_string(), - ..Variable::default() - }, - Variable { - name: "accessToken".to_string(), - value: "old".to_string(), - ..Variable::default() - }, - ]), - ..EnvironmentPatch::default() - }; - session - .call(|e| save_http_environment(e, &staging, &patch)) - .unwrap(); - let (port, _seen) = serve(1, |_, _| { - response( - "200 OK", - &[("Content-Type", "application/json")], - b"{\"access_token\":\"eyJ.a.b\",\"expires_in\":3600}", - ) - }); - let mut sent = request(&format!("http://127.0.0.1:{port}/login")); + let (mut sent, _seen) = scripted(scripts("", "env.set('id', 'from-script');")); sent.environment_id = Some(staging.clone()); sent.request_id = Some("login-id".to_string()); sent.name = "Login".to_string(); - sent.document.scripts = scripts( - "", - "env.set('accessToken', 'from-script');\nconsole.log(res.json().access_token);", + sent.document.extractions = vec![extraction("body.id", " id "), extraction("body.id", " ")]; + + let answer = send(&session, sent).unwrap(); + + assert_eq!(answer.scripts.extracted.len(), 1); + assert!(answer.scripts.extracted[0].found); + let row = row_of(&session, &staging, "id").unwrap(); + assert_eq!(row.value, "7"); + let login = FilledBy { + request_id: Some("login-id".to_string()), + name: "Login".to_string(), + }; + assert_eq!(row.filled_by, Some(login)); +} + +#[test] +fn an_extraction_with_no_environment_chosen_fills_the_globals() { + let session = hosted(); + let (mut sent, _seen) = scripted(RequestScripts::default()); + sent.document.extractions = vec![extraction("body.id", "id")]; + + send(&session, sent).unwrap(); + + let globals = session.call(http_environments).unwrap().globals; + assert_eq!(globals[0].value, "7"); +} + +#[test] +fn an_extraction_whose_path_leads_nowhere_leaves_its_variable_and_says_so() { + let session = hosted(); + let staging = environment(&session, "Staging", false); + let (mut sent, _seen) = scripted(RequestScripts::default()); + sent.environment_id = Some(staging.clone()); + sent.document.extractions = vec![extraction("body.gone", "token")]; + + let answer = send(&session, sent).unwrap(); + + assert!(!answer.scripts.extracted[0].found && !answer.scripts.wrote); + let token = row_of(&session, &staging, "token").unwrap(); + assert_eq!( + (token.value.as_str(), token.filled_by), + ("s3cr3t-value", None) ); - sent.document.extractions = vec![ - Extraction { - path: "body.access_token".to_string(), - variable: "accessToken".to_string(), - secret: true, - }, - Extraction { - path: "body.refresh_token".to_string(), - variable: "refresh".to_string(), - secret: false, - }, - ]; - let answer = session.wait(|e| send_http_request(e, sent)).unwrap(); - - let found: Vec<(&str, bool)> = answer - .scripts - .extracted - .iter() - .map(|extracted| (extracted.variable.as_str(), extracted.found)) - .collect(); - assert_eq!(found, [("accessToken", true), ("refresh", false)]); - // Made a secret by the rule, it is masked in what the script logged before it. - assert_eq!(logs(&console(&session)), ["{{accessToken}}"]); - let missed = console(&session).iter().any(|event| { - matches!(&event.line, ConsoleLine::Missed { path, variable } if path == "body.refresh_token" && variable == "refresh") + let missed = ConsoleLine::Missed { + path: "body.gone".to_string(), + variable: "token".to_string(), + }; + assert!(console(&session).contains(&missed)); +} + +/// Made a secret by the rule, it is masked in what the script logged before it. +#[test] +fn a_value_extracted_as_a_secret_is_hidden_in_what_the_scripts_logged() { + let session = hosted(); + let staging = environment(&session, "Staging", false); + let (port, _seen) = serve(1, |_, _| response("200 OK", &[], b"{\"key\":\"eyJ.a.b\"}")); + let mut sent = request(&format!("http://127.0.0.1:{port}/login")); + sent.environment_id = Some(staging.clone()); + sent.document.scripts = scripts("", "console.log(res.json().key);"); + sent.document.extractions = vec![Extraction { + secret: true, + ..extraction("body.key", "accessToken") + }]; + + send(&session, sent).unwrap(); + + assert_eq!(logs(&session), ["{{accessToken}}"]); + let kept = row_of(&session, &staging, "accessToken").unwrap(); + assert_eq!(kept.kind, VariableKind::Secret); +} + +#[test] +fn a_cookie_a_script_sets_is_sent_and_kept_and_one_the_answer_sets_is_read_after() { + let session = hosted(); + let (port, seen) = serve(1, |_, _| { + response("200 OK", &[("Set-Cookie", "answered=2; Path=/")], b"") }); - assert!(missed, "the path that led nowhere said in the console"); - let sets = session.call(http_environments).unwrap(); - let rows = &sets - .environments - .iter() - .find(|environment| environment.id == staging) - .unwrap() - .variables; - let token = rows.iter().find(|row| row.name == "accessToken").unwrap(); - assert_eq!(token.value, "eyJ.a.b"); - assert_eq!(token.kind, VariableKind::Secret); - assert_eq!( - token.filled_by, - Some(FilledBy { - request_id: Some("login-id".to_string()), - name: "Login".to_string(), - }) + let url = format!("http://127.0.0.1:{port}/"); + let mut sent = request(&url); + sent.document.scripts = scripts( + &format!("pm.cookies.jar().set('{url}', 'scripted', '1');"), + &format!( + "await new Promise((done) => pm.cookies.jar().getAll('{url}', (error, all) => {{\ + console.log(all.map((cookie) => cookie.name).sort().join(' ')); done(); }}));\ + console.log(pm.cookies.get('answered'));" + ), ); - let refresh = rows.iter().find(|row| row.name == "refresh").unwrap(); - assert_eq!(refresh.value, "kept"); - assert_eq!(refresh.filled_by, None); + + send(&session, sent).unwrap(); + + let cookie = header_of(&seen.recv().unwrap(), "cookie"); + assert_eq!(cookie.as_deref(), Some("scripted=1")); + assert_eq!(logs(&session), ["answered scripted", "2"]); + let kept = &session.call(http_cookies).unwrap()[0].cookies; + assert_eq!(kept.len(), 2); +} + +#[test] +fn what_a_script_sends_is_in_the_console_under_its_name() { + let session = hosted(); + let (port, _seen) = serve(2, |_, _| ok()); + let mut sent = request(&format!("http://127.0.0.1:{port}/")); + sent.document.scripts = scripts( + &format!("await pm.sendRequest('http://127.0.0.1:{port}/login');"), + "", + ); + + send(&session, sent).unwrap(); + + let said = console(&session); + let ConsoleLine::Out { url, by, .. } = &said[0] else { + panic!("{said:?}"); + }; + assert!(url.ends_with("/login")); + let by = by.as_ref().unwrap(); + assert_eq!((by.kind, by.name.as_str()), (ScriptKind::Before, "Ping")); + assert!(matches!( + &said[1], + ConsoleLine::In { + status: 200, + by: Some(_), + .. + } + )); + assert!(matches!(&said[2], ConsoleLine::Out { by: None, .. })); +} + +/// A send whose script never ends, cancelled: its answer. +fn cancelled(session: &Session, sent: SendRequest) -> Result { + let sending = session + .runtime + .spawn(send_http_request(Arc::clone(&session.engine), sent)); + while !sending.is_finished() { + let _ = session.call(|e| cancel_http_send(e, "tab-1")).unwrap(); + std::thread::sleep(Duration::from_millis(20)); + } + session.runtime.block_on(sending).unwrap() +} + +#[test] +fn a_cancel_stops_a_script_before_the_send_and_nothing_leaves() { + let session = hosted(); + let (sent, seen) = scripted(scripts("while (true) {}", "")); + + let answer = cancelled(&session, sent); + + assert_eq!(answer.unwrap_err().code, ErrorCode::HttpCancelled); + assert!(never_left(&seen)); +} + +#[test] +fn a_scripted_send_that_ended_leaves_nothing_to_cancel() { + let session = hosted(); + let (sent, _seen) = scripted(scripts("console.log(1);", "console.log(2);")); + + send(&session, sent).unwrap(); + + assert!(!session.call(|e| cancel_http_send(e, "tab-1")).unwrap()); } /// What a send writes after its answer — its history here — cannot be kept: the answer still @@ -429,17 +726,103 @@ fn a_history_that_cannot_be_written_is_said_beside_the_answer() { .execute(connection) .unwrap(); } - let (port, _seen) = serve(1, |_, _| ok()); + let (sent, _seen) = scripted(RequestScripts::default()); - let answer = - session.wait(|e| send_http_request(e, request(&format!("http://127.0.0.1:{port}/")))); + let answer = send(&session, sent); assert!(answer.is_ok(), "{answer:?}"); - assert!( - session - .heard - .events() - .iter() - .any(|event| matches!(event, EngineEvent::SendNotKept)) + assert!(not_kept_said(&session)); +} + +#[test] +fn a_variable_that_cannot_be_written_is_said_beside_the_answer() { + let session = hosted(); + let staging = environment(&session, "Staging", false); + let (engine, gone) = (Arc::clone(&session.engine), staging.clone()); + // Deleted while the request is under way: the write has no environment to go to. + let (port, _seen) = serve(1, move |_, _| { + engine::db::run_here(&engine, |e| delete_http_environment(e, &gone)).unwrap(); + ok() + }); + let mut sent = request(&format!("http://127.0.0.1:{port}/")); + sent.environment_id = Some(staging); + sent.document.scripts = scripts("", "env.set('late', '1');"); + + let answer = send(&session, sent).unwrap(); + + assert!(!answer.scripts.wrote); + assert!(not_kept_said(&session)); +} + +#[test] +fn a_file_a_script_gives_the_request_waits_for_a_yes() { + let session = hosted(); + let folder = tempfile::tempdir().unwrap(); + let path = folder.path().join("id_ed25519"); + std::fs::write(&path, "PRIVATE KEY").unwrap(); + let path = path.to_string_lossy().into_owned(); + let (mut sent, seen) = scripted(scripts( + &format!( + "pm.request.body.update({{ mode: 'file', file: {{ src: {} }} }});", + serde_json::to_string(&path).unwrap() + ), + "", + )); + sent.method = HttpMethod::Post; + + let refused = send(&session, sent.clone()).unwrap_err(); + assert_eq!(refused.code, ErrorCode::HttpScriptFile); + assert_eq!(refused.params["path"], path); + assert!(never_left(&seen)); + + sent.files = vec![path]; + send(&session, sent).unwrap(); + assert_eq!(seen.recv().unwrap().body, b"PRIVATE KEY"); +} + +#[test] +fn a_file_a_script_sends_by_itself_leaves_once_it_is_allowed() { + let session = hosted(); + let folder = tempfile::tempdir().unwrap(); + let path = folder.path().join("scan.bin"); + std::fs::write(&path, "scan").unwrap(); + let path = path.to_string_lossy().into_owned(); + let (port, seen) = serve(2, |_, _| ok()); + let mut sent = request(&format!("http://127.0.0.1:{port}/own")); + let source = serde_json::to_string(&path).unwrap(); + sent.document.scripts = scripts( + &format!( + "await pm.sendRequest({{ url: 'http://127.0.0.1:{port}/up', method: 'POST',\ + body: {{ mode: 'file', file: {{ src: {source} }} }} }});" + ), + "", ); + + let refused = send(&session, sent.clone()).unwrap_err(); + assert_eq!(refused.code, ErrorCode::HttpScriptFile); + assert!(never_left(&seen)); + + sent.files = vec![path]; + send(&session, sent).unwrap(); + assert_eq!(seen.recv().unwrap().body, b"scan"); +} + +/// Its own rows say so: no script added it. +#[test] +fn a_file_the_request_sends_by_itself_is_not_asked_about() { + use engine::http::model::RequestBody; + + let session = hosted(); + let folder = tempfile::tempdir().unwrap(); + let path = folder.path().join("scan.bin"); + std::fs::write(&path, "scan").unwrap(); + let (mut sent, seen) = scripted(scripts("console.log('untouched');", "")); + sent.method = HttpMethod::Post; + sent.document.body = RequestBody::Binary { + path: path.to_string_lossy().into_owned(), + }; + + send(&session, sent).unwrap(); + + assert_eq!(seen.recv().unwrap().body, b"scan"); } diff --git a/crates/engine/tests/scripts.rs b/crates/engine/tests/scripts.rs index 30be39238..6e6ad1a89 100644 --- a/crates/engine/tests/scripts.rs +++ b/crates/engine/tests/scripts.rs @@ -9,43 +9,77 @@ use std::thread; use std::time::{Duration, Instant}; use engine::http::scripts::model::{ - FailureKind, Job, LayerScope, Phase, Script, ScriptKind, ScriptLayer, ScriptRequest, - ScriptResponse, + FailureKind, Job, Outcome, Phase, Script, ScriptKind, ScriptRequest, ScriptResponse, }; -use engine::http::scripts::network::Network; +use engine::http::scripts::network::{Network, cookies_for}; use engine::http::scripts::process::ScriptProcess; +use engine::http::send::SendError; use engine::http::transport::Transport; +const SECONDS: Duration = Duration::from_secs(10); + fn host() -> ScriptProcess { ScriptProcess::start_at(Path::new(env!("CARGO_BIN_EXE_script-host"))).unwrap() } -fn runtime() -> tokio::runtime::Runtime { - tokio::runtime::Builder::new_multi_thread() - .worker_threads(1) - .enable_all() - .build() - .unwrap() +/// A runtime, and what a script reaches through it: an empty jar, and everything allowed. +fn network() -> (tokio::runtime::Runtime, Network) { + let runtime = tokio::runtime::Runtime::new().unwrap(); + let network = Network::new( + runtime.handle().clone(), + Transport::default(), + Some(Vec::new()), + true, + ); + (runtime, network) } -/// Answers every connection with a login: a JSON token and a cookie. -fn serve() -> u16 { +/// Answers every connection with a token and a cookie, and keeps each request whole. +fn serve() -> (u16, Arc>>) { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let port = listener.local_addr().unwrap().port(); + let kept = Arc::new(Mutex::new(Vec::new())); + let into = Arc::clone(&kept); thread::spawn(move || { for stream in listener.incoming() { let mut stream = stream.unwrap(); + let mut request = Vec::new(); let mut buffer = [0; 8192]; - let _ = stream.read(&mut buffer); - let body = "{\"access_token\":\"eyJ.secret.token\"}"; + while let Ok(read) = stream.read(&mut buffer) { + request.extend_from_slice(&buffer[..read]); + if read == 0 || whole(&request) { + break; + } + } + let request = String::from_utf8_lossy(&request).into_owned(); + into.lock().unwrap().push(request); + let body = "{\"token\":\"eyJ.a.b\"}"; + let length = body.len(); let _ = write!( stream, - "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nSet-Cookie: sid=42; Path=/\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", - body.len() + "HTTP/1.1 200 OK\r\nSet-Cookie: sid=42; Path=/\r\n\ + Content-Length: {length}\r\nConnection: close\r\n\r\n{body}" ); } }); - port + (port, kept) +} + +/// The headers ended, and as many bytes after them as they announced. +fn whole(request: &[u8]) -> bool { + let text = String::from_utf8_lossy(request); + let Some(end) = text.find("\r\n\r\n") else { + return false; + }; + let length = text[..end] + .lines() + .find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("content-length") + .then(|| value.trim().parse::().ok())? + }) + .unwrap_or(0); + request.len() >= end + 4 + length } fn job(phase: Phase, source: &str) -> Job { @@ -53,174 +87,240 @@ fn job(phase: Phase, source: &str) -> Job { phase, scripts: vec![Script { id: "request:script".to_string(), - level: engine::http::scripts::model::ScriptLevel::Request, - kind: if phase == Phase::Before { - ScriptKind::Before - } else { - ScriptKind::Tests - }, + kind: ScriptKind::Before, name: "Login".to_string(), - owner: None, source: source.to_string(), + ..Script::default() }], request: ScriptRequest { method: "POST".to_string(), - url: "{{baseUrl}}/login".to_string(), ..ScriptRequest::default() }, - response: (phase == Phase::After).then(|| ScriptResponse { - code: 200, - reason: "OK".to_string(), - body: "{}".to_string(), - ..ScriptResponse::default() - }), - layers: vec![ScriptLayer { - scope: LayerScope::Environment, - from: "Staging".to_string(), - values: [("baseUrl".to_string(), "http://127.0.0.1".to_string())].into(), - }], + response: (phase == Phase::After).then(ScriptResponse::default), environment: Some("Staging".to_string()), ..Job::default() } } -#[test] -fn a_script_runs_in_the_host_and_its_send_is_made_by_rust_with_the_jar() { - let port = serve(); - let runtime = runtime(); - let mut network = Network::new( - runtime.handle().clone(), - Transport::default(), - Some(Vec::new()), - true, - ); - let mut host = host(); +fn run(network: &mut Network, source: &str) -> Outcome { + host().run(&job(Phase::Before, source), SECONDS, network) +} + +/// What a script wrote, name and value, where nothing stopped it. +fn written(outcome: &Outcome) -> Vec<(&str, Option<&str>)> { + assert_eq!(outcome.failure, None); + let writes = outcome.writes.iter(); + writes + .map(|write| (write.name.as_str(), write.value.as_deref())) + .collect() +} + +/// The code a refused call carries to the script, for a script that awaits it. +fn refused(network: &mut Network, call: &str) -> String { let source = format!( - "const login = await pm.sendRequest('http://127.0.0.1:{port}/login'); - env.secret('accessToken', login.json().access_token); - console.log('cookie', login.cookies.get('sid')); - pm.cookies.jar().getAll('http://127.0.0.1:{port}/', (error, all) => env.set('cookies', all.length)); - pm.variables.set('started', 'yes');" + "try {{ {call} }} catch (error) {{ env.set('code', error.code); env.set('said', error.message); }}" ); - let outcome = host.run( - &job(Phase::Before, &source), - Duration::from_secs(10), + let outcome = run(network, &source); + written(&outcome)[0].1.unwrap().to_string() +} + +#[test] +fn a_send_a_script_makes_is_sent_by_this_process_and_its_answer_read() { + let (port, kept) = serve(); + let (_runtime, mut network) = network(); + + let outcome = run( &mut network, + &format!( + "const login = await pm.sendRequest({{ url: 'http://127.0.0.1:{port}/login', method: 'post',\ + header: {{ 'X-Trace': '1' }}, body: {{ mode: 'raw', raw: 'hello' }} }});\ + env.set('token', login.json().token); env.set('code', login.code);\ + env.set('cookie', login.cookies.get('sid'));" + ), ); - assert_eq!(outcome.failure, None); - let written: Vec<(&str, Option<&str>, bool)> = outcome - .writes - .iter() - .map(|write| (write.name.as_str(), write.value.as_deref(), write.secret)) - .collect(); - assert_eq!( - written, - [ - ("accessToken", Some("eyJ.secret.token"), true), - ("cookies", Some("1"), false) - ] - ); + let expected = [ + ("token", Some("eyJ.a.b")), + ("code", Some("200")), + ("cookie", Some("42")), + ]; + assert_eq!(written(&outcome), expected); + let request = &kept.lock().unwrap()[0]; + assert!(request.starts_with("POST /login HTTP/1.1\r\n"), "{request}"); + assert!(request.to_ascii_lowercase().contains("x-trace: 1\r\n")); + assert!(request.ends_with("\r\n\r\nhello")); assert_eq!(network.sent.len(), 1); - assert_eq!(network.jar.as_ref().map(Vec::len), Some(1)); - assert_eq!(network.changes.len(), 1); - assert_eq!(network.logs[0].text, "cookie 42"); + let sent = &network.sent[0]; + assert_eq!(sent.script.as_deref(), Some("request:script")); + assert!(sent.exchange.url.ends_with("/login") && sent.started <= sent.ended); + assert!(sent.answer.is_ok()); +} - // The same host, once the request is answered: what the first phase set is still there. - let outcome = host.run( - &job( - Phase::After, - "test('kept', () => expect(pm.variables.get('started')).toBe('yes'));", +#[test] +fn a_cookie_a_script_s_send_was_given_is_in_the_jar_its_next_send_carries() { + let (port, kept) = serve(); + let (_runtime, mut network) = network(); + + let outcome = run( + &mut network, + &format!( + "await pm.sendRequest('http://127.0.0.1:{port}/a');\ + await pm.sendRequest('http://127.0.0.1:{port}/b');" ), - Duration::from_secs(10), + ); + + assert_eq!(outcome.failure, None); + let second = kept.lock().unwrap()[1].to_ascii_lowercase(); + assert!(second.contains("cookie: sid=42\r\n"), "{second}"); + assert_eq!(network.jar.as_ref().map(Vec::len), Some(1)); + assert!(!network.changes.is_empty()); +} + +#[test] +fn a_request_without_cookies_hands_its_scripts_no_jar() { + let (_runtime, mut network) = network(); + network.jar = None; + + let code = refused( &mut network, + "await new Promise((done, fail) => pm.cookies.jar().getAll('http://a.test/', (error, all) => error ? fail(error) : done(all)));", ); - assert!(outcome.tests[0].passed, "{:?}", outcome.tests); + + assert_eq!(code, "httpScriptNoJar"); + assert!(cookies_for(None, "http://a.test/").is_empty()); } +/// Each call as Postman spells it, on the URL it names alone. #[test] -fn a_protected_environment_lets_a_script_read_but_not_change_unless_confirmed() { - let port = serve(); - let runtime = runtime(); - let mut network = Network::new(runtime.handle().clone(), Transport::default(), None, false); - let source = format!( - "await pm.sendRequest('http://127.0.0.1:{port}/read'); - await pm.sendRequest({{ url: 'http://127.0.0.1:{port}/pay', method: 'POST' }});" +fn a_script_gets_sets_removes_and_clears_the_cookies_of_a_url() { + let (_runtime, mut network) = network(); + + let outcome = run( + &mut network, + "const jar = pm.cookies.jar();\ + const say = (name) => (error, value) => env.set(name, error ? error.message : value);\ + jar.set('http://a.test/', 'one', '1');\ + jar.set('http://a.test/', { name: 'two', value: '2', path: '/in', httpOnly: true, secure: false });\ + jar.set('http://b.test/', 'other', '3');\ + jar.get('http://a.test/', 'one', say('one'));\ + jar.getAll('http://a.test/in', (error, all) => env.set('all', all.map((c) => c.name + c.path + c.httpOnly).sort().join(' ')));\ + jar.unset('http://a.test/in', 'two');\ + jar.get('http://a.test/in', 'two', (error, value) => env.set('two', String(value)));\ + jar.clear('http://a.test/');\ + jar.get('http://a.test/', 'one', (error, value) => env.set('cleared', String(value)));\ + jar.get('http://b.test/', 'other', say('other'));", ); - let outcome = host().run( - &job(Phase::Before, &source), - Duration::from_secs(10), + + let expected = [ + ("one", Some("1")), + ("all", Some("one/false two/intrue")), + ("two", Some("null")), + ("cleared", Some("null")), + ("other", Some("3")), + ]; + assert_eq!(written(&outcome), expected); + let left: Vec<_> = network + .jar + .unwrap() + .into_iter() + .map(|cookie| cookie.name) + .collect(); + assert_eq!(left, ["other"]); +} + +#[test] +fn a_cookie_a_script_sets_keeps_its_expiry_and_its_flags() { + let (_runtime, mut network) = network(); + + run( &mut network, + "pm.cookies.jar().set('https://shop.example.com/', { name: 'a', value: '1', domain: 'example.com', secure: true,\ + expires: 'Wed, 21 Oct 2099 07:28:00 GMT' });", ); - let failure = outcome.failure.unwrap(); - assert_eq!(failure.kind, FailureKind::Error); - assert_eq!(failure.line, Some(2)); - assert!(failure.message.contains("protected"), "{}", failure.message); - assert_eq!(network.sent.len(), 1, "the GET left, the POST did not"); + + let jar = network.jar.unwrap(); + assert!(jar[0].secure && !jar[0].host_only); + assert_eq!(jar[0].domain, "example.com"); + assert_eq!(jar[0].expires.unwrap().timestamp(), 4_096_250_880); } #[test] -fn an_endless_loop_is_stopped_at_its_deadline_and_the_host_is_not_given_another_phase() { - let runtime = runtime(); - let mut network = Network::new(runtime.handle().clone(), Transport::default(), None, true); - let mut host = host(); - let started = Instant::now(); - let outcome = host.run( - &job(Phase::Before, "while (true) {}"), - Duration::from_millis(500), +fn a_jar_is_asked_by_a_url() { + let (_runtime, mut network) = network(); + + let outcome = run( &mut network, + "pm.cookies.jar().get('not a url', 'a', (error) => env.set('said', error.message));", ); - assert_eq!(outcome.failure.unwrap().kind, FailureKind::Timeout); - assert!(started.elapsed() < Duration::from_secs(4)); - let outcome = host.run(&job(Phase::After, ""), Duration::from_secs(5), &mut network); - assert_eq!(outcome.failure.unwrap().kind, FailureKind::Host); + assert_eq!( + written(&outcome), + [("said", Some("not a url is not a URL"))] + ); + assert!(cookies_for(network.jar.as_deref(), "not a url").is_empty()); } -/// Answers every connection with a 200, and keeps each request whole, headers and body. -fn serve_keeping() -> (u16, Arc>>) { - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let port = listener.local_addr().unwrap().port(); - let kept = Arc::new(Mutex::new(Vec::new())); - let into = Arc::clone(&kept); - thread::spawn(move || { - for stream in listener.incoming() { - let mut stream = stream.unwrap(); - let mut request = Vec::new(); - let mut buffer = [0; 8192]; - while let Ok(read) = stream.read(&mut buffer) { - request.extend_from_slice(&buffer[..read]); - if read == 0 || whole(&request) { - break; - } - } - into.lock() - .unwrap() - .push(String::from_utf8_lossy(&request).into_owned()); - let _ = write!( - stream, - "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok" - ); - } - }); - (port, kept) +#[test] +fn a_protected_environment_lets_a_script_read_but_not_change_unless_confirmed() { + let (port, kept) = serve(); + let runtime = tokio::runtime::Runtime::new().unwrap(); + let handle = runtime.handle().clone(); + let mut protected = Network::new(handle, Transport::default(), None, false); + let source = format!( + "await pm.sendRequest('http://127.0.0.1:{port}/read');\n\ + await pm.sendRequest({{ url: 'http://127.0.0.1:{port}/pay', method: 'POST' }});" + ); + + let refused = run(&mut protected, &source).failure.unwrap(); + assert_eq!((refused.kind, refused.line), (FailureKind::Error, Some(2))); + assert!(refused.message.contains("protected"), "{}", refused.message); + assert_eq!( + kept.lock().unwrap().len(), + 1, + "the GET left, the POST did not" + ); + + let (_runtime, mut confirmed) = network(); + assert_eq!(run(&mut confirmed, &source).failure, None); + assert_eq!(kept.lock().unwrap().len(), 3); } -/// The headers ended, and as many bytes after them as they announced. -fn whole(request: &[u8]) -> bool { - let text = String::from_utf8_lossy(request); - let Some(end) = text.find("\r\n\r\n") else { - return false; - }; - let length = text[..end] - .lines() - .find_map(|line| { - let (name, value) = line.split_once(':')?; - name.eq_ignore_ascii_case("content-length") - .then(|| value.trim().parse::().ok())? - }) - .unwrap_or(0); - request.len() >= end + 4 + length +#[test] +fn a_send_that_cannot_be_made_carries_its_code_to_the_script() { + let closed = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = closed.local_addr().unwrap().port(); + drop(closed); + let (_runtime, mut network) = network(); + let cases = [ + ( + "{ url: 'http://a.test', method: 'PURGE' }".to_string(), + "httpScriptMethod", + ), + ("'ftp://a.test'".to_string(), "httpScriptSend"), + (format!("'http://127.0.0.1:{port}/'"), "httpScriptSend"), + ]; + + for (asked, expected) in cases { + let code = refused(&mut network, &format!("await pm.sendRequest({asked});")); + assert_eq!(code, expected, "{asked}"); + } + // The one that left is in the console, with how it failed. + assert_eq!(network.sent.len(), 1); + assert!(matches!(network.sent[0].answer, Err(SendError::Refused(_)))); +} + +#[test] +fn a_protected_environment_is_said_to_the_script_by_its_code() { + let runtime = tokio::runtime::Runtime::new().unwrap(); + let handle = runtime.handle().clone(); + let mut protected = Network::new(handle, Transport::default(), None, false); + + let code = refused( + &mut protected, + "await pm.sendRequest({ url: 'http://a.test', method: 'DELETE' });", + ); + + assert_eq!(code, "httpScriptProtected"); } /// A file outside any profile, standing for a private key. @@ -233,88 +333,93 @@ fn secret_file() -> (tempfile::TempDir, String) { #[test] fn a_script_sending_a_file_by_itself_waits_for_a_yes() { - let (port, kept) = serve_keeping(); + let (port, kept) = serve(); let (_folder, path) = secret_file(); - let runtime = runtime(); - let mut network = Network::new(runtime.handle().clone(), Transport::default(), None, true); - let source = format!( - "await pm.sendRequest({{ url: 'http://127.0.0.1:{port}/upload', method: 'POST', + let (_runtime, mut network) = network(); + let send = format!( + "await pm.sendRequest({{ url: 'http://127.0.0.1:{port}/upload', method: 'POST',\ body: {{ mode: 'file', file: {{ src: {} }} }} }});", serde_json::to_string(&path).unwrap() ); - let refused = host().run( - &job(Phase::Before, &source), - Duration::from_secs(10), - &mut network, - ); - + assert_eq!(refused(&mut network, &send), "httpScriptFile"); assert!(kept.lock().unwrap().is_empty()); - assert_eq!(refused.failure.unwrap().kind, FailureKind::Error); assert_eq!(network.refused_file.as_deref(), Some(path.as_str())); network.files.push(path); - let sent = host().run( - &job(Phase::Before, &source), - Duration::from_secs(10), - &mut network, - ); - assert_eq!(sent.failure, None); + assert_eq!(run(&mut network, &send).failure, None); assert!(kept.lock().unwrap()[0].ends_with("PRIVATE KEY 7f3a9c")); } #[test] -fn a_script_giving_the_request_a_file_body_waits_for_a_yes() { - let (port, kept) = serve_keeping(); - let (_folder, path) = secret_file(); - let profile = tempfile::tempdir().unwrap(); - engine::http::scripts::process::host_from(env!("CARGO_BIN_EXE_script-host").into()); - let runtime = runtime(); - let paths = engine::Paths { - profile: profile.path().to_path_buf(), - }; - let sink = Arc::new(engine::RecordingSink::default()); - let core = Arc::new(engine::Engine::new(paths, sink, runtime.handle().clone())); - engine::db::run_here(&core, |core| { - let phrase = engine::vault::secret("correct horse battery staple".to_owned()); - engine::vault::create_vault(core, phrase) - }) - .unwrap(); - let mut document = engine::http::model::RequestDocument { - url: format!("http://127.0.0.1:{port}/upload"), - ..Default::default() - }; - document.scripts.before = format!( - "pm.request.body.update({{ mode: 'file', file: {{ src: {} }} }});", - serde_json::to_string(&path).unwrap() +fn what_a_script_logs_is_kept_with_when_it_said_it() { + let (_runtime, mut network) = network(); + let before = chrono::Utc::now(); + + run(&mut network, "console.warn('said', 1);"); + + let log = &network.logs[0]; + assert_eq!( + (log.text.as_str(), log.script.as_deref()), + ("said 1", Some("request:script")) ); - let request = |files: Vec| engine::http::send::SendRequest { - id: "send-1".to_owned(), - kind: engine::http::model::RequestKind::Http, - method: engine::http::model::HttpMethod::Post, - document: document.clone(), - collection_id: None, - folder_id: None, - name: "Upload".to_owned(), - request_id: None, - environment_id: None, - confirmed: false, - files, - }; - let send = |files| { - runtime.block_on(engine::http::send_http_request( - Arc::clone(&core), - request(files), - )) - }; + assert!(log.at.unwrap() >= before); +} - let refused = send(Vec::new()).unwrap_err(); - assert!(kept.lock().unwrap().is_empty()); - assert_eq!(refused.code, engine::error::ErrorCode::HttpScriptFile); - assert_eq!(refused.params["path"], path); +/// The same host, once the request is answered. +#[test] +fn what_the_phase_before_left_is_there_for_the_one_after() { + let (_runtime, mut network) = network(); + let mut host = host(); + let before = job(Phase::Before, "pm.variables.set('started', 'yes');"); + let after = job( + Phase::After, + "env.set('kept', pm.variables.get('started'));", + ); - send(vec![path]).unwrap(); - assert!(kept.lock().unwrap()[0].ends_with("PRIVATE KEY 7f3a9c")); + host.run(&before, SECONDS, &mut network); + let outcome = host.run(&after, SECONDS, &mut network); + + assert_eq!(written(&outcome), [("kept", Some("yes"))]); +} + +#[test] +fn an_endless_loop_is_stopped_at_its_deadline_and_the_host_is_not_given_another_phase() { + let (_runtime, mut network) = network(); + let mut host = host(); + let started = Instant::now(); + let endless = job(Phase::Before, "while (true) {}"); + + let outcome = host.run(&endless, Duration::from_millis(500), &mut network); + assert_eq!(outcome.failure.unwrap().kind, FailureKind::Timeout); + assert!(started.elapsed() < Duration::from_secs(4)); + + let outcome = host.run(&job(Phase::After, ""), SECONDS, &mut network); + assert_eq!(outcome.failure.unwrap().kind, FailureKind::Host); +} + +#[test] +fn a_host_killed_from_another_thread_ends_its_phase_at_once() { + let (_runtime, mut network) = network(); + let mut host = host(); + let killer = host.killer(); + assert!(!killer.killed()); + let killing = killer.clone(); + thread::spawn(move || { + thread::sleep(Duration::from_millis(300)); + killing.kill(); + }); + let started = Instant::now(); + + let outcome = host.run( + &job(Phase::Before, "while (true) {}"), + SECONDS, + &mut network, + ); + + assert_eq!(outcome.failure.unwrap().kind, FailureKind::Host); + assert!(started.elapsed() < Duration::from_secs(5)); + assert!(killer.killed()); } #[test] From 71de85191902609188c9f7b283dd6c73748117e4 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 07:37:44 +0100 Subject: [PATCH 51/95] Request scripts: a URL no script changes leaves as typed (#1768) Co-authored-by: Claude Opus 5.5 --- crates/engine/src/http/scripts/engine.rs | 22 ++++++++++++++++++++++ crates/engine/src/http/scripts/prelude.js | 4 +++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/http/scripts/engine.rs b/crates/engine/src/http/scripts/engine.rs index ac3df5fd8..b9ca95188 100644 --- a/crates/engine/src/http/scripts/engine.rs +++ b/crates/engine/src/http/scripts/engine.rs @@ -484,6 +484,28 @@ mod tests { }); } + /// Any script rewrote it: `?flag` left as `?flag=` (#1766). + #[test] + fn a_url_no_script_changes_comes_back_as_typed() { + hosted(|| { + let (engine, _) = engine(); + for url in [ + "{{baseUrl}}/pay", + "https://user:pw@shop.test:8443/a/b/?x=1&y=#top", + "https://shop.test/a?flag", + "https://shop.test/a?flag&x=1", + "https://shop.test/a?x=1&", + "https://shop.test//a//b", + "shop.test/", + "http://[::1]:8080/a", + ] { + let mut job = before(""); + job.request.url = url.to_string(); + assert_eq!(engine.run(&job, SECOND).request.unwrap().url, url); + } + }); + } + #[test] fn env_writes_the_active_environment_and_with_none_the_globals() { hosted(|| { diff --git a/crates/engine/src/http/scripts/prelude.js b/crates/engine/src/http/scripts/prelude.js index 22c36359c..dcb74ab94 100644 --- a/crates/engine/src/http/scripts/prelude.js +++ b/crates/engine/src/http/scripts/prelude.js @@ -511,7 +511,9 @@ this.path = parts[5] ? parts[5].replace(/^\//, '').split('/') : []; this._trailing = parts[5] !== undefined && parts[5].endsWith('/') && parts[5] !== '/'; this._rootOnly = parts[5] === '/'; - this.query = new PropertyList(queryRows(parts[6]), false); + this.query = new PropertyList([], false); + // As read: a pair with no `=` has no value, where a list's row is given an empty one. + this.query._rows = queryRows(parts[6]); this.hash = parts[7]; } getHost() { From 510e95b683af840f069f55e9041ff7fd3825df76 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 07:37:54 +0100 Subject: [PATCH 52/95] Tools: unit tests completed for generators, keys and identities (#1782) * tools generators gaps * Tools, generators and identity: gaps --- crates/engine/src/tools/checks.rs | 111 ++++++++++ crates/engine/src/tools/generate.rs | 129 ++++++++++++ crates/engine/src/tools/generate/lorem.rs | 35 ++++ crates/engine/src/tools/generate/schema.rs | 211 ++++++++++++++++++++ crates/engine/src/tools/hash.rs | 8 + crates/engine/src/tools/identifiers.rs | 68 +++++++ crates/engine/src/tools/identity.rs | 32 +++ crates/engine/src/tools/identity/data.rs | 21 ++ crates/engine/src/tools/identity/numbers.rs | 17 ++ crates/engine/src/tools/identity/papers.rs | 66 ++++++ crates/engine/src/tools/jwt.rs | 76 +++++++ crates/engine/src/tools/random.rs | 41 ++++ 12 files changed, 815 insertions(+) diff --git a/crates/engine/src/tools/checks.rs b/crates/engine/src/tools/checks.rs index ec4016a94..9c7e37b04 100644 --- a/crates/engine/src/tools/checks.rs +++ b/crates/engine/src/tools/checks.rs @@ -712,4 +712,115 @@ mod tests { assert_eq!(ask("FR76 30*0"), CheckAnswer::Unreadable { at: 8 }); assert_eq!(ask("FR76"), CheckAnswer::TooShort); } + + /// By the prefix its issuers are given and a length it issues. + #[test] + fn a_network_is_known_by_its_prefix_and_its_length() { + use CardNetwork as Network; + for (prefix, length, network) in [ + ("34", 15, Some(Network::AmericanExpress)), + ("37", 15, Some(Network::AmericanExpress)), + ("35", 15, None), + ("34", 16, None), + ("51", 16, Some(Network::Mastercard)), + ("55", 16, Some(Network::Mastercard)), + ("2221", 16, Some(Network::Mastercard)), + ("2720", 16, Some(Network::Mastercard)), + ("2721", 16, None), + ("4", 13, Some(Network::Visa)), + ("4", 14, None), + ("6011", 16, Some(Network::Discover)), + ("644", 16, Some(Network::Discover)), + ("649", 16, Some(Network::Discover)), + ("65", 16, Some(Network::Discover)), + ("3528", 16, Some(Network::Jcb)), + ("300", 14, Some(Network::DinersClub)), + ("305", 14, Some(Network::DinersClub)), + ("306", 14, None), + ("36", 14, Some(Network::DinersClub)), + ("38", 14, Some(Network::DinersClub)), + ("39", 14, Some(Network::DinersClub)), + ("62", 16, Some(Network::UnionPay)), + ("50", 12, Some(Network::Maestro)), + ("56", 12, Some(Network::Maestro)), + ("69", 19, Some(Network::Maestro)), + ("9", 16, None), + ("", 0, None), + ] { + let number = format!("{prefix:0 = + (0..200).map(|_| draw.between(-1, 1)).collect(); + + assert_eq!(drawn, [-1, 0, 1].into()); + assert_eq!((draw.between(5, 5), draw.between(5, 1)), (5, 5)); + assert!(!draw.chance(0.0) && draw.chance(1.0)); + } + + /// FNV-1a's published value. + #[test] + fn a_word_s_seed_is_its_hash() { + assert_eq!( + (fnv1a(""), fnv1a("a"), seed_of("7"), seed_of("a")), + (0x811c_9dc5, 0xe40c_292c, 7, 0xe40c_292c) + ); + } + + #[test] + fn a_text_is_of_the_kind_it_reads_as() { + for (example, kind) in [ + ("01922b6e-4b30-7cc4-9a5c-6f2d8e1b3a77", TextKind::Uuid), + ("2026-01-02T03:04:05Z", TextKind::DateTime), + ("2026-01-02", TextKind::Date), + ("http://a", TextKind::Uri), + ("https://a", TextKind::Uri), + ("ftp://a", TextKind::Words), + ("ada@exemple.fr", TextKind::Email), + ("ada@exemple", TextKind::Words), + ("exemple.fr", TextKind::Words), + ("10.0.0.1", TextKind::Ipv4), + ("10.0.0.256", TextKind::Words), + ("", TextKind::Words), + ] { + assert_eq!(kind_of(example), kind, "{example}"); + } + } + + fn drawn_like(example: &Value) -> Vec { + (0..40) + .map(|seed| like(example, &mut Draw::new(seed))) + .collect() + } + + /// A list of about as many items, never none; an empty one stays so. + #[test] + fn a_list_drawn_is_about_as_long() { + let lengths = |items: usize| -> std::collections::BTreeSet { + let example = Value::from(vec![1; items]); + drawn_like(&example) + .iter() + .map(|drawn| drawn.as_array().unwrap().len()) + .collect() + }; + + assert_eq!(lengths(0), [0].into()); + assert_eq!(lengths(1), [1, 2, 3].into()); + assert_eq!(lengths(4), [3, 4, 5].into()); + } + + /// Of the same sign, and no more than twice as large — ten at least. + #[test] + fn a_number_drawn_is_of_the_same_sign_and_size() { + let range = |example: Value| { + let drawn: Vec = drawn_like(&example) + .iter() + .map(|value| value.as_f64().unwrap()) + .collect(); + ( + drawn.iter().copied().fold(f64::MAX, f64::min), + drawn.iter().copied().fold(f64::MIN, f64::max), + ) + }; + for (example, low, high) in [ + (Value::from(100), 0.0, 200.0), + (Value::from(-100), -200.0, 0.0), + (Value::from(0), 0.0, 20.0), + (Value::from(1.5), 0.0, 3.0), + (Value::from(-1.5), -3.0, 0.0), + (Value::from(0.0), 0.0, 2.0), + ] { + let (least, most) = range(example.clone()); + assert!( + least >= low && most <= high && least < most, + "{example}: {least}..{most}" + ); + } + } + + #[test] + fn both_booleans_are_drawn_and_a_capital_is_kept() { + let drawn = drawn_like(&Value::Bool(true)); + assert!(drawn.contains(&Value::Bool(true)) && drawn.contains(&Value::Bool(false))); + + let capitals = |text: &str| { + drawn_like(&Value::from(text)) + .iter() + .filter(|drawn| drawn.as_str().unwrap().starts_with(char::is_uppercase)) + .count() + }; + assert_eq!( + ( + capitals("Two words"), + capitals("two words"), + capitals("ADA@exemple.fr") + ), + (40, 0, 0) + ); + } } diff --git a/crates/engine/src/tools/generate/lorem.rs b/crates/engine/src/tools/generate/lorem.rs index 6c7c7450a..996980157 100644 --- a/crates/engine/src/tools/generate/lorem.rs +++ b/crates/engine/src/tools/generate/lorem.rs @@ -266,4 +266,39 @@ mod tests { }); assert_eq!((words.count, words.at_most), (1, MAX_WORDS)); } + + /// Past eight words, one after the third, the fourth or the fifth; the opening has its own. + #[test] + fn a_long_sentence_takes_a_comma_and_a_short_one_none() { + let sentences: Vec = (0..300) + .map(|seed| sentence(&mut Draw::new(seed), false)) + .collect(); + let (mut short, mut long) = (0, 0); + for sentence in &sentences { + let words: Vec<&str> = sentence.split(' ').collect(); + let comma = words.iter().position(|word| word.ends_with(',')); + assert!((6..=14).contains(&words.len()), "{sentence}"); + if words.len() > 8 { + assert!(comma.is_some_and(|at| (3..=5).contains(&at)), "{sentence}"); + long += 1; + } else { + assert_eq!(comma, None, "{sentence}"); + short += 1; + } + assert!(!sentence.contains(",,")); + } + assert!(short > 0 && long > 0); + } + + /// Asked for, it opens the first sentence of the first paragraph, and no other. + #[test] + fn the_classic_opens_the_first_block_alone_and_only_when_asked() { + let opens = |text: &str| text.matches("Lorem ipsum dolor sit amet").count(); + for unit in [LoremUnit::Sentences, LoremUnit::Paragraphs] { + let asked = text(unit, 4, true); + assert_eq!(opens(&asked), 1, "{asked}"); + assert!(asked.starts_with("Lorem ipsum")); + assert_eq!(opens(&text(unit, 4, false)), 0); + } + } } diff --git a/crates/engine/src/tools/generate/schema.rs b/crates/engine/src/tools/generate/schema.rs index d04019101..767ad4855 100644 --- a/crates/engine/src/tools/generate/schema.rs +++ b/crates/engine/src/tools/generate/schema.rs @@ -533,4 +533,215 @@ mod tests { .is_object() ); } + + /// A key that is a keyword **and** holds what that keyword holds. + #[test] + fn a_keyword_says_schema_by_what_it_holds() { + use serde_json::json; + for (key, value, says) in [ + ("$ref", json!("#/a"), true), + ("$ref", json!(1), false), + ("type", json!("string"), true), + ("type", json!("user"), false), + ("type", json!(["string", "null"]), true), + ("type", json!(["string", "user"]), false), + ("type", json!([]), false), + ("type", json!([1]), false), + ("type", json!(1), false), + ("properties", json!({ "a": {} }), true), + ("properties", json!({ "a": true }), true), + ("properties", json!({ "a": 1 }), false), + ("properties", json!([]), false), + ("items", json!({}), true), + ("items", json!(false), true), + ("items", json!([{}]), false), + ("enum", json!([1]), true), + ("enum", json!(1), false), + ("oneOf", json!([{}, true]), true), + ("oneOf", json!([{}, 1]), false), + ("oneOf", json!([]), false), + ("required", json!(["a"]), true), + ("required", json!([1]), false), + ("required", json!(true), false), + ("name", json!("string"), false), + ] { + assert_eq!(says_schema(key, &value), says, "{key}: {value}"); + } + } + + fn drawn(schema: &serde_json::Value) -> Vec { + let answer = generate(&GenerateRequest { + source: JsonSource::Schema, + text: schema.to_string(), + count: 40, + seed: Some("1".to_owned()), + }); + match answer { + GenerateAnswer::Generated { text, .. } => serde_json::from_str(&text).unwrap(), + other => panic!("{other:?}"), + } + } + + /// The type asked for, one of several when a list is; otherwise what the keywords imply. + #[test] + fn a_value_is_of_the_type_its_schema_says_or_implies() { + use serde_json::json; + let kinds = |schema: serde_json::Value| -> std::collections::BTreeSet<&'static str> { + let of = |value: &Value| match value { + Value::Null => "null", + Value::Bool(_) => "boolean", + Value::Number(_) => "number", + Value::String(_) => "string", + Value::Array(_) => "array", + Value::Object(_) => "object", + }; + drawn(&schema).iter().map(of).collect() + }; + for (schema, expected) in [ + (json!({ "type": "boolean" }), vec!["boolean"]), + ( + json!({ "type": ["null", "integer"] }), + vec!["null", "number"], + ), + (json!({ "type": [], "minLength": 1 }), vec!["string"]), + (json!({ "properties": { "a": true } }), vec!["object"]), + (json!({ "items": { "type": "null" } }), vec!["array"]), + (json!({ "minimum": 1 }), vec!["number"]), + (json!({ "maximum": 1 }), vec!["number"]), + (json!({ "minLength": 1 }), vec!["string"]), + (json!({ "enum": [1, "a"] }), vec!["number", "string"]), + (json!({ "const": null }), vec!["null"]), + ( + json!({ "anyOf": [{ "type": "null" }, { "type": "boolean" }] }), + vec!["boolean", "null"], + ), + ] { + assert_eq!( + kinds(schema.clone()), + expected.into_iter().collect(), + "{schema}" + ); + } + } + + /// `true` takes anything, `false` nothing. + #[test] + fn a_schema_that_is_a_boolean_draws_a_text_or_nothing() { + let schema = serde_json::json!({ + "type": "object", + "required": ["any", "none"], + "properties": { "any": true, "none": false }, + }); + + assert!( + drawn(&schema) + .iter() + .all(|document| document["any"].is_string() && document["none"].is_null()) + ); + } + + #[test] + fn a_list_is_as_long_as_its_bounds_say() { + let lengths = |bounds: serde_json::Value| -> std::collections::BTreeSet { + let mut schema = serde_json::json!({ "type": "array", "items": { "type": "null" } }); + schema + .as_object_mut() + .unwrap() + .extend(bounds.as_object().unwrap().clone()); + drawn(&schema) + .iter() + .map(|list| list.as_array().unwrap().len()) + .collect() + }; + + assert_eq!(lengths(serde_json::json!({})), [1, 2, 3].into()); + assert_eq!( + lengths(serde_json::json!({ "minItems": 2, "maxItems": 3 })), + [2, 3].into() + ); + assert_eq!( + lengths(serde_json::json!({ "minItems": 4 })), + [4, 5, 6].into() + ); + assert_eq!( + lengths(serde_json::json!({ "minItems": 0, "maxItems": 0 })), + [0].into() + ); + assert!( + lengths(serde_json::json!({ "minItems": 1, "maxItems": 90 })) + .iter() + .all(|length| *length <= 11) + ); + } + + /// No space left at its end where it was cut. + #[test] + fn a_text_is_as_long_as_its_bounds_say() { + for (low, high) in [(0, 5), (30, 31), (12, 12)] { + let schema = + serde_json::json!({ "type": "string", "minLength": low, "maxLength": high }); + for document in drawn(&schema) { + let text = document.as_str().unwrap(); + assert!(text.chars().count() <= high, "{text:?}"); + assert_eq!(text, text.trim_end()); + } + } + let long = serde_json::json!({ "type": "string", "minLength": 30 }); + assert!( + drawn(&long) + .iter() + .all(|document| document.as_str().unwrap().chars().count() >= 30) + ); + } + + #[test] + fn a_bound_at_its_cap_is_honoured_and_not_said() { + let unsupported = |schema: serde_json::Value| { + let answer = generate(&GenerateRequest { + source: JsonSource::Schema, + text: schema.to_string(), + count: 1, + seed: Some("1".to_owned()), + }); + match answer { + GenerateAnswer::Generated { unsupported, .. } => unsupported.len(), + other => panic!("{other:?}"), + } + }; + let list = |items: usize| serde_json::json!({ "type": "array", "items": { "type": "null" }, "minItems": items }); + let word = |length: usize| serde_json::json!({ "type": "string", "minLength": length }); + + assert_eq!( + ( + unsupported(list(MAX_ITEMS)), + unsupported(list(MAX_ITEMS + 1)) + ), + (0, 1) + ); + assert_eq!( + ( + unsupported(word(MAX_LENGTH)), + unsupported(word(MAX_LENGTH + 1)) + ), + (0, 1) + ); + } + + /// A value past the depth is drawn as nothing rather than refused. + #[test] + fn a_schema_is_drawn_down_to_its_depth() { + let nested = |levels: usize| { + (0..levels).fold(serde_json::json!({ "const": 1 }), |inner, _| serde_json::json!({ "type": "array", "minItems": 1, "maxItems": 1, "items": inner })) + }; + let deepest = |levels: usize| { + let mut value = drawn(&nested(levels)).remove(0); + while let Value::Array(mut items) = value { + value = items.remove(0); + } + value + }; + + assert_eq!(deepest(MAX_DEPTH), serde_json::json!(1)); + assert_eq!(deepest(MAX_DEPTH + 1), Value::Null); + } } diff --git a/crates/engine/src/tools/hash.rs b/crates/engine/src/tools/hash.rs index 5549f68ec..9d3e7d1da 100644 --- a/crates/engine/src/tools/hash.rs +++ b/crates/engine/src/tools/hash.rs @@ -717,4 +717,12 @@ mod tests { } ); } + + /// Blanks alone are no digest of any length. + #[test] + fn blanks_have_no_shape() { + for expected in ["", " ", ":", "="] { + assert_eq!(shaped(expected), DigestShape::Unknown, "{expected:?}"); + } + } } diff --git a/crates/engine/src/tools/identifiers.rs b/crates/engine/src/tools/identifiers.rs index 91278b3c3..834fc189a 100644 --- a/crates/engine/src/tools/identifiers.rs +++ b/crates/engine/src/tools/identifiers.rs @@ -726,4 +726,72 @@ mod tests { MAX_IDENTIFIERS as usize ); } + + #[test] + fn no_identifier_drawn_comes_twice() { + for kind in [ + IdKind::UuidV4, + IdKind::UuidV7, + IdKind::Ulid, + IdKind::NanoId, + IdKind::Cuid2, + IdKind::ObjectId, + IdKind::Ksuid, + ] { + let ids = drawn(kind, 50); + let distinct: std::collections::BTreeSet<&String> = ids.iter().collect(); + assert_eq!(distinct.len(), 50, "{kind:?}"); + } + } + + /// Each shape with one thing wrong about it is no longer it. + #[test] + fn an_identifier_is_known_by_its_length_and_its_alphabet() { + let kind = |text: &str| match inspect(text) { + IdInspection::Uuid { .. } => "uuid", + IdInspection::Ulid { .. } => "ulid", + IdInspection::ObjectId { .. } => "objectId", + IdInspection::Ksuid { .. } => "ksuid", + IdInspection::CuidV1 { .. } => "cuid", + IdInspection::OutOfRange { .. } => "outOfRange", + IdInspection::Possible { .. } => "possible", + IdInspection::Unrecognised => "unrecognised", + }; + for (text, expected) in [ + ("01ARZ3NDEKTSV4RRFFQ69G5FAV", "ulid"), + ("7ZZZZZZZZZTSV4RRFFQ69G5FAV", "ulid"), + ("8ZZZZZZZZZTSV4RRFFQ69G5FAV", "outOfRange"), + ("01ARZ3NDEKTSV4RRFFQ69G5FA!", "unrecognised"), + ("507f1f77bcf86cd799439011", "objectId"), + ("507f1f77bcf86cd79943901!", "unrecognised"), + ("0ujtsYcgvSTl8PAuAdqWYSMnLOv", "ksuid"), + ("0ujtsYcgvSTl8PAuAdqWYSMnLO!", "unrecognised"), + ("cjld2cjxh0000qzrmn831i7rn", "cuid"), + ("djld2cjxh0000qzrmn831i7rn", "possible"), + ("cjld2cjxh0000qzrmn831i7r!", "unrecognised"), + ] { + assert_eq!(kind(text), expected, "{text}"); + } + } + + #[test] + fn what_could_be_several_kinds_says_each() { + let possible = |text: &str| match inspect(text) { + IdInspection::Possible { kinds } => kinds, + _ => Vec::new(), + }; + + let cuid2 = "t".repeat(CUID2_LENGTH); + assert_eq!(possible(&cuid2), [IdKind::Cuid2, IdKind::NanoId]); + assert_eq!(possible(&format!("1{}", &cuid2[1..])), [IdKind::NanoId]); + assert_eq!( + possible(&format!("t{}", "T".repeat(CUID2_LENGTH - 1))), + [IdKind::NanoId] + ); + assert_eq!(possible(&"a".repeat(8)), [IdKind::NanoId]); + assert!(possible(&"a".repeat(7)).is_empty()); + let longest = NANOID_LENGTHS.1 as usize; + assert_eq!(possible(&"a".repeat(longest)), [IdKind::NanoId]); + assert!(possible(&"a".repeat(longest + 1)).is_empty()); + } } diff --git a/crates/engine/src/tools/identity.rs b/crates/engine/src/tools/identity.rs index 82864fda5..b70798b41 100644 --- a/crates/engine/src/tools/identity.rs +++ b/crates/engine/src/tools/identity.rs @@ -1633,4 +1633,36 @@ s:Ba generate(&request, today()) ); } + + #[test] + fn a_month_has_its_own_days() { + for (year, month, days) in [ + (2023, 2, 28), + (2024, 2, 29), + (2100, 2, 28), + (2026, 1, 31), + (2026, 4, 30), + (2026, 11, 30), + (2026, 12, 31), + ] { + assert_eq!(days_in(year, month), days, "{year}-{month}"); + } + } + + #[test] + fn an_account_is_an_iban_where_the_country_writes_one() { + let mut draw = Draw::new(1); + for country in Country::ALL { + assert_eq!( + has_iban(country), + iban(country, &mut draw).is_some(), + "{country}" + ); + assert_eq!( + has_iban(country), + !matches!(country, Country::Us | Country::Ca), + "{country}" + ); + } + } } diff --git a/crates/engine/src/tools/identity/data.rs b/crates/engine/src/tools/identity/data.rs index 979907c1e..45e431dc1 100644 --- a/crates/engine/src/tools/identity/data.rs +++ b/crates/engine/src/tools/identity/data.rs @@ -344,4 +344,25 @@ High Street assert!(land.is_whole(), "{country}"); } } + + /// A place of two languages has streets in each. + #[test] + fn a_place_s_streets_are_those_of_its_own_tag_or_the_country_s_first() { + let land = Land { + places: Vec::new(), + streets: vec![("fr", vec!["rue"]), ("nl", vec!["straat"])], + }; + + assert_eq!(land.streets("nl"), ["straat"]); + assert_eq!(land.streets("fr"), ["rue"]); + assert_eq!(land.streets("de"), ["rue"]); + assert!( + Land { + streets: Vec::new(), + ..land + } + .streets("fr") + .is_empty() + ); + } } diff --git a/crates/engine/src/tools/identity/numbers.rs b/crates/engine/src/tools/identity/numbers.rs index 01341ae12..c5227eff8 100644 --- a/crates/engine/src/tools/identity/numbers.rs +++ b/crates/engine/src/tools/identity/numbers.rs @@ -450,4 +450,21 @@ mod tests { assert!(routing_number_holds("021000021")); assert!(!routing_number_holds("021000022")); } + + /// Its consonants, then its vowels, then `X`; a given name of four consonants skips its second. + #[test] + fn three_letters_of_an_italian_name() { + for (name, given, letters) in [ + ("Rossi", false, "RSS"), + ("Marco", true, "MRC"), + ("Roberto", true, "RRT"), + ("Roberto", false, "RBR"), + ("Gianfranco", true, "GFR"), + ("Ada", true, "DAA"), + ("Fo", false, "FOX"), + ("È", true, "EXX"), + ] { + assert_eq!(italian_name(name, given), letters, "{name}"); + } + } } diff --git a/crates/engine/src/tools/identity/papers.rs b/crates/engine/src/tools/identity/papers.rs index bba20ceef..0871026d8 100644 --- a/crates/engine/src/tools/identity/papers.rs +++ b/crates/engine/src/tools/identity/papers.rs @@ -624,4 +624,70 @@ mod tests { } use super::*; + + fn drawn(make: impl Fn(&mut Draw) -> T) -> Vec { + (0..500).map(|seed| make(&mut Draw::new(seed))).collect() + } + + /// Odd for a man, even for a woman, of as many digits as asked, every one of them drawn. + #[test] + fn a_serial_says_the_sex_by_its_parity() { + let serials = |sex: Sex| -> std::collections::BTreeSet { + drawn(|draw| serial_of(sex, draw, 1)).into_iter().collect() + }; + + assert_eq!( + serials(Sex::Male), + ["1", "3", "5", "7"].map(str::to_owned).into() + ); + assert_eq!( + serials(Sex::Female), + ["2", "4", "6", "8"].map(str::to_owned).into() + ); + assert!( + drawn(|draw| serial_of(Sex::Male, draw, 3)) + .iter() + .all(|serial| serial.len() == 3) + ); + } + + /// The doubled digit and the one that is not there move, and the others are shuffled. + #[test] + fn a_german_number_is_drawn_whole() { + let bodies: Vec> = drawn(|draw| german(draw).remove(0).value) + .iter() + .map(|number| { + number + .chars() + .filter(char::is_ascii_digit) + .take(10) + .collect() + }) + .collect(); + let twice_at: std::collections::BTreeSet = bodies + .iter() + .filter_map(|body| (0..10).rev().find(|at| body[..*at].contains(&body[*at]))) + .collect(); + + assert!(twice_at.len() > 5, "{twice_at:?}"); + let opening: std::collections::BTreeSet<&[char]> = + bodies.iter().map(|body| &body[..4]).collect(); + assert!(opening.len() > 300, "{}", opening.len()); + } + + /// Two letters the administration uses, and none of the seven pairs it keeps aside. + #[test] + fn a_british_number_never_starts_with_a_pair_kept_aside() { + for number in drawn(|draw| british(draw).remove(0).value) { + assert!( + !["BG", "GB", "KN", "NK", "NT", "TN", "ZZ"].contains(&&number[..2]), + "{number}" + ); + assert!( + !number[..2].contains(['D', 'F', 'I', 'Q', 'U', 'V']) + && !number[1..2].contains('O'), + "{number}" + ); + } + } } diff --git a/crates/engine/src/tools/jwt.rs b/crates/engine/src/tools/jwt.rs index 102232e7c..37c872285 100644 --- a/crates/engine/src/tools/jwt.rs +++ b/crates/engine/src/tools/jwt.rs @@ -561,4 +561,80 @@ mod tests { Verification::Valid ); } + + /// At the very second it expires, a token has; at the one it starts, it may be used. + #[test] + fn a_token_s_state_changes_at_its_own_second() { + let dated = |name: &str, seconds: i64| { + #[allow(clippy::cast_precision_loss)] + let epoch_milliseconds = ((now().timestamp() + seconds) * 1000) as f64; + DatedClaim { + name: name.to_owned(), + epoch_milliseconds, + ..dated_claim() + } + }; + for (claims, expected) in [ + (vec![], TokenState::Undated), + (vec![dated("exp", 0)], TokenState::Expired), + (vec![dated("exp", 1)], TokenState::Valid), + (vec![dated("nbf", 0)], TokenState::Valid), + (vec![dated("nbf", 1)], TokenState::NotYetValid), + (vec![dated("nbf", 1), dated("exp", -1)], TokenState::Expired), + ] { + assert_eq!(state(&claims, now()), expected, "{claims:?}"); + } + } + + /// A claim of a token that expires in 2100. + fn dated_claim() -> DatedClaim { + let token = signed( + "HS256", + &serde_json::json!({ "exp": 4_102_444_800_u64 }), + b"k", + ); + match ask(&token, "", false) { + JwtAnswer::Decoded { dates, .. } => dates[0].clone(), + other @ JwtAnswer::Malformed { .. } => panic!("{other:?}"), + } + } + + /// Counted in the text as pasted: what is before the segment, its dots included. + #[test] + fn a_segment_that_does_not_read_is_located_in_the_text_as_pasted() { + let token = signed("HS256", &serde_json::json!({}), b"k"); + let parts: Vec<&str> = token.split('.').collect(); + for (text, segment, at) in [ + (format!("*.{}.{}", parts[1], parts[2]), Segment::Header, 0), + ( + format!("{}.*.{}", parts[0], parts[2]), + Segment::Payload, + parts[0].len() + 1, + ), + ( + format!(" Bearer {}.*.{}", parts[0], parts[2]), + Segment::Payload, + parts[0].len() + 1 + 9, + ), + ( + format!("{}.{}.*", parts[0], parts[1]), + Segment::Signature, + parts[0].len() + parts[1].len() + 2, + ), + ] { + let JwtAnswer::Malformed { + segment: named, + at: located, + .. + } = ask(&text, "", false) + else { + panic!("{text}"); + }; + assert_eq!( + (named, located.map(|at| at as usize)), + (Some(segment), Some(at + 1)), + "{text}" + ); + } + } } diff --git a/crates/engine/src/tools/random.rs b/crates/engine/src/tools/random.rs index 0fda60ba5..e1fb4b621 100644 --- a/crates/engine/src/tools/random.rs +++ b/crates/engine/src/tools/random.rs @@ -241,4 +241,45 @@ mod tests { assert_eq!(passwords[0].len(), MIN_LENGTH as usize); assert_eq!(strength, Strength::VeryWeak); } + + /// The usual bands, each reached at its own number of bits. + #[test] + fn a_strength_is_the_band_its_bits_reach() { + for (bits, strength) in [ + (0.0, Strength::VeryWeak), + (27.9, Strength::VeryWeak), + (28.0, Strength::Weak), + (36.0, Strength::Fair), + (60.0, Strength::Strong), + (127.9, Strength::Strong), + (128.0, Strength::VeryStrong), + ] { + assert_eq!(Strength::of(bits), strength, "{bits}"); + } + } + + /// A set chosen twice is one set: the alphabet, and the bits, are counted once. + #[test] + fn a_set_chosen_twice_counts_once() { + let bits = |sets: &[CharacterSet]| { + let request = PasswordRequest { + sets: sets.to_vec(), + ..request(20) + }; + generated(passwords(&request).unwrap()).1 + }; + let (one, other) = (CharacterSet::Lowercase, CharacterSet::Digits); + + assert!((bits(&[one, other, one]) - bits(&[one, other])).abs() < f64::EPSILON); + assert!((bits(&[other, one]) - bits(&[one, other])).abs() < f64::EPSILON); + } + + #[test] + fn a_draw_is_below_its_bound() { + assert!((0..200).all(|_| uniform(3).unwrap() < 3)); + assert_eq!(uniform(1), Ok(0)); + let drawn: std::collections::BTreeSet = + (0..200).map(|_| uniform(3).unwrap()).collect(); + assert_eq!(drawn.len(), 3); + } } From b4f2f56905e8d100246b0889f72029fd4ed43ae3 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 07:49:25 +0100 Subject: [PATCH 53/95] Tools: unit tests completed for time and networks (#1781) * tools time gaps * tools network gaps * tools network gaps * A plan that fills its block --- crates/engine/src/tools/cidr.rs | 45 ++++++++ crates/engine/src/tools/cidr/masks.rs | 16 +++ crates/engine/src/tools/cidr/plan.rs | 38 +++++++ crates/engine/src/tools/cidr/summary.rs | 27 +++++ crates/engine/src/tools/cron.rs | 138 ++++++++++++++++++++++++ crates/engine/src/tools/dates.rs | 80 ++++++++++++++ crates/engine/src/tools/durations.rs | 89 +++++++++++++++ crates/engine/src/tools/permissions.rs | 24 +++++ crates/engine/src/tools/transfer.rs | 30 ++++++ crates/engine/src/tools/zones.rs | 53 +++++++++ 10 files changed, 540 insertions(+) diff --git a/crates/engine/src/tools/cidr.rs b/crates/engine/src/tools/cidr.rs index 76317b79a..15a90d4c6 100644 --- a/crates/engine/src/tools/cidr.rs +++ b/crates/engine/src/tools/cidr.rs @@ -857,4 +857,49 @@ mod tests { assert_eq!(split_into("10.24.8.0/21", 20).prefix, 22); assert_eq!(split_into("10.24.8.0/21", 33).prefix, 22); } + + /// IPv4 from `/30` up has a network and a broadcast that are no hosts; `/31` and `/32` have + /// neither, nor IPv6. + #[test] + fn the_narrowest_blocks_have_no_broadcast() { + for (block, broadcast, first, usable) in [ + ("10.0.0.0/30", Some("10.0.0.3"), "10.0.0.1", "2"), + ("10.0.0.0/31", None, "10.0.0.0", "2"), + ("10.0.0.0/32", None, "10.0.0.0", "1"), + ("2001:db8::/126", None, "2001:db8::", "4"), + ] { + let read = block_of(block); + assert_eq!( + ( + read.broadcast.as_deref(), + read.first.as_str(), + read.usable.as_str() + ), + (broadcast, first, usable), + "{block}" + ); + } + } + + /// The whole table of a family is the last split of one. + #[test] + fn a_split_is_offered_down_to_one_address() { + for (block, choices) in [ + ("10.0.0.0/29", vec![30, 31, 32]), + ("10.0.0.0/31", vec![32]), + ("10.0.0.0/32", vec![]), + ] { + assert_eq!(ask(block).split_choices, choices, "{block}"); + } + assert_eq!(split_into("10.0.0.0/24", 25).prefix, 25); + // A prefix that splits nothing is the first offered. + assert_eq!(split_into("10.0.0.0/24", 24).prefix, 25); + } + + /// The same bits in the other family are another address. + #[test] + fn an_address_of_the_other_family_is_outside() { + assert_eq!(member("0.0.0.0/0", "::1"), CidrMembership::Outside); + assert_eq!(member("::/0", "0.0.0.1"), CidrMembership::Outside); + } } diff --git a/crates/engine/src/tools/cidr/masks.rs b/crates/engine/src/tools/cidr/masks.rs index f9dd0655c..2ba6f9ae8 100644 --- a/crates/engine/src/tools/cidr/masks.rs +++ b/crates/engine/src/tools/cidr/masks.rs @@ -107,4 +107,20 @@ mod tests { assert!(masks_of("").is_empty()); assert!(masks_of("10.0.0.0/33").is_empty()); } + + #[test] + fn an_ipv6_prefix_holds_networks_of_64_bits_down_to_one() { + let networks = |prefix: u8| { + let masks = masks_of(&format!("2001:db8::/{prefix}")); + masks + .into_iter() + .find(|row| row.prefix == prefix) + .unwrap() + .networks64 + }; + + assert_eq!(networks(63).as_deref(), Some("2")); + assert_eq!(networks(64).as_deref(), Some("1")); + assert_eq!(networks(65), None); + } } diff --git a/crates/engine/src/tools/cidr/plan.rs b/crates/engine/src/tools/cidr/plan.rs index 64dace0a0..f85e0f611 100644 --- a/crates/engine/src/tools/cidr/plan.rs +++ b/crates/engine/src/tools/cidr/plan.rs @@ -269,4 +269,42 @@ mod tests { ); assert!(plan.free.is_empty()); } + + /// The whole block taken, nothing is left; what comes after has no room. + #[test] + fn a_plan_that_fills_its_block_leaves_nothing_free() { + let plan = plan_of("10.0.0.0/28", "a 2\nb 2\nc 2\nd 2\ne 2"); + + let no_room = plan + .lines + .iter() + .filter(|line| matches!(line, PlanLine::NoRoom { .. })) + .count(); + assert_eq!((plan.lines.len(), no_room), (5, 1)); + assert!(plan.free.is_empty(), "{:?}", plan.free); + + let almost = plan_of("10.0.0.0/28", "a 2\nb 2\nc 2"); + assert_eq!(almost.free, ["10.0.0.12/30"]); + } + + #[test] + fn a_need_of_no_host_is_not_read() { + let plan = plan_of("10.0.0.0/24", "Vide 0\nUn 1"); + + assert_eq!(plan.lines.len(), 2); + assert_eq!(placed(&plan.lines[0]).0, "Un"); + assert!(matches!(&plan.lines[1], PlanLine::Unreadable { text } if text == "Vide 0")); + } + + /// Lines none of which is read are said; no line at all is no plan. + #[test] + fn a_plan_of_unreadable_lines_is_still_a_plan() { + assert_eq!(plan_of("10.0.0.0/24", "rien").lines.len(), 1); + let empty = describe(&CidrRequest { + network: "10.0.0.0/24".to_owned(), + plan: " \n".to_owned(), + ..CidrRequest::default() + }); + assert_eq!(empty.plan, None); + } } diff --git a/crates/engine/src/tools/cidr/summary.rs b/crates/engine/src/tools/cidr/summary.rs index 921f16b6f..7cf85d272 100644 --- a/crates/engine/src/tools/cidr/summary.rs +++ b/crates/engine/src/tools/cidr/summary.rs @@ -199,4 +199,31 @@ mod tests { .is_none() ); } + + #[test] + fn a_list_none_of_which_reads_is_still_summarised_as_such() { + let summary = summary_of("ici"); + + assert!(summary.families.is_empty()); + assert_eq!(summary.unreadable, ["ici"]); + let empty = describe(&CidrRequest { + list: " ,;\n".to_owned(), + ..CidrRequest::default() + }); + assert_eq!(empty.summary, None); + } + + /// Alone at the end of its block, or with the whole space to cover. + #[test] + fn a_range_is_covered_by_the_fewest_blocks() { + for (list, blocks) in [ + ("10.0.0.255", vec!["10.0.0.255/32"]), + ("10.0.0.0 - 10.0.0.255", vec!["10.0.0.0/24"]), + ("10.0.0.1 - 10.0.0.2", vec!["10.0.0.1/32", "10.0.0.2/32"]), + ("0.0.0.0 - 255.255.255.255", vec!["0.0.0.0/0"]), + ("::/0", vec!["::/0"]), + ] { + assert_eq!(summary_of(list).families[0].blocks, blocks, "{list}"); + } + } } diff --git a/crates/engine/src/tools/cron.rs b/crates/engine/src/tools/cron.rs index 868840ef9..919786c15 100644 --- a/crates/engine/src/tools/cron.rs +++ b/crates/engine/src/tools/cron.rs @@ -1377,4 +1377,142 @@ mod tests { ); assert_eq!(refusal(" "), (None, String::new(), 1, Empty)); } + + #[test] + fn a_value_that_is_no_value_is_refused_by_what_it_is() { + for (expression, problem) in [ + ("5- * * * *", CronProblem::NotANumber), + ("-5 * * * *", CronProblem::NotANumber), + ("1x * * * *", CronProblem::NotANumber), + ("foo * * * *", CronProblem::UnknownName), + ("99999999999 * * * *", CronProblem::OutOfRange), + ("? * * * *", CronProblem::NotHere), + ("* * * ? *", CronProblem::NotHere), + ("*/0 * * * *", CronProblem::ZeroStep), + ("*/x * * * *", CronProblem::NotANumber), + ("5-1 * * * *", CronProblem::ReversedRange), + ("5/15 * * * *", CronProblem::NotHere), + ("0 0 * * MON#6", CronProblem::OutOfRange), + ("0 0 * * MON#x", CronProblem::OutOfRange), + ] { + assert_eq!(refusal(expression).3, problem, "{expression}"); + } + } + + #[test] + fn a_range_of_one_value_and_either_day_field_left_open_are_read() { + assert_eq!( + pieces("5-5 * * * *", CronField::Minute), + [Piece::Range { from: 5, to: 5 }] + ); + assert_eq!(pieces("0 0 * * ?", CronField::DayOfWeek), [Piece::Every]); + assert_eq!(pieces("0 0 * * *", CronField::DayOfMonth), [Piece::Every]); + } + + #[test] + fn only_both_day_fields_set_are_either_one() { + for (expression, both) in [ + ("0 0 1 * *", false), + ("0 0 * * 5", false), + ("0 0 1 * 5", true), + ("0 0 ? * 5", false), + ] { + let CronAnswer::Read { both_days, .. } = ask(expression) else { + panic!("{expression}"); + }; + assert_eq!(both_days, both, "{expression}"); + } + } + + /// Fifty are listed; one more, and the two ends alone. + #[test] + fn as_many_runs_as_are_listed_are_listed_whole() { + let (total, first, last) = counted(between( + "* * * * *", + "UTC", + "2026-03-01 00:00", + "2026-03-01 00:50", + )); + assert_eq!( + (total as usize, first.len(), last.len()), + (LISTED, LISTED, 0) + ); + + let (total, first, last) = counted(between( + "* * * * *", + "UTC", + "2026-03-01 00:00", + "2026-03-01 00:51", + )); + assert_eq!( + (total as usize, first.len(), last.len()), + (LISTED + 1, EDGE, EDGE) + ); + assert!( + first[0].contains("00:00:00") && last[EDGE - 1].contains("00:50:00"), + "{first:?} {last:?}" + ); + } + + /// The run at the end is past it; the one at the start is in. + #[test] + fn a_window_holds_its_start_and_not_its_end() { + let (total, first, _) = counted(between( + "0 * * * *", + "UTC", + "2026-03-01 01:00", + "2026-03-01 03:00", + )); + + assert_eq!(total, 2); + assert!( + first[0].contains("01:00:00") && first[1].contains("02:00:00"), + "{first:?}" + ); + } + + /// A day the clocks change on is walked run by run, and so is one the window cuts. + #[test] + fn a_day_the_clocks_change_on_is_counted_as_it_runs() { + for (until, hours) in [("2026-03-30 00:00", 24 + 23), ("2026-03-29 12:00", 24 + 11)] { + let (total, ..) = counted(between( + "0 * * * *", + "Europe/Paris", + "2026-03-28 00:00", + until, + )); + assert_eq!(total, hours, "{until}"); + } + let (total, ..) = counted(between( + "0 * * * *", + "Europe/Paris", + "2026-10-25 00:00", + "2026-10-26 00:00", + )); + assert_eq!(total, 25); + } + + #[test] + fn a_window_of_as_many_years_as_are_counted_is_counted() { + let window = |until: &str| match between("0 0 1 1 *", "UTC", "2026-01-01 00:00", until) { + CronAnswer::Read { window, .. } => window.unwrap(), + other => panic!("{other:?}"), + }; + + assert!(matches!( + window("2036-01-01 00:00"), + CronWindow::Counted { total: 10, .. } + )); + // Ten years of 366 days exactly, then a day more. + assert!(matches!( + window("2036-01-09 00:00"), + CronWindow::Counted { .. } + )); + assert!(matches!( + window("2036-01-10 00:00"), + CronWindow::TooLong { + years: WINDOW_YEARS + } + )); + } } diff --git a/crates/engine/src/tools/dates.rs b/crates/engine/src/tools/dates.rs index 3b40ffc5b..fa5c8030d 100644 --- a/crates/engine/src/tools/dates.rs +++ b/crates/engine/src/tools/dates.rs @@ -725,4 +725,84 @@ mod tests { assert!(text.ends_with('Z')); assert_eq!(read(&text).0, ReadAs::Iso8601); } + + /// Each unit from 1973 on: a timestamp in seconds reaches `1e11` only in the year 5138. + #[test] + fn a_magnitude_changes_at_its_own_size() { + for (text, magnitude) in [ + ("99999999999", Magnitude::Seconds), + ("100000000000", Magnitude::Milliseconds), + ("99999999999999", Magnitude::Milliseconds), + ("100000000000000", Magnitude::Microseconds), + ("99999999999999999", Magnitude::Microseconds), + ("100000000000000000", Magnitude::Nanoseconds), + ] { + assert_eq!(read(text).1, Some(magnitude), "{text}"); + } + } + + #[test] + fn a_reading_says_what_it_had_to_assume() { + let assumed = |text: &str| match ask(text) { + InstantAnswer::Read { + guessed, + local_assumed, + ambiguous, + .. + } => (guessed, local_assumed, ambiguous), + other => panic!("{text}: {other:?}"), + }; + + assert_eq!(assumed("1790000000"), (true, false, false)); + assert_eq!(assumed("2026-03-01T00:00:00Z"), (false, false, false)); + assert_eq!(assumed("2026-03-01T00:00:00"), (false, true, false)); + } + + #[test] + fn a_text_that_only_looks_like_a_number_or_a_year_is_no_date() { + for text in [".", "-", ".5", "1.x", "1.2.3", "2026", "20", "x2026-01-01"] { + let answer = ask(text); + let number = matches!( + answer, + InstantAnswer::Read { + read_as: ReadAs::Unix, + .. + } + ); + assert_eq!(number, matches!(text, "2026" | "20"), "{text}: {answer:?}"); + } + } + + #[test] + fn a_time_is_within_a_day_and_its_offset_within_one_too() { + let reads = |time: &str| { + matches!( + ask(&format!("2026-03-01{time}")), + InstantAnswer::Read { .. } + ) + }; + for time in [ + "T23:59:59Z", + "t23:59:59z", + " 23:59:59", + "T00:00", + "T00:00:00+23:59", + "T00:00:00-0530", + "T00:00+05", + ] { + assert!(reads(time), "{time}"); + } + for time in [ + "T24:00:00Z", + "T23:60:00Z", + "T23:59:60Z", + "T00:00:00+24:00", + "T00:00:00+01:60", + "X00:00", + "T00:00:00.Z", + "T0:00", + ] { + assert!(!reads(time), "{time}"); + } + } } diff --git a/crates/engine/src/tools/durations.rs b/crates/engine/src/tools/durations.rs index a5e56bded..dba44dbc8 100644 --- a/crates/engine/src/tools/durations.rs +++ b/crates/engine/src/tools/durations.rs @@ -914,4 +914,93 @@ mod tests { assert_eq!(refused("1.5h 30"), (6, DurationProblem::FractionNotLast)); assert_eq!(refused("abc"), (1, DurationProblem::Unexpected)); } + + /// Blanks are no date. + #[test] + fn a_gap_waits_for_both_dates() { + let asked = |from: &str, to: &str| { + let request = DurationsRequest { + from: from.to_owned(), + to: to.to_owned(), + duration: " ".to_owned(), + }; + let answer = measure(&request, PARIS); + (answer.gap.is_some(), answer.duration.is_some()) + }; + + assert_eq!(asked("2026-01-01", "2026-01-02"), (true, false)); + assert_eq!(asked(" ", "2026-01-02"), (false, false)); + assert_eq!(asked("2026-01-01", " "), (false, false)); + } + + #[test] + fn a_date_past_the_year_9999_is_out_of_range() { + assert!(matches!( + gap_of("9999-06-01", "9999-12-01"), + GapAnswer::Measured { .. } + )); + assert_eq!( + gap_of("2026-01-01", "9999-12-31T23:30:00-01:00"), + GapAnswer::OutOfRange { + field: GapField::To + } + ); + } + + #[test] + fn two_dates_of_one_instant_are_no_time_apart() { + let (negative, calendar, elapsed, iso, _) = + measured("2026-01-31 10:00", "2026-01-31 10:00"); + + assert!(!negative); + assert_eq!(calendar, calendar_of(0, 0, 0, 0, 0)); + assert_eq!((elapsed.total_minutes, iso.as_str()), (0, "PT0S")); + } + + /// To the second: the clocks changed at 01:00 UTC. + #[test] + fn a_change_of_clocks_is_found_wherever_it_stands_between_the_dates() { + for (from, to) in [ + ("2026-03-29T00:59:59Z", "2026-03-29T01:00:00Z"), + ("2026-03-28T23:30:00Z", "2026-03-30T12:00:00Z"), + ("2025-12-01", "2026-06-01"), + ] { + let transition = measured(from, to).4.unwrap(); + assert_eq!(transition.date.as_deref(), Some("2026-03-29"), "{from}"); + assert!(transition.forward); + } + assert_eq!( + measured("2026-03-29T00:59:58Z", "2026-03-29T00:59:59Z").4, + None + ); + } + + #[test] + fn a_number_of_a_duration_is_read_whole() { + for (text, iso) in [ + ("1,5h", "PT1.5H"), + ("1.5h", "PT1.5H"), + ("2h", "PT2H"), + ("1:30", "PT1H30M"), + ("1 h 30", "PT1H30M"), + ] { + let (_, _, written, ..) = read(text); + assert_eq!(written, iso, "{text}"); + } + } + + /// Where it goes wrong, from one. + #[test] + fn a_part_of_a_duration_out_of_its_place_is_located() { + for (text, at, problem) in [ + ("1.h", 2, DurationProblem::Unexpected), + ("P1M1Y", 5, DurationProblem::OutOfOrder), + ("P1D1D", 5, DurationProblem::Repeated), + ("P1DT1H1H", 8, DurationProblem::Repeated), + ("PT1.5H1M", 7, DurationProblem::FractionNotLast), + ("1:2:3:4", 6, DurationProblem::Unexpected), + ] { + assert_eq!(refused(text), (at, problem), "{text}"); + } + } } diff --git a/crates/engine/src/tools/permissions.rs b/crates/engine/src/tools/permissions.rs index f02bb41ba..20200d084 100644 --- a/crates/engine/src/tools/permissions.rs +++ b/crates/engine/src/tools/permissions.rs @@ -570,4 +570,28 @@ mod tests { assert_eq!(refusal(" drwxr-xrw!"), (ModeProblem::Unexpected, 12)); assert_eq!(refusal("wrxr-xr-x"), (ModeProblem::Unexpected, 1)); } + + /// Four digits only with a special bit. + #[test] + fn an_octal_mode_is_written_with_its_special_digit_when_it_has_one() { + for (text, octal) in [ + ("777", "777"), + ("0", "000"), + ("1000", "1000"), + ("4755", "4755"), + ("0644", "644"), + ] { + assert_eq!(mode(text).0.octal, octal, "{text}"); + } + } + + /// `ls -l` writes a mark after its ten letters alone. + #[test] + fn the_mark_after_a_mode_is_passed_over_only_there() { + for mark in ['.', '+', '@'] { + assert_eq!(mode(&format!("-rw-r--r--{mark}")).0.octal, "644"); + refusal(&format!("rw-r--r--{mark}")); + } + refusal("-rw-r--r--x"); + } } diff --git a/crates/engine/src/tools/transfer.rs b/crates/engine/src/tools/transfer.rs index fd21d435a..f824bf454 100644 --- a/crates/engine/src/tools/transfer.rs +++ b/crates/engine/src/tools/transfer.rs @@ -367,4 +367,34 @@ mod tests { TransferAnswer::TooLarge ); } + + /// Nothing takes no time at all, which is not less than a second of it. + #[test] + fn a_transfer_of_nothing_takes_no_time() { + let nothing = spans(&ask("0", "1", RateUnit::GigabitPerSecond, 100)).0; + assert_eq!(nothing, of(0, 0, 0, 0)); + + let little = spans(&ask("0,000001", "1", RateUnit::GigabitPerSecond, 100)).0; + assert!(little.under_a_second); + } + + /// Where it goes wrong, from one; minus nothing is nothing. + #[test] + fn a_rate_that_does_not_read_is_located() { + let field = TransferField::Rate; + for (rate, expected) in [ + ("x", TransferAnswer::Unreadable { field, at: 1 }), + (" x", TransferAnswer::Unreadable { field, at: 3 }), + ("10 x", TransferAnswer::Unreadable { field, at: 5 }), + (" -1", TransferAnswer::Negative { field, at: 2 }), + ("0", TransferAnswer::ZeroRate), + ("-0", TransferAnswer::ZeroRate), + ] { + assert_eq!( + ask("1", rate, RateUnit::MegabitPerSecond, 100), + expected, + "{rate:?}" + ); + } + } } diff --git a/crates/engine/src/tools/zones.rs b/crates/engine/src/tools/zones.rs index a4caaa940..43b4f8d84 100644 --- a/crates/engine/src/tools/zones.rs +++ b/crates/engine/src/tools/zones.rs @@ -564,4 +564,57 @@ mod tests { assert!(matches!(dates::parse(&text, None), Ok(Parsed::Wall(..)))); assert_eq!(now_in(Some("Nowhere"), None).len(), 19); } + + #[test] + fn an_offset_is_written_with_its_sign() { + for (seconds, text) in [ + (0, "+00:00"), + (-1, "-00:00"), + (19_800, "+05:30"), + (-12_600, "-03:30"), + (50_400, "+14:00"), + ] { + assert_eq!(offset_text(seconds), text); + } + } + + /// An abbreviation met whole first, then by name. + #[test] + fn what_a_search_finds_is_in_order() { + let at = DateTime::parse_from_rfc3339("2026-07-01T00:00:00Z") + .unwrap() + .with_timezone(&Utc); + + let found = search("est", at); + let first: Vec = found + .iter() + .map(|zone| zone.abbreviation.as_deref() == Some("EST")) + .collect(); + assert!(first[0] && first.is_sorted_by(|a, b| a >= b), "{found:?}"); + let names = search("america/new", at); + assert!( + names.is_sorted_by(|a, b| a.zone <= b.zone) && !names.is_empty(), + "{names:?}" + ); + assert!(search(" ", at).is_empty()); + } + + /// Past the range chrono can place, rather than a panic. + #[test] + fn a_time_past_the_year_9999_is_out_of_range() { + let placed = + |text: &str| matches!(ask(text, "UTC", &[], false), ZonesAnswer::Placed { .. }); + + assert!(placed("9999-12-31T23:59:59Z")); + assert!(!placed("9999-12-31T23:30:00-01:00")); + } + + #[test] + fn a_summer_time_is_said_where_the_clocks_are_on_it() { + for (text, summer) in [("2026-07-01 12:00", true), ("2026-01-01 12:00", false)] { + let (_, times, _) = placed(ask(text, "Europe/Paris", &["UTC"], false)); + assert_eq!(row(×, "Europe/Paris").summer_time, summer); + assert!(!row(×, "UTC").summer_time); + } + } } From c0fa7da13f174fa404318cf79d0a42a8c820be36 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 07:53:25 +0100 Subject: [PATCH 54/95] Notes: marks, cells and code read back as they were written (#1785) * Notes: marks, cells and code read back as they were written Co-Authored-By: Claude Opus 5.5 * Notes: what starts an item reads back in it, and an empty item has text Co-Authored-By: Claude Opus 5.5 * Notes: a star against a field is written escaped Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/notes/markdown.rs | 14 + crates/richtext/src/escape.rs | 25 +- crates/richtext/src/inlines.rs | 2 +- crates/richtext/src/read.rs | 61 +++- crates/richtext/src/write.rs | 528 ++++++++++++++++++++++++++-- docs/architecture.md | 3 +- 6 files changed, 588 insertions(+), 45 deletions(-) diff --git a/crates/engine/src/notes/markdown.rs b/crates/engine/src/notes/markdown.rs index e76c89719..b58e6337e 100644 --- a/crates/engine/src/notes/markdown.rs +++ b/crates/engine/src/notes/markdown.rs @@ -47,6 +47,8 @@ pub(crate) fn outline(markdown: &str) -> Vec { } Event::Text(text) | Event::Code(text) => out.line.push_str(&text), Event::SoftBreak => out.line.push(' '), + // A break in a cell or a heading, which hold one line. + Event::InlineHtml(tag) if &*tag == "
" => out.line.push(' '), Event::End(TagEnd::TableCell) => out.line.push_str(" · "), Event::End(TagEnd::TableHead | TagEnd::TableRow) => { if out.line.ends_with(" · ") { @@ -113,6 +115,11 @@ pub(crate) fn present(markdown: &str) -> Presentation { text.push_str(&words); } } + Event::InlineHtml(tag) if &*tag == "
" => { + if let Some((_, text)) = heading.as_mut() { + text.push(' '); + } + } _ => {} } } @@ -473,4 +480,11 @@ mod tests { assert_eq!(shown.slides, ["intro", "#\n\nafter"]); assert!(shown.map.is_empty()); } + + #[test] + fn a_break_in_a_cell_or_a_heading_is_a_space() { + assert_eq!(plain("| a
b |\n| --- |"), "a b"); + assert_eq!(plain("# a
b"), "a b"); + assert_eq!(present("# a
b").map[0].text, "a b"); + } } diff --git a/crates/richtext/src/escape.rs b/crates/richtext/src/escape.rs index 605e3b6bb..6d962d4c1 100644 --- a/crates/richtext/src/escape.rs +++ b/crates/richtext/src/escape.rs @@ -3,22 +3,28 @@ //! every `_ * ~ [ ] \` and turns `& < >` into entities: `{{db_host}}` stopped being a field, and //! « a -> b » was stored as `a -> b`. A `{{field}}` is left exactly as typed. -/// A tab starting a line is written ` `: Markdown reads it as an indented code block, or -/// drops it on a line that continues a paragraph. +/// A tab starting a line is written ` `, and the first of four spaces ` `: Markdown reads +/// them as an indented code block, or drops them on a line that continues a paragraph. pub fn escape(text: &str, starts_line: bool) -> String { let mut out = String::with_capacity(text.len()); let mut rest = text; + let mut field_before = None; while let Some((before, field, after)) = next_field(rest) { - escape_run(before, &mut out); + escape_run(before, (field_before, Some('{')), &mut out); out.push_str(field); + field_before = Some('}'); rest = after; } - escape_run(rest, &mut out); + escape_run(rest, (field_before, None), &mut out); if !starts_line { return out; } - let tabs = out.chars().take_while(|glyph| *glyph == '\t').count(); - format!("{}{}", " ".repeat(tabs), &out[tabs..]) + let text = out.trim_start_matches([' ', '\t']); + let lead = out[..out.len() - text.len()].replace('\t', " "); + if lead.starts_with(" ") { + return format!(" {}{text}", &lead[1..]); + } + format!("{lead}{text}") } /// `{{` then anything but braces and line ends, then `}}`. @@ -36,11 +42,12 @@ fn next_field(text: &str) -> Option<(&str, &str, &str)> { None } -fn escape_run(run: &str, out: &mut String) { +/// `around`, the braces of the fields the run stands between. +fn escape_run(run: &str, around: (Option, Option), out: &mut String) { let glyphs: Vec = run.chars().collect(); for (at, glyph) in glyphs.iter().enumerate() { - let before = at.checked_sub(1).map(|at| glyphs[at]); - let after = glyphs.get(at + 1).copied(); + let before = at.checked_sub(1).map(|at| glyphs[at]).or(around.0); + let after = glyphs.get(at + 1).copied().or(around.1); if needs_escape(*glyph, before, after, &glyphs[at..]) { out.push('\\'); } diff --git a/crates/richtext/src/inlines.rs b/crates/richtext/src/inlines.rs index c3f936cb5..7cdd80e6d 100644 --- a/crates/richtext/src/inlines.rs +++ b/crates/richtext/src/inlines.rs @@ -130,7 +130,7 @@ pub fn marks_at(content: &[Inline], at: usize) -> Marks { marks } -fn wears(marks: &Marks, mark: &Mark) -> bool { +pub fn wears(marks: &Marks, mark: &Mark) -> bool { match mark { Mark::Bold => marks.bold, Mark::Italic => marks.italic, diff --git a/crates/richtext/src/read.rs b/crates/richtext/src/read.rs index 247a47af8..e51a5f624 100644 --- a/crates/richtext/src/read.rs +++ b/crates/richtext/src/read.rs @@ -99,6 +99,7 @@ impl Reader { marks, }); } + Event::InlineHtml(html) if is_break(&html) => self.inline(Inline::HardBreak), Event::Html(html) | Event::InlineHtml(html) => { let text = without_tags(&html); self.text(text.trim_end_matches('\n')); @@ -196,9 +197,10 @@ impl Reader { }; match open { Open::Blocks(blocks) => self.open.push(Open::Blocks(blocks)), - Open::Quote(blocks) => self.block(Block::Quote(blocks)), + Open::Quote(blocks) => self.block(Block::Quote(typed_in(blocks))), Open::List { kind, items } => self.block(Block::List { kind, items }), - Open::Item(item) => { + Open::Item(mut item) => { + item.blocks = typed_in(item.blocks); if let Some(Open::List { items, .. }) = self.open.last_mut() { items.push(item); } @@ -323,6 +325,14 @@ impl Reader { } } +/// An item or a quote with nothing in it holds a paragraph to type in. +fn typed_in(blocks: Vec) -> Vec { + if blocks.is_empty() { + return vec![Block::Paragraph(Vec::new())]; + } + blocks +} + fn is_block(tag: &Tag<'_>) -> bool { matches!( tag, @@ -348,6 +358,12 @@ fn heading_level(level: HeadingLevel) -> u8 { } } +/// `
`, how a cell or a heading writes a break. +fn is_break(html: &str) -> bool { + html.trim_matches(['<', '>', '/', ' ']) + .eq_ignore_ascii_case("br") +} + /// HTML read as the text it shows. fn without_tags(html: &str) -> String { let mut text = String::new(); @@ -388,3 +404,44 @@ fn autolinks(text: &str) -> Vec<(&str, Option)> { } pieces } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_empty_item_or_quote_has_a_paragraph_to_type_in() { + let empty = Block::Paragraph(Vec::new()); + let item = |checked| Item { + checked, + blocks: vec![empty.clone()], + }; + for (markdown, kind, checked) in [ + ("-", ListKind::Bullet, false), + ("2.", ListKind::Ordered { start: 2 }, false), + ("- [x] \n", ListKind::Task, true), + ] { + let items = vec![item(checked)]; + assert_eq!( + read(markdown).blocks, + [Block::List { kind, items }], + "{markdown}" + ); + } + assert_eq!(read(">").blocks, [Block::Quote(vec![empty])]); + } + + #[test] + fn a_break_written_in_html_is_a_break() { + for html in ["
", "
", "
", "
"] { + let document = read(&format!("a{html}b")); + let expected = vec![Inline::text("a"), Inline::HardBreak, Inline::text("b")]; + assert_eq!(document.blocks, [Block::Paragraph(expected)], "{html}"); + } + let document = read("ab"); + assert_eq!( + document.blocks, + [Block::Paragraph(vec![Inline::text("ab")])] + ); + } +} diff --git a/crates/richtext/src/write.rs b/crates/richtext/src/write.rs index fd72522c8..97d06e84a 100644 --- a/crates/richtext/src/write.rs +++ b/crates/richtext/src/write.rs @@ -2,8 +2,11 @@ //! line apart, tight lists, a table padded to its widest cell and set apart by one more blank //! line on each side, a hard break as two spaces, and typed text escaped by `escape`. +use std::cmp::Reverse; + use crate::escape::escape; -use crate::model::{Block, Cell, Document, Inline, Item, ListKind}; +use crate::inlines::{Mark, normalize, put, wears}; +use crate::model::{Block, Cell, Document, Inline, Item, ListKind, Marks}; /// The narrowest column a table writes, as its separator's `---`. const MIN_COLUMN: usize = 3; @@ -22,7 +25,7 @@ fn block(block: &Block) -> String { match block { Block::Paragraph(content) => inlines(content), Block::Heading { level, content } => { - format!("{} {}", "#".repeat(usize::from(*level)), inlines(content)) + format!("{} {}", "#".repeat(usize::from(*level)), one_line(content)) } Block::List { kind, items } => list(*kind, items), Block::Quote(inner) => blocks(inner, "\n\n") @@ -38,11 +41,14 @@ fn block(block: &Block) -> String { .join("\n"), Block::CodeBlock { language, text } => { let newline = if text.is_empty() { "" } else { "\n" }; - format!("```{language}\n{text}{newline}```") + let fence = "`".repeat(longest_backticks(text).max(2) + 1); + format!("{fence}{language}\n{text}{newline}{fence}") } Block::Table(rows) => format!("\n{}\n", table(rows)), Block::Image { alt, src, width } => { - format!("![{alt}]({})", crate::picture::written(src, *width)) + let alt = escape(alt, false).replace(']', "\\]"); + let src = crate::picture::written(src, *width); + format!("![{alt}]({})", address(&src)) } Block::Rule => "---".to_owned(), } @@ -65,7 +71,7 @@ fn list(kind: ListKind, items: &[Item]) -> String { ListKind::Ordered { .. } => " ".repeat(marker.len()), ListKind::Bullet | ListKind::Task => " ".to_owned(), }; - let body = blocks(&item.blocks, "\n"); + let body = item_blocks(kind, &item.blocks); let mut lines = body.split('\n'); let first = lines.next().unwrap_or_default(); let rest: Vec = lines @@ -86,10 +92,60 @@ fn list(kind: ListKind, items: &[Item]) -> String { .join("\n") } +/// An item's blocks a line apart, one more where the next would be read into the one before. +fn item_blocks(kind: ListKind, blocks: &[Block]) -> String { + let mut out = String::new(); + // A box is followed by text alone, and `- ---` is one rule. + let text = matches!( + blocks.first(), + Some(Block::Paragraph(_) | Block::Image { .. }) + ); + if kind == ListKind::Task && !text || blocks.first() == Some(&Block::Rule) { + out.push('\n'); + } + for (at, each) in blocks.iter().enumerate() { + if at > 0 { + let between = if joins(&blocks[at - 1], each) { + "\n\n" + } else { + "\n" + }; + out.push_str(between); + } + out.push_str(&block(each)); + } + out +} + +fn joins(before: &Block, after: &Block) -> bool { + let paragraph = match before { + Block::Paragraph(content) => !content.is_empty(), + Block::Image { .. } => true, + _ => false, + }; + // Lists and quotes end on a paragraph, which the next line continues. + let continued = paragraph || matches!(before, Block::List { .. } | Block::Quote(_)); + match after { + Block::Paragraph(content) => continued && !content.is_empty(), + Block::Image { .. } => continued, + Block::Quote(_) => matches!(before, Block::Quote(_)), + Block::Rule => paragraph, + // Only a list starting at 1, on an item with something in it, interrupts a paragraph. + Block::List { kind, items } => { + let blank = items.first().is_some_and(|item| match item.blocks.first() { + Some(Block::Paragraph(content)) => content.is_empty(), + first => first == Some(&Block::Rule), + }); + paragraph && (blank || matches!(kind, ListKind::Ordered { start: 0 | 2.. })) + } + _ => false, + } +} + fn table(rows: &[Vec]) -> String { let written: Vec> = rows .iter() - .map(|row| row.iter().map(|cell| inlines(cell)).collect()) + .map(|row| row.iter().map(|content| cell(content)).collect()) .collect(); let columns = written.iter().map(Vec::len).max().unwrap_or(0); let widths: Vec = (0..columns) @@ -128,41 +184,182 @@ fn table(rows: &[Vec]) -> String { out.join("\n") } -/// Marked runs: each mark's delimiters around the run that wears it. +fn cell(content: &[Inline]) -> String { + one_line(content).replace('|', "\\|") +} + +/// What a cell and a heading hold: their breaks are `
`. +fn one_line(content: &[Inline]) -> String { + inlines(content).replace(" \n", "
").replace('\n', " ") +} + +/// Marked runs: a mark is opened before the first run that wears it and closed after the last. fn inlines(content: &[Inline]) -> String { + let runs = unmarked_edges(content); let mut out = String::new(); - for inline in content { - match inline { - Inline::HardBreak => out.push_str(" \n"), - Inline::Text { text, marks } => { - let starts_line = out.is_empty() || out.ends_with('\n'); - let mut run = if marks.code { - format!("`{text}`") - } else { - escape(text, starts_line) - }; - if marks.strike { - run = format!("~~{run}~~"); - } - if marks.italic { - run = format!("*{run}*"); - } - if marks.bold { - run = format!("**{run}**"); - } - if let Some(href) = &marks.link { - run = format!("[{run}]({href})"); - } - out.push_str(&run); - } + let mut open: Vec = Vec::new(); + for (at, inline) in runs.iter().enumerate() { + let Inline::Text { text, marks } = inline else { + close(&mut out, &mut open, 0); + out.push_str(" \n"); + continue; + }; + let still = open.iter().take_while(|mark| wears(marks, mark)).count(); + close(&mut out, &mut open, still); + let starts_line = out.is_empty() || out.ends_with('\n'); + let mut opening = worn(marks); + opening.retain(|mark| !open.contains(mark)); + opening.sort_by_key(|mark| Reverse(lasts(&runs[at..], mark))); + for mark in opening { + out.push_str(delimiter(&mark)); + open.push(mark); + } + if marks.code { + out.push_str(&code_span(text)); + continue; + } + let text = escape(text, starts_line); + if marks.link.is_some() { + out.push_str(&text.replace(']', "\\]")); + } else { + out.push_str(&text); } } + close(&mut out, &mut open, 0); out } +fn close(out: &mut String, open: &mut Vec, still: usize) { + for mark in open.drain(still..).rev() { + if let Mark::Link(Some(href)) = &mark { + out.push_str("]("); + out.push_str(&address(href)); + out.push(')'); + } else { + out.push_str(delimiter(&mark)); + } + } +} + +fn delimiter(mark: &Mark) -> &'static str { + match mark { + Mark::Link(_) => "[", + Mark::Bold => "**", + Mark::Italic => "*", + Mark::Strike => "~~", + Mark::Code => "`", + } +} + +/// The marks of a run but its code, the outermost first where all last as long. +fn worn(marks: &Marks) -> Vec { + let mut worn = Vec::new(); + if marks.link.is_some() { + worn.push(Mark::Link(marks.link.clone())); + } + for mark in [Mark::Bold, Mark::Italic, Mark::Strike] { + if wears(marks, &mark) { + worn.push(mark); + } + } + worn +} + +/// How many runs wear the mark, from the first on. +fn lasts(runs: &[Inline], mark: &Mark) -> usize { + runs.iter() + .take_while(|run| matches!(run, Inline::Text { marks, .. } if wears(marks, mark))) + .count() +} + +/// Emphasis is read as such only against a word: the spaces at its ends go outside it. +fn unmarked_edges(content: &[Inline]) -> Vec { + let mut pieces: Vec = content.iter().flat_map(around_spaces).collect(); + for mark in [Mark::Bold, Mark::Italic, Mark::Strike] { + unmark_spaces(pieces.iter_mut(), &mark); + unmark_spaces(pieces.iter_mut().rev(), &mark); + } + normalize(&mut pieces); + pieces +} + +/// The spaces a run starts with, what is between, and those it ends with. +fn around_spaces(inline: &Inline) -> Vec { + let Inline::Text { text, marks } = inline else { + return vec![inline.clone()]; + }; + if marks.code { + return vec![inline.clone()]; + } + let ended = text.trim_end(); + let word = ended.trim_start(); + [ + &ended[..ended.len() - word.len()], + word, + &text[ended.len()..], + ] + .into_iter() + .map(|text| Inline::Text { + text: text.to_owned(), + marks: marks.clone(), + }) + .collect() +} + +/// The spaces met before the first word of each run wearing `mark`. +fn unmark_spaces<'a>(pieces: impl Iterator, mark: &Mark) { + let mut inside = false; + for piece in pieces { + let Inline::Text { text, marks } = piece else { + inside = false; + continue; + }; + if !inside && !marks.code && text.trim().is_empty() { + put(marks, mark, false); + } else { + inside = wears(marks, mark); + } + } +} + +/// Fenced by one backtick more than it holds, set off by a space its own edge would lose. +fn code_span(text: &str) -> String { + let fence = "`".repeat(longest_backticks(text) + 1); + let spaced = text.starts_with(' ') && text.ends_with(' ') && !text.trim().is_empty(); + let set_off = spaced || text.starts_with('`') || text.ends_with('`'); + let pad = if set_off { " " } else { "" }; + format!("{fence}{pad}{text}{pad}{fence}") +} + +fn longest_backticks(text: &str) -> usize { + text.split(|glyph| glyph != '`') + .map(str::len) + .max() + .unwrap_or(0) +} + +/// Between angle brackets where a space or a lone parenthesis would end it. +fn address(href: &str) -> String { + let mut depth = 0; + let mut balanced = true; + for glyph in href.chars() { + match glyph { + '(' => depth += 1, + ')' => depth -= 1, + _ => {} + } + balanced &= depth >= 0; + } + if balanced && depth == 0 && !href.starts_with('<') && !href.contains(char::is_whitespace) { + return href.to_owned(); + } + format!("<{}>", href.replace('<', "\\<").replace('>', "\\>")) +} + #[cfg(test)] mod tests { - use crate::{read, write}; + use super::*; + use crate::read; fn round(markdown: &str) -> String { write(&read(markdown)) @@ -193,4 +390,271 @@ mod tests { "[**gras**](https://a.fr)" ); } + + /// A run wearing the marks named by `worn`: `b`, `i`, `s`, `c`, and `l` a link. + fn run(worn: &str, text: &str) -> Inline { + let link = worn.contains('l').then(|| "https://a.fr".to_owned()); + Inline::Text { + text: text.to_owned(), + marks: Marks { + bold: worn.contains('b'), + italic: worn.contains('i'), + strike: worn.contains('s'), + code: worn.contains('c'), + link, + }, + } + } + + fn paragraph(content: Vec) -> Document { + Document { + blocks: vec![Block::Paragraph(content)], + } + } + + #[track_caller] + fn written(document: &Document, expected: &str) { + let markdown = write(document); + assert_eq!(markdown, expected); + assert_eq!(read(&markdown), *document, "read back"); + } + + #[test] + fn a_mark_is_written_once_around_the_runs_that_wear_it() { + for (content, expected) in [ + (vec![run("b", "a "), run("bi", "b")], "**a *b***"), + (vec![run("bi", "a"), run("b", " b")], "***a* b**"), + ( + vec![run("i", "a "), run("bi", "b"), run("i", " c")], + "*a **b** c*", + ), + (vec![run("b", "a"), run("i", "b")], "**a***b*"), + ( + vec![run("b", "x "), run("bl", "a"), run("b", " y")], + "**x [a](https://a.fr) y**", + ), + ( + vec![run("l", "a"), run("lb", "b")], + "[a**b**](https://a.fr)", + ), + (vec![run("bisl", "a")], "[***~~a~~***](https://a.fr)"), + (vec![run("bc", "a"), run("b", "b")], "**`a`b**"), + ] { + written(¶graph(content), expected); + } + } + + #[test] + fn a_mark_is_closed_before_a_break_and_opened_after_it() { + written( + ¶graph(vec![run("b", "a"), Inline::HardBreak, run("b", "b")]), + "**a** \n**b**", + ); + } + + /// `**a **b` is stars and letters, for Markdown. + #[test] + fn the_spaces_at_the_ends_of_a_mark_are_written_outside_it() { + for (content, expected) in [ + (vec![run("b", "a "), run("", "b")], "**a** b"), + (vec![run("", "a"), run("i", " b")], "a *b*"), + (vec![run("s", " \u{a0}a "), run("", "b")], " \u{a0}~~a~~ b"), + ( + vec![run("b", "a "), run("bi", " "), run("", "b")], + "**a** b", + ), + (vec![run("", "a"), run("b", " "), run("", "b")], "a b"), + ] { + assert_eq!(write(¶graph(content)), expected); + } + } + + #[test] + fn a_code_span_is_fenced_by_more_backticks_than_it_holds() { + for (text, expected) in [ + ("a`b", "``a`b``"), + ("`a", "`` `a ``"), + ("a``", "``` a`` ```"), + (" a ", "` a `"), + (" a", "` a`"), + (" ", "` `"), + ] { + written(¶graph(vec![run("c", text)]), expected); + } + } + + #[test] + fn a_code_block_is_fenced_by_more_backticks_than_it_holds() { + for (text, fence) in [ + ("a ` b", "```"), + ("```\na\n```", "````"), + ("`````", "``````"), + ] { + let block = Block::CodeBlock { + language: "md".to_owned(), + text: text.to_owned(), + }; + written( + &Document { + blocks: vec![block], + }, + &format!("{fence}md\n{text}\n{fence}"), + ); + } + } + + #[test] + fn a_cell_holds_one_line_and_its_bars() { + for (content, expected) in [ + ( + vec![run("", "a"), Inline::HardBreak, run("", "b")], + "a
b", + ), + (vec![run("", "a|b")], r"a\|b"), + (vec![run("", r"a\|b")], r"a\\\|b"), + (vec![run("c", "a|b")], r"`a\|b`"), + ] { + let table = Block::Table(vec![vec![content, vec![run("", "c")]]]); + let dashes = "-".repeat(expected.len()); + written( + &Document { + blocks: vec![table], + }, + &format!("| {expected} | c |\n| {dashes} | --- |"), + ); + } + } + + #[test] + fn a_heading_holds_one_line() { + let heading = |content| Document { + blocks: vec![Block::Heading { level: 2, content }], + }; + written( + &heading(vec![run("", "a"), Inline::HardBreak, run("b", "b")]), + "## a
**b**", + ); + assert_eq!(write(&heading(vec![run("", "a\nb")])), "## a b"); + } + + #[test] + fn a_bracket_stays_in_its_link_or_in_its_image() { + for (text, expected) in [ + ("a]b", r"[a\]b](https://a.fr)"), + ("[a]", r"[\[a\]](https://a.fr)"), + ] { + written(¶graph(vec![run("l", text)]), expected); + } + let image = Block::Image { + alt: "a]b*c*".to_owned(), + src: "x.png".to_owned(), + width: None, + }; + written( + &Document { + blocks: vec![image], + }, + r"![a\]b\*c\*](x.png)", + ); + } + + #[test] + fn an_address_ends_where_it_ended() { + for (href, expected) in [ + ("https://a.fr/b_(c)", "https://a.fr/b_(c)"), + ("", ""), + ("a b", "
"), + ("a)", ""), + ("(a", "<(a>"), + (")a(", "<)a(>"), + ("", r"<\>"), + ] { + let mut link = run("", "x"); + if let Inline::Text { marks, .. } = &mut link { + marks.link = Some(href.to_owned()); + } + written(¶graph(vec![link]), &format!("[x]({expected})")); + } + } + + /// Tight, as an item is, where what follows would not be read into it. + #[test] + fn an_item_s_blocks_are_parted_where_the_next_would_continue_the_one_before() { + for (markdown, tight) in [ + ("- a\n\n b", false), + ("- a\n\n ---", false), + ("- a\n\n 3. b", false), + ("- a\n\n 0. b", false), + ("- a\n\n 1. ", false), + ("- a\n\n - ", false), + ("- > a\n\n b", false), + ("- > a\n\n > b", false), + ("- - a\n\n b", false), + ("- a\n\n ![b](c)", false), + ("- a\n 1. b", true), + ("- a\n - b", true), + ("- a\n > b", true), + ("- a\n # b", true), + ("- # a\n b", true), + ("- ```\n a\n ```\n b", true), + ] { + let document = read(markdown); + assert_eq!(write(&document), markdown); + assert_eq!(document.blocks.len(), 1, "{markdown}"); + assert_eq!(!markdown.contains("\n\n"), tight); + } + } + + #[test] + fn what_starts_an_item_is_read_in_it() { + for markdown in [ + "- \n ---", + "1. \n ---\n a", + "- [ ] \n # a", + "- [x] \n ```\n a\n ```", + "- [ ] \n > a", + "- [ ] \n - a", + "- [ ] ![a](b)", + "- # a", + "- > a", + ] { + let document = read(markdown); + assert_eq!(write(&document), markdown); + assert_eq!(document.blocks.len(), 1, "{markdown}"); + } + let rule = Block::List { + kind: ListKind::Task, + items: vec![Item { + checked: true, + blocks: vec![Block::Rule, Block::Paragraph(vec![run("", "a")])], + }], + }; + let document = Document { blocks: vec![rule] }; + assert_eq!(read(&write(&document)), document); + } + + #[test] + fn a_star_against_a_field_is_a_star() { + for (text, expected) in [ + ("*{{a}}*", r"\*{{a}}\*"), + ("{{a}}_{{b}}", "{{a}}\\_{{b}}"), + ("{{a}} * {{b}}", "{{a}} * {{b}}"), + ] { + written(¶graph(vec![run("", text)]), expected); + } + } + + #[test] + fn four_spaces_that_start_a_paragraph_are_no_code() { + for (text, expected) in [ + (" a", " a"), + (" a", " a"), + ("\ta", " a"), + (" \ta", " a"), + ] { + let markdown = write(¶graph(vec![run("", text)])); + assert_eq!(markdown, expected); + assert!(matches!(read(&markdown).blocks[0], Block::Paragraph(_))); + } + } } diff --git a/docs/architecture.md b/docs/architecture.md index 34aea6457..74d575094 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1389,7 +1389,8 @@ and exporting write a Note as the Markdown it is, where a snippet is fenced. a test) and written back byte for byte, as `golden/markdown` and `golden/markdown-escape` hold. What the schema does not hold is read as what it shows: raw HTML as its text, a footnote as its brackets, a reference link inline, a bare `https://` - address as a link to itself. `richtext::escape` is `escapeMarkdownText`, ported rule for rule. + address as a link to itself. A cell and a heading hold one line: their breaks are `
`. + `richtext::escape` is `escapeMarkdownText`, ported rule for rule. Undo keeps the document and the selection before each transaction (`History`): a Note is a few kilobytes. - **Editing is `richtext::edit`'s**, the view `overlays/editor/rich.rs`'s. A caret is a path to a From 17111f296c1f85d48b9ef2ebd86453afd7e6cd9b Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 07:53:34 +0100 Subject: [PATCH 55/95] Database and errors: unit tests rewritten for opening, the queue and logs (#1783) Co-authored-by: Claude Opus 5.5 --- crates/engine/src/changelog/model.rs | 21 +++ crates/engine/src/db.rs | 258 ++++++++++++++------------- crates/engine/src/db/queue.rs | 60 +++++++ crates/engine/src/docs/model.rs | 38 ++++ crates/engine/src/docs/search.rs | 19 ++ crates/engine/src/error.rs | 225 +++++++++++++++++++++++ crates/engine/tests/formats.rs | 51 +----- 7 files changed, 498 insertions(+), 174 deletions(-) diff --git a/crates/engine/src/changelog/model.rs b/crates/engine/src/changelog/model.rs index 2e0df4df8..06b95c0dc 100644 --- a/crates/engine/src/changelog/model.rs +++ b/crates/engine/src/changelog/model.rs @@ -552,4 +552,25 @@ Everything above the first release is preamble. assert!(parse_section("\n \n").is_empty()); } } + + /// Glued to the entry above, a line of the next section would read as its end. + #[test] + fn a_heading_closes_the_entry_above_it() { + for heading in ["# Titre", "## [0.9.2]"] { + let sections = parse_section(&format!("- One.\n{heading}\n Loose.\n")); + assert_eq!(reads(§ions[0]), ["One.", "Loose."], "{heading}"); + } + let sections = parse_section("- One.\n### Fixed\n Loose.\n"); + assert_eq!( + (reads(§ions[0]), reads(§ions[1])), + (vec!["One.".to_owned()], vec!["Loose.".to_owned()]) + ); + } + + #[test] + fn a_dash_with_nothing_after_it_is_no_entry() { + let releases = parse("## 0.1.0\n\n- \n* Starred.\n-\n"); + + assert_eq!(reads(&releases[0].sections[0]), ["Starred. -"]); + } } diff --git a/crates/engine/src/db.rs b/crates/engine/src/db.rs index 13cdf82b6..3c8d95e64 100644 --- a/crates/engine/src/db.rs +++ b/crates/engine/src/db.rs @@ -326,174 +326,157 @@ pub mod iso8601 { #[cfg(test)] mod tests { use super::*; - use diesel::sql_types::{BigInt, Integer}; + use diesel::sql_types::BigInt; - fn in_memory() -> Db { - Mutex::new(Some(open_in_memory().unwrap())) + /// A pragma of this connection, as SQLite answers it. + fn pragma(library: &mut Library, name: &str) -> i64 { + #[derive(QueryableByName)] + struct Value { + #[diesel(sql_type = BigInt)] + value: i64, + } + + diesel::sql_query(format!( + "WITH found(value) AS (SELECT * FROM pragma_{name}) SELECT value FROM found" + )) + .get_result::(library.db()) + .unwrap() + .value } - /// Stays here rather than in `tests/`: `configure` is private. - #[test] - fn foreign_keys_are_enforced() { + /// Apart: SQLite has no table of this one. + fn mapped(library: &mut Library) -> i64 { #[derive(QueryableByName)] - struct ForeignKeys { - #[diesel(sql_type = Integer)] - foreign_keys: i32, + struct Value { + #[diesel(sql_type = BigInt)] + mmap_size: i64, } - let mut connection = open_in_memory().unwrap(); - - let enabled = diesel::sql_query("PRAGMA foreign_keys") - .get_result::(connection.db()) + diesel::sql_query("PRAGMA mmap_size") + .get_result::(library.db()) .unwrap() - .foreign_keys; + .mmap_size + } - assert_eq!(enabled, 1); + fn opened(scratch: &tempfile::TempDir) -> Library { + let path = scratch.path().join(crate::layout::DATABASE); + open(&path, test_vault().unwrap()).unwrap() } - /// SQLite would otherwise meet the damage on whichever query reads the broken page, days - /// later, with every launch copy a copy of the broken file. - #[test] - fn a_damaged_file_is_named_as_such_rather_than_opened() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let path = directory.join(crate::layout::DATABASE); + fn spaces(library: &mut Library) -> usize { + crate::spaces::store::list(library).unwrap().len() + } - // A real library, with enough in it to fill more than the first page. - { - let mut library = open(&path, test_vault().unwrap()).unwrap(); - for at in 0..40 { - crate::spaces::store::create(&mut library, &format!("Space {at}")).unwrap(); - } + /// Why opening was refused. Not `unwrap_err`: it would want `Library: Debug`, and a library + /// holds the key. + fn refusal(path: &Path) -> StorageError { + match open(path, test_vault().unwrap()) { + Ok(_) => panic!("{} opened", path.display()), + Err(error) => error, } + } - // Garbage past the header: a broken header fails to open rather than to check. - let mut bytes = std::fs::read(&path).unwrap(); - assert!(bytes.len() > 4096, "the corpus did not reach a second page"); - for byte in bytes.iter_mut().skip(4096).take(512) { - *byte = 0x42; + /// Each is per connection and not SQLite's default: cascades enforced, a file another + /// process holds waited for, commits not flushed one by one, the file read through a mapping. + #[test] + fn a_library_is_opened_with_its_pragmas() { + let scratch = tempfile::tempdir().unwrap(); + let mut library = opened(&scratch); + + for (name, value) in [ + ("foreign_keys", 1), + ("busy_timeout", 5000), + ("synchronous", 1), + ] { + assert_eq!(pragma(&mut library, name), value, "{name}"); } - std::fs::write(&path, &bytes).unwrap(); - - let Err(error) = open(&path, test_vault().unwrap()) else { - panic!("a damaged database opened as if it were sound"); - }; - - assert!(matches!(error, StorageError::Damaged(_)), "{error}"); - assert!( - format!("{error}").contains(&path.display().to_string()), - "the failure does not name the file: {error}" - ); + // A build of SQLite whose ceiling is lower answers that ceiling. + assert_eq!(mapped(&mut library), 1 << 30); } - /// A sound library answers the check and says nothing about it. #[test] - fn a_sound_library_passes_the_check_it_runs_at_every_open() { - let mut library = open_in_memory().unwrap(); + fn the_mapping_shrinks_once_the_index_is_read() { + let scratch = tempfile::tempdir().unwrap(); + let mut library = opened(&scratch); - assert!(quick_check(library.db()).is_ok()); + library.map_less().unwrap(); + + assert_eq!(mapped(&mut library), 1 << 26); } #[test] - fn a_database_that_will_not_open_says_which_file() { + fn a_library_knows_the_folder_it_is_in_and_is_numbered_once() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - // A directory fails to open the way a corrupt file or a permission would. - // Destructured: `unwrap_err` would want `Library: Debug`, and a library holds the key. - let Err(error) = open(&directory, test_vault().unwrap()) else { - panic!("a directory opened as a database"); - }; + let (first, second) = (opened(&scratch), opened(&scratch)); - assert!( - format!("{error}").contains(&directory.display().to_string()), - "the failure does not name the file: {error}" - ); + assert_eq!(first.directory(), scratch.path()); + assert!(first.number() > 0 && second.number() > first.number()); } - /// SQLite's default of zero turns a file another process holds for a moment into a - /// storage error on the first write. + /// Every function that writes several rows counts on it. #[test] - fn a_locked_database_is_waited_on_rather_than_reported() { - #[derive(QueryableByName)] - struct BusyTimeout { - #[diesel(sql_type = Integer)] - timeout: i32, - } + fn a_transaction_that_fails_keeps_nothing_of_what_it_wrote() { + let mut library = open_in_memory().unwrap(); + crate::spaces::store::create(&mut library, "Kept").unwrap(); + let before = spaces(&mut library); - let mut connection = open_in_memory().unwrap(); + let failed: Result<(), StorageError> = library.transaction(|connection, _| { + diesel::sql_query("DELETE FROM spaces").execute(connection)?; + Err(StorageError::Unavailable) + }); - let timeout = diesel::sql_query("PRAGMA busy_timeout") - .get_result::(connection.db()) - .unwrap() - .timeout; - - assert_eq!(timeout, 5000); + assert!(matches!(failed, Err(StorageError::Unavailable))); + assert_eq!(spaces(&mut library), before); } - /// `NORMAL` can lose the last commit to a power cut, and cannot corrupt the file. #[test] - fn commits_are_not_fsynced_one_by_one() { - #[derive(QueryableByName)] - struct Synchronous { - #[diesel(sql_type = Integer)] - synchronous: i32, - } - - let mut connection = open_in_memory().unwrap(); - - let level = diesel::sql_query("PRAGMA synchronous") - .get_result::(connection.db()) - .unwrap() - .synchronous; + fn a_sound_library_passes_the_check_run_at_every_open() { + let mut library = open_in_memory().unwrap(); - assert_eq!(level, 1); + assert!(quick_check(library.db()).is_ok()); } - /// Asked of a file: an in-memory database has nothing to map. A build of SQLite whose - /// ceiling is lower answers that ceiling, and the corpus would be read through the cache. + /// SQLite would otherwise meet the damage on whichever query reads the broken page, days + /// later, with every launch copy a copy of the broken file. #[test] - fn the_file_is_read_through_a_mapping() { - #[derive(QueryableByName)] - struct MmapSize { - #[diesel(sql_type = BigInt)] - mmap_size: i64, - } - + fn a_damaged_file_is_named_as_such_rather_than_opened() { let scratch = tempfile::tempdir().unwrap(); - let mut library = open(&scratch.path().join("notes.db"), test_vault().unwrap()).unwrap(); + let path = scratch.path().join(crate::layout::DATABASE); + // A real library, with enough in it to fill more than the first page. + { + let mut library = opened(&scratch); + for at in 0..40 { + crate::spaces::store::create(&mut library, &format!("Space {at}")).unwrap(); + } + } + // Garbage past the header: a broken header fails to open rather than to check. + let mut bytes = std::fs::read(&path).unwrap(); + assert!(bytes.len() > 4096, "the corpus did not reach a second page"); + bytes[4096..4096 + 512].fill(0x42); + std::fs::write(&path, &bytes).unwrap(); - let size = diesel::sql_query("PRAGMA mmap_size") - .get_result::(library.db()) - .unwrap() - .mmap_size; + let error = refusal(&path); - assert_eq!(size, 1 << 30); + assert!(matches!(error, StorageError::Damaged(_)), "{error}"); + let named = path.display().to_string(); + assert!(error.to_string().contains(&named), "{error}"); } + /// A directory fails to open the way a permission would. #[test] - fn the_mapping_shrinks_once_the_index_is_read() { - #[derive(QueryableByName)] - struct MmapSize { - #[diesel(sql_type = BigInt)] - mmap_size: i64, - } - + fn a_database_that_will_not_open_says_which_file() { let scratch = tempfile::tempdir().unwrap(); - let mut library = open(&scratch.path().join("notes.db"), test_vault().unwrap()).unwrap(); - library.map_less().unwrap(); + let error = refusal(scratch.path()); - let size = diesel::sql_query("PRAGMA mmap_size") - .get_result::(library.db()) - .unwrap() - .mmap_size; - assert_eq!(size, 1 << 26); + let named = scratch.path().display().to_string(); + assert!(error.to_string().contains(&named), "{error}"); } #[test] - fn a_healthy_connection_is_handed_over() { - let db = in_memory(); + fn the_library_open_is_handed_over() { + let db: Db = Mutex::new(Some(open_in_memory().unwrap())); assert!(lock(&db).is_ok()); } @@ -503,10 +486,37 @@ mod tests { fn a_library_still_locked_is_reported_rather_than_unwrapped() { let db: Db = Mutex::new(None); - let Err(error) = lock(&db) else { - panic!("a locked library must be reported, not handed over"); - }; + assert!(matches!(lock(&db).map(drop), Err(StorageError::Locked))); + let sent = lock_library(&db, 1).map(drop); + assert!(matches!(sent, Err(StorageError::Locked))); + } + + #[test] + fn a_lock_a_panic_left_behind_is_unavailable() { + let db: Arc = Arc::new(Mutex::new(None)); + let holding = Arc::clone(&db); + let _ = std::thread::spawn(move || { + let _held = holding.lock(); + panic!("while holding the library"); + }) + .join(); + + assert!(matches!( + lock(&db).map(drop), + Err(StorageError::Unavailable) + )); + } + + /// A send writes only into the library it read from. + #[test] + fn a_library_opened_since_is_not_the_one_a_send_read_from() { + let library = open_in_memory().unwrap(); + let number = library.number(); + let db: Db = Mutex::new(Some(library)); + + assert!(lock_library(&db, number).unwrap().is_some()); - assert!(matches!(error, StorageError::Locked)); + *db.lock().unwrap() = Some(open_in_memory().unwrap()); + assert!(lock_library(&db, number).unwrap().is_none()); } } diff --git a/crates/engine/src/db/queue.rs b/crates/engine/src/db/queue.rs index d8b66c5b9..62e447464 100644 --- a/crates/engine/src/db/queue.rs +++ b/crates/engine/src/db/queue.rs @@ -86,6 +86,7 @@ mod tests { use std::sync::{Arc, Mutex}; use super::*; + use crate::error::ErrorCode; fn block_on(future: impl Future) -> T { tokio::runtime::Builder::new_current_thread() @@ -115,4 +116,63 @@ mod tests { assert_eq!(*order.lock().unwrap(), [(1, true), (2, true), (3, true)]); assert!(!on_db_thread()); } + + /// The interface sends from its thread and waits elsewhere, in whatever order. + #[test] + fn a_job_submitted_is_queued_at_the_call_whenever_it_is_waited_for() { + let queue = DbQueue::start(); + let order = Arc::new(Mutex::new(Vec::new())); + let job = |n: u32| { + let order = Arc::clone(&order); + queue.submit(move || { + order.lock().unwrap().push(n); + Ok(n) + }) + }; + let (first, second) = (job(1), job(2)); + + let answers = block_on(async { (second.await.unwrap(), first.await.unwrap()) }); + + assert_eq!(answers, (2, 1)); + assert_eq!(*order.lock().unwrap(), [1, 2]); + } + + #[test] + fn a_job_s_own_failure_is_its_answer() { + let queue = DbQueue::start(); + + let failed = block_on(queue.run(|| Err::<(), _>(StorageError::Locked.into()))); + + assert_eq!(failed.unwrap_err().code, ErrorCode::Locked); + } + + /// A panic ends the process (D18); what waits meanwhile is answered rather than held. + #[test] + fn a_job_that_panics_and_those_after_it_are_answered_unavailable() { + let queue = DbQueue::start(); + + let fell = block_on(queue.run(|| -> Result<(), AppError> { panic!("a job fell") })); + let after = block_on(queue.run(|| Ok(()))); + + assert_eq!(fell.unwrap_err().code, ErrorCode::StorageUnavailable); + assert_eq!(after.unwrap_err().code, ErrorCode::StorageUnavailable); + } + + #[test] + fn a_queue_dropped_still_runs_what_it_was_sent() { + let queue = DbQueue::start(); + let sent = queue.submit(|| Ok(1)); + drop(queue); + + assert_eq!(block_on(sent).unwrap(), 1); + } + + /// Nested, as an integration test calling one data function inside another. + #[test] + fn a_thread_taken_for_the_db_one_is_itself_again_after() { + let nested = as_db_thread(|| as_db_thread(on_db_thread) && on_db_thread()); + + assert!(nested); + assert!(!on_db_thread()); + } } diff --git a/crates/engine/src/docs/model.rs b/crates/engine/src/docs/model.rs index 33f55321f..1d473a19b 100644 --- a/crates/engine/src/docs/model.rs +++ b/crates/engine/src/docs/model.rs @@ -661,4 +661,42 @@ mod tests { assert_eq!(slug("où-vont-mes-notes-"), "ou-vont-mes-notes"); assert_eq!(slug("L’API : `GET`, « v1 »"), "lapi-get-v1"); } + + #[test] + fn a_link_is_an_address_by_its_scheme_and_a_page_by_its_name() { + let to = |href: &str| match body(&format!("[a]({href})")).remove(0) { + Block::Paragraph(mut runs) => runs.remove(0), + other => panic!("{other:?}"), + }; + for address in ["https://devnotes.fr", "http://localhost:8080"] { + assert!( + matches!(to(address), Inline::Link { to: Target::Address(found), .. } if found == address) + ); + } + for page in ["start.md", "start.md#a"] { + assert!( + matches!(to(page), Inline::Link { to: Target::Page { id, .. }, .. } if id == "start"), + "{page}" + ); + } + for nowhere in ["", "start", "a/start.md", "a.b.md", "ftp://a"] { + assert!( + refused(&format!("[a]({nowhere})")).contains("leads nowhere"), + "{nowhere}" + ); + } + } + + #[test] + fn a_name_is_given_in_its_language_or_in_english() { + let names = Names { + fr: "Début".to_owned(), + en: "Start".to_owned(), + }; + + assert_eq!( + [names.of("fr"), names.of("en"), names.of("de")], + ["Début", "Start", "Start"] + ); + } } diff --git a/crates/engine/src/docs/search.rs b/crates/engine/src/docs/search.rs index a5e668bf6..23717f4c4 100644 --- a/crates/engine/src/docs/search.rs +++ b/crates/engine/src/docs/search.rs @@ -193,4 +193,23 @@ mod tests { ); assert_eq!(excerpt(text, "absent"), text); } + + /// Whether or not its own text says the word again. + #[test] + fn a_section_is_found_by_its_heading_alone() { + for language in ["fr", "en"] { + for section in sections(language) { + let word = section + .folded_heading + .split_whitespace() + .find(|word| !section.folded_text.contains(*word)); + let Some(word) = word else { continue }; + let hits = search_docs(language, word); + assert!( + hits.len() >= AT_MOST || hits.iter().any(|hit| hit.heading == section.heading), + "{language}: {word}" + ); + } + } + } } diff --git a/crates/engine/src/error.rs b/crates/engine/src/error.rs index 02aa6896f..4542f9f23 100644 --- a/crates/engine/src/error.rs +++ b/crates/engine/src/error.rs @@ -345,3 +345,228 @@ impl From for AppError { } } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::http::runner::DataFault; + use crate::http::send::SendError; + + fn text(text: &str) -> String { + text.to_string() + } + + /// Each failure of the storage, with the code it answers and the value its sentence states. + fn storage_errors() -> Vec<(StorageError, ErrorCode, Option<&'static str>)> { + use ErrorCode as C; + use StorageError as E; + vec![ + (E::NoteNotFound(text("x")), C::NoteNotFound, Some("id")), + (E::SpaceNotFound(text("x")), C::SpaceNotFound, Some("id")), + ( + E::DuplicateSpaceName(text("x")), + C::DuplicateSpaceName, + Some("name"), + ), + (E::FolderNotFound(text("x")), C::FolderNotFound, Some("id")), + ( + E::DuplicateFolderName(text("x")), + C::DuplicateFolderName, + Some("name"), + ), + ( + E::AttachmentNotFound(text("x")), + C::AttachmentNotFound, + Some("id"), + ), + ( + E::HttpItemNotFound(text("x")), + C::HttpItemNotFound, + Some("id"), + ), + ( + E::HttpEnvironmentNotFound(text("x")), + C::HttpEnvironmentNotFound, + Some("id"), + ), + ( + E::DuplicateEnvironmentName(text("x")), + C::DuplicateEnvironmentName, + Some("name"), + ), + ( + E::RevisionNotFound(text("x")), + C::RevisionNotFound, + Some("id"), + ), + ( + E::LibraryNotFound(text("x")), + C::LibraryNotFound, + Some("id"), + ), + (E::LibraryOpen, C::LibraryOpen, None), + (E::LastLibrary, C::LastLibrary, None), + ( + E::NothingToSetAside(text("x")), + C::NothingToSetAside, + Some("path"), + ), + (E::BackupNotFound(text("x")), C::BackupNotFound, Some("id")), + ( + E::BackupUnopenable(text("x")), + C::BackupUnopenable, + Some("id"), + ), + (E::File(text("x")), C::FileAccess, None), + (E::ImportFormat(text("x")), C::ImportFormat, None), + (E::Damaged(text("x")), C::LibraryDamaged, None), + (E::WrongPassphrase, C::WrongPassphrase, None), + (E::PassphraseRequired, C::PassphraseRequired, None), + (E::Unavailable, C::StorageUnavailable, None), + (E::Locked, C::Locked, None), + // Nothing here gives the interface anything to do beyond reporting the failure. + ( + E::CorruptRow { + id: text("x"), + field: "tags", + }, + C::Storage, + None, + ), + (E::SchemaTooRecent(text("x")), C::Storage, None), + (E::Migration(text("x")), C::Storage, None), + (E::Vault(text("x")), C::Storage, None), + (E::Sqlite(diesel::result::Error::NotFound), C::Storage, None), + ] + } + + #[test] + fn a_failure_of_the_storage_answers_its_code_and_what_its_sentence_states() { + for (error, code, named) in storage_errors() { + let answered = AppError::from(error); + + assert_eq!(answered.code, code); + let stated: Vec<_> = answered + .params + .iter() + .map(|(key, value)| (key.as_str(), value.as_str())) + .collect(); + let expected: Vec<_> = named.iter().map(|key| (*key, "x")).collect(); + assert_eq!(stated, expected, "{code:?}"); + assert!(!answered.detail.is_empty()); + } + } + + #[test] + fn a_file_too_large_says_its_name_and_the_limit() { + let answered = AppError::from(StorageError::TooLarge { + name: text("film.mp4"), + limit_mb: 25, + }); + + assert_eq!(answered.code, ErrorCode::FileTooLarge); + assert_eq!( + ( + answered.params["name"].as_str(), + answered.params["limit"].as_str() + ), + ("film.mp4", "25") + ); + } + + #[test] + fn an_input_refused_names_its_field_wherever_it_was_refused() { + let refused = || ValidationError::new("folderId", "a folder cannot move into itself"); + + for answered in [ + AppError::from(refused()), + AppError::from(StorageError::from(refused())), + ] { + assert_eq!( + (answered.code, answered.params["field"].as_str()), + (ErrorCode::InvalidInput, "folderId") + ); + } + } + + /// It aborts startup: `storage` is the honest code, and its version is in the detail. + #[test] + fn a_schema_too_recent_says_the_migration_it_does_not_know() { + let answered = AppError::from(StorageError::SchemaTooRecent(text("2099-01-01-000000"))); + + assert_eq!(answered.code, ErrorCode::Storage); + assert!(answered.detail.contains("2099-01-01-000000")); + } + + #[test] + fn a_storage_unavailable_is_the_same_wherever_it_is_said() { + assert_eq!( + AppError::storage_unavailable().code, + AppError::from(StorageError::Unavailable).code + ); + assert!(AppError::storage_unavailable().params.is_empty()); + } + + /// ⚠️ Never a name, a file, a URL or a script's words: a log is read by others. + #[test] + fn a_log_never_says_what_was_typed() { + let typed = || text("s3cret-typed"); + let errors = [ + AppError::from(StorageError::DuplicateSpaceName(typed())), + StorageError::DuplicateFolderName(typed()).into(), + StorageError::DuplicateEnvironmentName(typed()).into(), + StorageError::NothingToSetAside(typed()).into(), + StorageError::File(typed()).into(), + StorageError::TooLarge { + name: typed(), + limit_mb: 1, + } + .into(), + StorageError::ImportFormat(typed()).into(), + ValidationError::new("title", typed()).into(), + SendError::Variable(typed()).into(), + SendError::InvalidUrl(typed()).into(), + SendError::Unresolved(typed()).into(), + SendError::Refused(typed()).into(), + SendError::Tls(typed()).into(), + SendError::FileUnreadable(typed()).into(), + SendError::FileTooLarge(typed()).into(), + SendError::GraphqlVariables(typed()).into(), + SendError::Network(typed()).into(), + SendError::SocketScheme { + twin: Some(typed()), + } + .into(), + ]; + for error in errors { + let line = error.for_log(); + assert!(!line.contains("s3cret"), "{line}"); + assert_eq!(line, format!("{:?}", error.code)); + } + } + + /// An identifier, an instant, a count: nothing anyone typed. + #[test] + fn a_log_says_the_detail_of_a_failure_that_holds_nothing_typed() { + let errors = [ + AppError::from(StorageError::NoteNotFound(text("n-1"))), + StorageError::BackupNotFound(text("2026-07-25_09-05-07")).into(), + StorageError::Locked.into(), + StorageError::Damaged(text("page 3")).into(), + StorageError::CorruptRow { + id: text("n-1"), + field: "tags", + } + .into(), + SendError::Handshake(403).into(), + SendError::Fell.into(), + DataFault::Empty.into(), + ]; + for error in errors { + assert_eq!( + error.for_log(), + format!("{:?}: {}", error.code, error.detail) + ); + } + } +} diff --git a/crates/engine/tests/formats.rs b/crates/engine/tests/formats.rs index 635b420d9..40ee45d0a 100644 --- a/crates/engine/tests/formats.rs +++ b/crates/engine/tests/formats.rs @@ -1,13 +1,10 @@ //! The JSON shape of what the core writes and reads back (an export, its notes, spaces and -//! attachments), and the codes its errors carry: the compiler checks none of it. +//! attachments): the compiler checks none of it. use std::collections::BTreeMap; use engine::attachments::model::Attachment; use engine::db::iso8601; -use engine::error::StorageError; -use engine::error::ValidationError; -use engine::error::{AppError, ErrorCode}; use engine::notes::checklist::ChecklistItem; use engine::notes::kind::NoteKind; use engine::notes::language::Language; @@ -100,32 +97,6 @@ fn a_space_serializes_with_camel_case_keys() { ); } -#[test] -fn every_error_carries_a_non_empty_detail() { - let errors = [ - StorageError::NoteNotFound("n-1".to_string()), - StorageError::SpaceNotFound("s-1".to_string()), - StorageError::DuplicateSpaceName("Personal".to_string()), - StorageError::SchemaTooRecent("2099-01-01-000000".to_string()), - StorageError::Migration("base verrouillée".to_string()), - ]; - - for error in errors { - assert!(!AppError::from(error).detail.is_empty()); - } -} - -#[test] -fn a_schema_too_recent_degrades_to_storage_rather_than_leaking_a_dead_code() { - // It aborts startup, so `storage` is the honest code. - let error = AppError::from(StorageError::SchemaTooRecent( - "2099-01-01-000000".to_string(), - )); - - assert!(matches!(error.code, ErrorCode::Storage)); - assert!(error.detail.contains("2099-01-01-000000")); -} - #[test] fn an_instant_is_written_as_a_string_read_back_as_a_date() { let json = serde_json::to_value(sample()).unwrap(); @@ -244,23 +215,3 @@ fn the_values_of_the_fields_are_written_as_a_named_map() { serde_json::json!({ "host": "db.internal" }) ); } - -#[test] -fn an_error_carries_its_code_and_what_to_interpolate() { - let duplicate = AppError::from(StorageError::DuplicateSpaceName("Personal".to_string())); - assert_eq!(duplicate.code, ErrorCode::DuplicateSpaceName); - assert_eq!(duplicate.params["name"], "Personal"); - - let missing = AppError::from(StorageError::HttpItemNotFound("r-1".to_string())); - assert_eq!(missing.code, ErrorCode::HttpItemNotFound); - assert_eq!(missing.params["id"], "r-1"); - - let refused = AppError::from(StorageError::from(ValidationError::new( - "folderId", - "a folder cannot move into itself", - ))); - assert_eq!(refused.code, ErrorCode::InvalidInput); - assert_eq!(refused.params["field"], "folderId"); - - assert!(AppError::storage_unavailable().params.is_empty()); -} From f542fbaae3248b77decdcd26a652920f758463a7 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 07:53:45 +0100 Subject: [PATCH 56/95] Tools: unit tests completed for conversions, text and comparisons (#1780) * Tools, encoding and conversion: gaps * tools text gaps --- crates/engine/src/tools/bases.rs | 68 +++++++++++ crates/engine/src/tools/colour.rs | 67 +++++++++++ crates/engine/src/tools/convert.rs | 75 +++++++++++- crates/engine/src/tools/convert/xml.rs | 33 ++++++ crates/engine/src/tools/diff.rs | 154 +++++++++++++++++++++++++ crates/engine/src/tools/files.rs | 23 +++- crates/engine/src/tools/image.rs | 36 ++++++ crates/engine/src/tools/numbers.rs | 27 +++++ crates/engine/src/tools/qr.rs | 88 ++++++++++++++ crates/engine/src/tools/sizes.rs | 22 ++++ crates/engine/src/tools/stats.rs | 32 +++++ crates/engine/src/tools/text.rs | 95 +++++++++++++++ crates/engine/src/tools/text_diff.rs | 126 ++++++++++++++++++++ 13 files changed, 841 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/tools/bases.rs b/crates/engine/src/tools/bases.rs index e50175be7..ba90aca06 100644 --- a/crates/engine/src/tools/bases.rs +++ b/crates/engine/src/tools/bases.rs @@ -855,7 +855,9 @@ mod tests { ("01000011 01100001", ByteEncoding::Binary, "Ca"), ("0x43 0x61", ByteEncoding::Hex, "Ca"), ("43:61:66", ByteEncoding::Hex, "Caf"), + ("43-61,66", ByteEncoding::Hex, "Caf"), ("67 97 102", ByteEncoding::Decimal, "Caf"), + ("67,97, 102", ByteEncoding::Decimal, "Caf"), ("INQWM===", ByteEncoding::Base32, "Caf"), ("w6l0w6k_Pg", ByteEncoding::Base64Url, "été?>"), ("Q2Fmw6k=", ByteEncoding::Base64, "Café"), @@ -868,6 +870,72 @@ mod tests { } } + /// Its letters alone are Base32's: its length is not. + #[test] + fn a_shape_no_reading_of_it_fits_is_not_offered() { + for (pasted, refused) in [ + ("ABC", ByteEncoding::Base32), + ("Q2Fm-w6k", ByteEncoding::Base64), + ("Q2Fm-", ByteEncoding::Base64Url), + ("4 3", ByteEncoding::Hex), + ] { + let answer = read(pasted, None); + assert_ne!(answer.read_as, refused, "{pasted}"); + assert!(!answer.also.contains(&refused), "{pasted}"); + } + } + + #[test] + fn nothing_to_decode_is_of_no_length() { + for reading in [ + ByteEncoding::Hex, + ByteEncoding::Binary, + ByteEncoding::Decimal, + ] { + let decoded = read(" ", Some(reading)).decoded; + let expected = DecodedBytes::Invalid { + problem: DecodeProblem::Length, + at: None, + character: None, + }; + assert_eq!(decoded, expected, "{reading:?}"); + } + } + + /// Each group is whole bytes: `67 97 102` is decimal, not hexadecimal. + #[test] + fn hexadecimal_of_an_odd_length_is_refused() { + for text in ["436", "43 6", "4 36 1", "43:6:61"] { + let decoded = read(text, Some(ByteEncoding::Hex)).decoded; + assert!( + matches!( + decoded, + DecodedBytes::Invalid { + problem: DecodeProblem::Length, + .. + } + ), + "{text}: {decoded:?}" + ); + } + } + + #[test] + fn a_file_keeps_its_padding_in_base64_and_not_in_its_url_form() { + let folder = tempfile::tempdir().unwrap(); + let source = folder.path().join("a"); + std::fs::write(&source, [0xfb, 0xff]).unwrap(); + + let Base64FileAnswer::Encoded { + base64, base64_url, .. + } = encode_file(&source.to_string_lossy()) + else { + panic!("not encoded"); + }; + + assert_eq!((base64.as_str(), base64_url.as_str()), ("+/8=", "-_8")); + } + #[test] fn an_ambiguous_text_says_what_else_it_could_be_and_takes_a_forced_reading() { let answer = read("deadbeef", None); diff --git a/crates/engine/src/tools/colour.rs b/crates/engine/src/tools/colour.rs index b0dda37e6..7cd7b2738 100644 --- a/crates/engine/src/tools/colour.rs +++ b/crates/engine/src/tools/colour.rs @@ -763,4 +763,71 @@ mod tests { }) ); } + + /// White on grey, its ratio either side of each level. + #[test] + fn a_level_is_reached_at_its_own_ratio() { + let grey = |value: u8| Rgba { + r: f64::from(value) / 255.0, + g: f64::from(value) / 255.0, + b: f64::from(value) / 255.0, + a: 1.0, + }; + let sizes = |value: u8| { + let judged = contrast(grey(value), WHITE); + ( + judged.ratio, + judged.aa.normal, + judged.aa.large, + judged.aaa.normal, + judged.aaa.large, + ) + }; + // The lightest grey that reaches 3, 4.5 and 7 on white, and the one after it. + for (value, aa, aa_large, aaa, aaa_large) in [ + (149, false, false, false, false), + (148, false, true, false, false), + (119, false, true, false, false), + (118, true, true, false, true), + (90, true, true, false, true), + (89, true, true, true, true), + ] { + let (ratio, normal, large, high, high_large) = sizes(value); + assert_eq!( + (normal, large, high, high_large), + (aa, aa_large, aaa, aaa_large), + "{value}: {ratio}" + ); + } + } + + /// The level asked is the next one missed; nothing is mended past the highest. + #[test] + fn a_contrast_is_mended_to_the_level_it_misses() { + let fixed = |value: u8| { + let grey = f64::from(value) / 255.0; + contrast( + Rgba { + r: grey, + g: grey, + b: grey, + a: 1.0, + }, + WHITE, + ) + .fix + .map(|fix| match fix { + ContrastFix::Found { level, hex } => (level, hex), + ContrastFix::Unreachable { level } => (level, String::new()), + }) + }; + + assert_eq!(fixed(149).map(|(level, _)| level), Some(WcagLevel::Aa)); + assert_eq!(fixed(118).map(|(level, _)| level), Some(WcagLevel::Aaa)); + assert_eq!(fixed(89), None); + // The nearest that does, not merely one that does. + let (_, hex) = fixed(149).unwrap(); + let shade = u8::from_str_radix(&hex[1..3], 16).unwrap(); + assert!((118..=119).contains(&shade), "{hex}"); + } } diff --git a/crates/engine/src/tools/convert.rs b/crates/engine/src/tools/convert.rs index b6c77e624..0a7f25a20 100644 --- a/crates/engine/src/tools/convert.rs +++ b/crates/engine/src/tools/convert.rs @@ -541,7 +541,78 @@ mod tests { #[test] fn a_position_counts_characters_not_bytes() { - // Byte 8 is the `x`, after two characters of three and two bytes on its line. - assert_eq!(position("é\né€x", 8), (2, 3)); + // Byte 8 is the `x`, after two characters of three and two bytes on its line; 9 is past + // it, 6 inside the euro sign. + for (offset, at) in [ + (0, (1, 1)), + (2, (1, 2)), + (3, (2, 1)), + (8, (2, 3)), + (6, (2, 2)), + (99, (2, 4)), + ] { + assert_eq!(position("é\né€x", offset), at, "{offset}"); + } + } + + #[test] + fn a_yaml_refusal_says_its_column_from_one() { + assert_eq!( + read_value("a: 1\nb: *nowhere\n", DataFormat::Yaml), + Err((2, 4)) + ); + } + + /// A list of mappings lends; an empty one, or one holding anything else, is a value. + #[test] + fn a_merge_key_that_lends_nothing_stays_an_ordinary_key() { + for (yaml, read) in [ + ("a:\n <<: []\n", serde_json::json!({ "a": { "<<": [] } })), + ( + "a:\n <<: [{b: 1}, 2]\n", + serde_json::json!({ "a": { "<<": [{ "b": 1 }, 2] } }), + ), + ( + "a:\n <<: [{b: 1}]\n", + serde_json::json!({ "a": { "b": 1 } }), + ), + ] { + assert_eq!(read_value(yaml, DataFormat::Yaml), Ok(read), "{yaml}"); + } + } + + /// The narrowest that fits: what parses as JSON is JSON, though YAML takes it too. + #[test] + fn a_format_is_known_by_the_shape_of_what_was_written() { + use DataFormat::{Json, Toml, Xml, Yaml}; + for (text, format) in [ + ("
", Xml), + ("\n{\"a\": 1}", Json), + ("{ broken", Json), + ("[1, 2]", Json), + ("[\"a\"]", Json), + ("[broken", Json), + ("[a, b]\n", Json), + ("[]", Json), + ("[server]\nport = 1", Toml), + ("[[products]] # a list\nname = 'x'", Toml), + ("[server", Json), + ("[a]b", Json), + ("42", Json), + ("\"a string\"", Json), + ("# a comment\n\n[server]\nport = 1", Toml), + ("title = \"x\"", Toml), + ("a.b-c_d = 1", Toml), + ("\"a key\" = 1", Toml), + ("# note\nname: x", Yaml), + ("= 1", Yaml), + ("a(b) = 1", Yaml), + ("f: x = 1", Yaml), + ("- a\n- b", Yaml), + ("plain text", Yaml), + ("", Yaml), + ] { + assert_eq!(detect(text), format, "{text:?}"); + } } } diff --git a/crates/engine/src/tools/convert/xml.rs b/crates/engine/src/tools/convert/xml.rs index 2d8e2c2b8..17aaf55bb 100644 --- a/crates/engine/src/tools/convert/xml.rs +++ b/crates/engine/src/tools/convert/xml.rs @@ -247,4 +247,37 @@ mod tests { assert!(read("").is_err()); assert!(read("text").is_err()); } + + #[test] + fn a_name_is_one_xml_takes() { + for (name, takes) in [ + ("a", true), + ("_a", true), + ("é", true), + ("a-b_c.d:e1", true), + ("", false), + ("1a", false), + ("-a", false), + ("a b", false), + ("a/b", false), + ] { + assert_eq!(is_name(name), takes, "{name:?}"); + let written = write(&serde_json::json!({ name: "x" })); + assert_eq!(written.is_ok(), takes, "{name:?}"); + } + } + + /// A quote needs escaping inside an attribute alone. + #[test] + fn what_xml_reserves_is_escaped() { + let value = serde_json::json!({ "a": { "@k": "\"<&>", "#text": "\"<&>" } }); + + let written = write(&value).ok().unwrap(); + + assert!( + written.ends_with("\"<&>\n"), + "{written}" + ); + assert_eq!(read(&written).ok().unwrap(), value); + } } diff --git a/crates/engine/src/tools/diff.rs b/crates/engine/src/tools/diff.rs index 02d21603f..37ff46f81 100644 --- a/crates/engine/src/tools/diff.rs +++ b/crates/engine/src/tools/diff.rs @@ -1018,4 +1018,158 @@ mod tests { assert_eq!(summaries(&changes), [(JsonChangeKind::Modified, "$.port")]); } + + /// Pretty JSON, two spaces, one line per value. + #[test] + fn a_document_is_laid_out_as_pretty_json_beside_its_twin() { + let text = r#"{"a":[1,{"b":[],"c":{}}],"d":"x"}"#; + + let (_, _, rows, _) = compared(text, text, true, true); + + let pretty = + serde_json::to_string_pretty(&serde_json::from_str::(text).unwrap()).unwrap(); + for side in [ + |row: &JsonDiffRow| row.left.clone(), + |row: &JsonDiffRow| row.right.clone(), + ] { + let lines: Vec<_> = rows.iter().map(|row| side(row).unwrap()).collect(); + let texts: Vec<&str> = lines.iter().map(|line| line.text.as_str()).collect(); + assert_eq!(texts.join("\n"), pretty); + assert!( + lines + .iter() + .zip(1..) + .all(|(line, number)| line.number == number) + ); + } + assert!(rows.iter().all(|row| row.kind == JsonDiffRowKind::Same)); + } + + /// For a change to scroll to: a container's braces are its own. + #[test] + fn a_row_names_the_value_it_writes() { + let (_, _, rows, _) = compared(r#"{"a":[1,{"b":2}]}"#, "{}", true, true); + + let paths: Vec<&str> = rows + .iter() + .filter(|row| row.left.is_some()) + .map(|row| row.path.as_str()) + .collect(); + assert_eq!( + paths, + [ + "$", "$.a", "$.a[0]", "$.a[1]", "$.a[1].b", "$.a[1]", "$.a", "$" + ] + ); + } + + /// Lists meet item for item, as objects do key for key. + #[test] + fn the_keys_of_an_object_in_a_list_follow_the_other_side_s_order() { + let (_, _, rows, _) = compared(r#"[{"a":1,"b":2}]"#, r#"[{"b":2,"a":1}]"#, true, true); + assert!( + rows.iter().all(|row| row.kind == JsonDiffRowKind::Same), + "{rows:?}" + ); + + let (_, _, rows, _) = compared(r#"[{"a":1,"b":2}]"#, r#"[{"b":2,"a":1}]"#, false, true); + assert!(rows.iter().any(|row| row.kind != JsonDiffRowKind::Same)); + } + + #[test] + fn spaces_in_a_string_make_a_row_differ_only_when_they_count() { + let kinds = |ignored: bool| -> Vec { + let (_, _, rows, _) = compared(r#"{"a":"x y"}"#, r#"{"a":"x y"}"#, true, ignored); + rows.iter().map(|row| row.kind).collect() + }; + + assert!( + kinds(true) + .iter() + .all(|kind| *kind == JsonDiffRowKind::Same) + ); + assert!( + kinds(false) + .iter() + .any(|kind| *kind != JsonDiffRowKind::Same) + ); + } + + /// Two objects of a list are one when only the order of their keys differs. + #[test] + fn an_object_of_a_list_is_the_same_whatever_its_order_when_it_is_ignored() { + let (ignored, ..) = compared(r#"[{"a":1,"b":2},3]"#, r#"[{"b":2,"a":1},3]"#, true, true); + let (counted, ..) = compared(r#"[{"a":1,"b":2},3]"#, r#"[{"b":2,"a":1},3]"#, false, true); + + assert!(ignored.is_empty()); + assert_eq!(summaries(&counted), [(JsonChangeKind::Reordered, "$[0]")]); + } + + #[test] + fn an_item_taken_out_of_a_list_is_said_where_it_was() { + let (changes, counts, _, patch) = compared("[1,2,3,4]", "[1,4]", true, true); + + assert_eq!( + summaries(&changes), + [ + (JsonChangeKind::Removed, "$[1]"), + (JsonChangeKind::Removed, "$[2]") + ] + ); + assert_eq!( + changes[0].before, + Some(ValueSummary::Scalar { + text: "2".to_owned() + }) + ); + assert_eq!(counts.removed, 2); + let mut document = serde_json::json!([1, 2, 3, 4]); + apply(&mut document, &patch); + assert_eq!(document, serde_json::json!([1, 4])); + } + + #[test] + fn several_items_added_in_a_row_are_added_in_their_order() { + for (a, b) in [ + ("[1]", "[1,2,3]"), + ("[1,9]", "[0,5,1,7,8,9]"), + ("[1,2,3]", "[7,8,9,10,11]"), + ] { + let (_, _, _, patch) = compared(a, b, true, true); + let mut document: Value = serde_json::from_str(a).unwrap(); + apply(&mut document, &patch); + assert_eq!( + document, + serde_json::from_str::(b).unwrap(), + "{patch}" + ); + } + } + + #[test] + fn the_rows_are_cut_past_their_cap_and_say_so() { + let rows = |items: usize| { + let list = vec!["1"; items].join(","); + let request = JsonDiffRequest { + a: format!("[{list}]"), + b: format!("[{list}]"), + format_a: None, + format_b: None, + ignore_key_order: true, + ignore_whitespace: true, + }; + match diff(&request) { + JsonDiffAnswer::Compared { + rows, + rows_truncated, + .. + } => (rows.len(), rows_truncated), + other => panic!("{other:?}"), + } + }; + + // The list's two brackets are rows too. + assert_eq!(rows(MAX_ROWS - 2), (MAX_ROWS, false)); + assert_eq!(rows(MAX_ROWS - 1), (MAX_ROWS, true)); + } } diff --git a/crates/engine/src/tools/files.rs b/crates/engine/src/tools/files.rs index ec66537c8..35faf64e4 100644 --- a/crates/engine/src/tools/files.rs +++ b/crates/engine/src/tools/files.rs @@ -82,11 +82,28 @@ mod tests { let folder = tempfile::tempdir().unwrap(); let path = folder.path().join("big.bin"); let file = File::create(&path).unwrap(); - file.set_len(MAX_SENT_BYTES + 1).unwrap(); + let read = |size: u64| { + file.set_len(size).unwrap(); + read_limited(&path.to_string_lossy()).map(|bytes| bytes.len() as u64) + }; + assert_eq!(read(MAX_SENT_BYTES), Ok(MAX_SENT_BYTES)); + assert_eq!(read(MAX_SENT_BYTES + 1), Err(FileProblem::TooLarge)); + } + + #[test] + fn a_folder_is_not_read_and_a_folder_that_is_not_there_not_written_to() { + let folder = tempfile::tempdir().unwrap(); + let inside = folder.path().join("absent").join("a"); + + assert_eq!( + read_limited(&folder.path().to_string_lossy()), + Err(FileProblem::Unreadable) + ); assert_eq!( - read_limited(&path.to_string_lossy()), - Err(FileProblem::TooLarge) + write(&inside.to_string_lossy(), b"a"), + Err(FileProblem::Unwritable) ); + assert_eq!(name_of("/"), "/"); } } diff --git a/crates/engine/src/tools/image.rs b/crates/engine/src/tools/image.rs index 2c9562365..659ac90e3 100644 --- a/crates/engine/src/tools/image.rs +++ b/crates/engine/src/tools/image.rs @@ -377,4 +377,40 @@ mod tests { ] ); } + + /// An attribute's name inside another's, or in a value, is not that attribute. + #[test] + fn an_svg_s_size_is_read_from_its_own_attributes() { + for (svg, sides) in [ + ( + r#""#, + (Some(24), Some(16)), + ), + ( + r#""#, + (Some(24), Some(16)), + ), + ( + r#""#, + (Some(24), Some(16)), + ), + ("", (None, None)), + ("", (None, None)), + (""), None); + } + + /// A container of something else: sound, not a picture. + #[test] + fn a_riff_that_is_no_webp_is_no_picture() { + assert_eq!(size(b"RIFF\0\0\0\0WAVEfmt "), None); + assert_eq!(size(b"XXXX\0\0\0\0WEBPVP8 "), None); + } } diff --git a/crates/engine/src/tools/numbers.rs b/crates/engine/src/tools/numbers.rs index f65d357e6..dcaafdb53 100644 --- a/crates/engine/src/tools/numbers.rs +++ b/crates/engine/src/tools/numbers.rs @@ -178,4 +178,31 @@ mod tests { ); assert_eq!(leading_number("750KiB"), Ok((Decimal::from(750), 3))); } + + /// A space or a mark groups digits only between two of them. + #[test] + fn what_stands_apart_from_the_digits_ends_the_number() { + for (text, end) in [ + ("1 000", 5), + ("1 000", 1), + ("1 x", 1), + ("1,x", 1), + ("1 000 ", 5), + ("1._2", 1), + ] { + assert_eq!(leading_number(text).map(|(_, end)| end), Ok(end), "{text}"); + } + } + + #[test] + fn an_exponent_without_digits_is_no_exponent() { + for (text, end) in [("1e", 1), ("1e+", 1), ("2ex", 1), ("1e0", 3)] { + let (value, stopped) = leading_number(text).unwrap(); + assert_eq!( + (value.to_string().as_str(), stopped), + (&text[..1], end), + "{text}" + ); + } + } } diff --git a/crates/engine/src/tools/qr.rs b/crates/engine/src/tools/qr.rs index 53d54e526..efb93fb84 100644 --- a/crates/engine/src/tools/qr.rs +++ b/crates/engine/src/tools/qr.rs @@ -816,4 +816,92 @@ mod tests { assert_eq!(rgba.len(), 290 * 290 * 4); assert!(rgba.chunks(4).all(|pixel| pixel[3] == u8::MAX)); } + + /// Byte for byte what a code holds, the version past nine counting its length on more bits. + #[test] + fn a_text_as_long_as_a_version_holds_is_that_version() { + for correction in [QrCorrection::Low, QrCorrection::High] { + for version in [1, 9, 10, 40] { + let room = byte_capacity(version, correction.level()); + let answer = describe(&request(text(&"a".repeat(room)), correction)); + let QrAnswer::Code { + version: drawn, + capacity, + bytes, + .. + } = answer + else { + panic!("{version}: {answer:?}"); + }; + assert_eq!( + (drawn, capacity), + (u32::from(version.unsigned_abs()), bytes) + ); + } + } + } + + #[test] + fn a_scheme_is_spelled_as_rfc_3986_spells_one() { + for (url, spelled) in [ + ("https://a", true), + ("git+ssh://a", true), + ("x-app:a", true), + ("h2:a", true), + ("2h:a", false), + ("ex.fr:80/a", false), + ("a/b", false), + ] { + assert_eq!(has_scheme(url), spelled, "{url}"); + } + } + + /// A text is not asked for a scheme. + #[test] + fn only_a_url_is_said_to_miss_its_scheme() { + for (content, missing) in [ + (url("exemple.fr"), true), + (url("https://exemple.fr"), false), + (text("exemple.fr"), false), + ] { + let QrAnswer::Code { missing_scheme, .. } = + describe(&request(content, QrCorrection::Medium)) + else { + panic!("no code"); + }; + assert_eq!(missing_scheme, missing); + } + } + + /// A line of exactly its room is not folded; a line goes on with its space counted. + #[test] + fn a_vcard_line_is_folded_past_its_room_and_no_sooner() { + let room = VCARD_LINE_OCTETS; + + assert_eq!(fold(&"a".repeat(room)), "a".repeat(room)); + let folded = fold(&"a".repeat(room * 2)); + let lines: Vec<&str> = folded.split("\r\n").collect(); + assert_eq!( + lines.iter().map(|line| line.len()).collect::>(), + [room, room, 2] + ); + assert!(lines[1..].iter().all(|line| line.starts_with(' '))); + } + + /// A viewer reads the PNG as it was drawn: eight bits of grey a pixel. + #[test] + fn the_png_says_how_its_pixels_are_written() { + let drawn = drawn(&request(text("a"), QrCorrection::Low)).unwrap(); + + let bytes = png(&drawn).unwrap(); + + let reader = png::Decoder::new(std::io::Cursor::new(bytes)) + .read_info() + .unwrap(); + let info = reader.info(); + assert_eq!( + (info.color_type, info.bit_depth), + (png::ColorType::Grayscale, png::BitDepth::Eight) + ); + } } diff --git a/crates/engine/src/tools/sizes.rs b/crates/engine/src/tools/sizes.rs index 3490a6e2a..005bc7fcf 100644 --- a/crates/engine/src/tools/sizes.rs +++ b/crates/engine/src/tools/sizes.rs @@ -446,4 +446,26 @@ mod tests { SizesAnswer::Converted { .. } )); } + + /// From kilo, which nothing is under. + #[test] + fn a_quantity_is_of_the_rank_its_bytes_reach() { + for (bytes, reached) in [(0, 0), (999_999, 0), (1_000_000, 1), (1_000_000_000, 2)] { + assert_eq!( + rank(SizeUnit::Bit, Decimal::from(bytes)), + reached, + "{bytes}" + ); + } + } + + /// Minus nothing is nothing. + #[test] + fn a_negative_zero_is_no_negative_quantity() { + assert!(read_quantity("-0", DECIMAL[0]).is_ok()); + assert_eq!( + read_quantity(" -1", DECIMAL[0]), + Err(QuantityProblem::Negative(2)) + ); + } } diff --git a/crates/engine/src/tools/stats.rs b/crates/engine/src/tools/stats.rs index 0664b691b..f111af2bf 100644 --- a/crates/engine/src/tools/stats.rs +++ b/crates/engine/src/tools/stats.rs @@ -302,4 +302,36 @@ mod tests { assert_eq!(many.frequencies.len(), MAX_FREQUENCIES); assert!(many.frequencies_truncated); } + + #[test] + fn the_frequencies_are_cut_past_their_cap_and_say_so() { + let distinct = |count: usize| { + let text: String = (0..count) + .filter_map(|at| char::from_u32(0x4e00 + u32::try_from(at).unwrap())) + .collect(); + let stats = count_of(&text); + ( + stats.frequencies.len(), + stats.frequencies_truncated, + stats.distinct as usize, + ) + }; + + assert_eq!( + distinct(MAX_FREQUENCIES), + (MAX_FREQUENCIES, false, MAX_FREQUENCIES) + ); + assert_eq!( + distinct(MAX_FREQUENCIES + 1), + (MAX_FREQUENCIES, true, MAX_FREQUENCIES + 1) + ); + } + + fn count_of(text: &str) -> TextStats { + count(&StatsRequest { + text: text.to_owned(), + count_whitespace: true, + fold_case: false, + }) + } } diff --git a/crates/engine/src/tools/text.rs b/crates/engine/src/tools/text.rs index cb3da96e3..d8f911eb2 100644 --- a/crates/engine/src/tools/text.rs +++ b/crates/engine/src/tools/text.rs @@ -957,4 +957,99 @@ strasse-nummer" assert_eq!(answer.text, ""); assert_eq!(answer.final_newline, FinalNewlineChange::Unchanged); } + + /// An apostrophe after a separator, or before one, binds nothing. + #[test] + fn an_apostrophe_binds_only_two_words_it_stands_between() { + for (text, read) in [ + ("l'été", "l'été"), + ("rock 'n roll", "rock n roll"), + ("the dogs' bowl", "the dogs bowl"), + ("a - 'b", "a b"), + ("a-'b", "a b"), + ("'quoted'", "quoted"), + ] { + assert_eq!(case(text, TextCase::Lower), read, "{text}"); + } + } + + /// An acronym ends before a capitalised word; a capital after a digit starts one. + #[test] + fn a_capital_starts_a_word_after_a_lower_case_a_digit_or_an_acronym() { + for (text, read) in [ + ("HTTPServer", "http_server"), + ("HTTP", "http"), + ("v2Beta", "v2_beta"), + ("fooBAR", "foo_bar"), + ("a1b2", "a1b2"), + ("foo Bar", "foo_bar"), + ("foo-BAr", "foo_b_ar"), + ] { + assert_eq!(case(text, TextCase::Snake), read, "{text}"); + } + } + + /// In an English title, `l` is no article; in a French one, the word it elides into takes its + /// capital, and the second half of `aujourd'hui` does not. + #[test] + fn a_title_capitalises_after_an_elision_in_french_alone() { + let title = |text: &str, language: TitleLanguage| { + let request = CaseRequest { + title_case_language: language, + ..request(text) + }; + case_of(&request, TextCase::Title) + }; + for (text, english, french) in [ + ("vers l'été", "Vers L'été", "Vers l'Été"), + ("don't stop", "Don't Stop", "Don't Stop"), + ("aujourd'hui", "Aujourd'hui", "Aujourd'hui"), + ("la fin", "La Fin", "La Fin"), + ( + "la fin de la nuit", + "La Fin De La Nuit", + "La Fin de la Nuit", + ), + ] { + assert_eq!(title(text, TitleLanguage::English), english, "{text}"); + assert_eq!(title(text, TitleLanguage::French), french, "{text}"); + } + } + + #[test] + fn a_text_starting_with_a_separator_has_no_space_before_its_first_word() { + assert_eq!(case("'a b", TextCase::Sentence), "A b"); + } + + /// The text's own habit; a line feed on a tie, or with none. + #[test] + fn a_newline_added_is_the_text_s_own() { + for (text, ending) in [ + ("a\r\nb\r\nc", "\r\n"), + ("a\rb\rc\nd", "\r"), + ("a\nb\r\nc", "\n"), + ("a\r\nb\rc", "\r\n"), + ("a\nb\rc", "\n"), + ("a", "\n"), + ] { + let answer = fix(text, None, false, FinalNewline::Add); + assert_eq!(answer.text, format!("{text}{ending}"), "{text:?}"); + assert_eq!(answer.final_newline, FinalNewlineChange::Added); + } + } + + #[test] + fn a_text_that_ends_with_a_newline_is_given_no_other() { + for text in ["a\n", "a\r\nb\r\n", "\n"] { + let answer = fix(text, None, false, FinalNewline::Add); + assert_eq!( + (answer.text.as_str(), answer.final_newline), + (text, FinalNewlineChange::Unchanged) + ); + } + assert_eq!( + fix("a", None, false, FinalNewline::Remove).final_newline, + FinalNewlineChange::Unchanged + ); + } } diff --git a/crates/engine/src/tools/text_diff.rs b/crates/engine/src/tools/text_diff.rs index 7094962b5..41cb4d23f 100644 --- a/crates/engine/src/tools/text_diff.rs +++ b/crates/engine/src/tools/text_diff.rs @@ -503,4 +503,130 @@ mod tests { assert!(diff(&ask(r#"{"a":1}"#, r#"{"a":2}"#, Granularity::Lines)).both_json); assert!(!diff(&ask(r#"{"a":1}"#, "a: 2", Granularity::Lines)).both_json); } + + fn side(line: Option<&TextDiffLine>) -> Option<(u32, Vec<(&str, bool)>)> { + line.map(|line| { + let pieces = line + .pieces + .iter() + .map(|piece| (piece.text.as_str(), piece.changed)); + (line.number, pieces.collect()) + }) + } + + fn sides(answer: &TextDiffAnswer) -> Vec<(Option, Option)> { + let number = |line: &Option| line.as_ref().map(|line| line.number); + answer + .rows + .iter() + .map(|row| (number(&row.left), number(&row.right))) + .collect() + } + + /// Each line numbered in its own text; a row with one side is a gap on the other. + #[test] + fn the_lines_left_over_on_one_side_are_removed_or_added() { + let shorter = diff(&ask("a\nx\ny\nz\nb", "a\nX\nb", Granularity::Lines)); + assert_eq!( + sides(&shorter), + [ + (Some(1), Some(1)), + (Some(2), Some(2)), + (Some(3), None), + (Some(4), None), + (Some(5), Some(3)) + ] + ); + let longer = diff(&ask("a\nx\nb", "a\nX\nY\nb", Granularity::Lines)); + assert_eq!( + sides(&longer), + [ + (Some(1), Some(1)), + (Some(2), Some(2)), + (None, Some(3)), + (Some(3), Some(4)) + ] + ); + assert_eq!((longer.added, longer.removed), (2, 1)); + } + + /// What changed is marked: a whole line added, removed or modified, none of a line kept. + #[test] + fn a_line_is_marked_when_it_changed() { + let answer = diff(&ask( + "same\nold\ngone\nend", + "same\nnew\nend\nmore", + Granularity::Lines, + )); + + let rows: Vec<_> = answer + .rows + .iter() + .map(|row| (side(row.left.as_ref()), side(row.right.as_ref()))) + .collect(); + assert_eq!( + rows[0], + ( + Some((1, vec![("same", false)])), + Some((1, vec![("same", false)])) + ) + ); + assert_eq!( + rows[1], + ( + Some((2, vec![("old", true)])), + Some((2, vec![("new", true)])) + ) + ); + assert_eq!(rows[2], (Some((3, vec![("gone", true)])), None)); + assert_eq!( + rows[3], + ( + Some((4, vec![("end", false)])), + Some((3, vec![("end", false)])) + ) + ); + assert_eq!(rows[4], (None, Some((4, vec![("more", true)])))); + } + + #[test] + fn a_line_modified_by_words_keeps_its_number_on_each_side() { + let answer = diff(&ask("a\nb one", "z\na\nb two", Granularity::Words)); + + let row = answer.rows.last().unwrap(); + assert_eq!( + side(row.left.as_ref()), + Some((2, vec![("b ", false), ("one", true)])) + ); + assert_eq!( + side(row.right.as_ref()), + Some((3, vec![("b ", false), ("two", true)])) + ); + } + + #[test] + fn as_many_rows_as_the_cap_are_all_there() { + let answer = diff(&ask(&"line\n".repeat(MAX_ROWS), "", Granularity::Lines)); + + assert!(!answer.rows_truncated); + assert_eq!(answer.rows.len(), MAX_ROWS); + } + + /// A blank side is JSON of nothing. + #[test] + fn both_sides_have_to_be_json_to_be_compared_as_values() { + for (a, b, both) in [ + ("{}", "[1]", true), + ("a", "{}", false), + ("{}", "a", false), + ("", "{}", false), + ("{}", " \n", false), + ] { + assert_eq!( + diff(&ask(a, b, Granularity::Lines)).both_json, + both, + "{a:?} {b:?}" + ); + } + } } From 01a57e8ca5048000778b1580f01d09f21a923aad Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 08:05:49 +0100 Subject: [PATCH 57/95] Notes: a page pasted keeps its words, cells and nested lists (#1791) * Notes: a page pasted keeps the words before its first tag Co-Authored-By: Claude Opus 5.5 * Notes: a page pasted keeps its words, cells and nested lists Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/richtext/src/html.rs | 159 +++++++++++++++++++++++++++++++++--- 1 file changed, 146 insertions(+), 13 deletions(-) diff --git a/crates/richtext/src/html.rs b/crates/richtext/src/html.rs index f1c46b1dc..cf9bef431 100644 --- a/crates/richtext/src/html.rs +++ b/crates/richtext/src/html.rs @@ -102,7 +102,11 @@ impl TokenSink for Sink { } fn pieces(html: &str) -> Vec { - let markup = html.find('<').map_or(html, |at| &html[at..]); + let markup = if html.starts_with("Version:") { + html.find('<').map_or("", |at| &html[at..]) + } else { + html + }; let tokenizer = Tokenizer::new(Sink::default(), TokenizerOpts::default()); let input = BufferQueue::default(); input.push_back(StrTendril::from_slice(markup)); @@ -179,12 +183,21 @@ impl Builder { items: Vec::new(), }); } - "li" => self.start(Open::Item(Vec::new())), + "li" => { + self.close_to(|open| matches!(open, Open::List { .. })); + self.start(Open::Item(Vec::new())); + } "blockquote" => self.start(Open::Quote(Vec::new())), "pre" => self.start(Open::Code(String::new())), "table" => self.start(Open::Table(Vec::new())), - "tr" => self.start(Open::Row(Vec::new())), - "td" | "th" => self.start(Open::Cell(Vec::new())), + "tr" => { + self.close_to(|open| matches!(open, Open::Table(_))); + self.start(Open::Row(Vec::new())); + } + "td" | "th" => { + self.close_to(|open| matches!(open, Open::Row(_))); + self.start(Open::Cell(Vec::new())); + } "br" => self.line_break(), _ => self.wear(name, href, style), } @@ -194,17 +207,18 @@ impl Builder { fn wear(&mut self, name: &str, href: Option, style: &str) { let before = self.marks.clone(); let style = style.to_ascii_lowercase().replace(' ', ""); + let weight = style + .split(';') + .find_map(|rule| rule.strip_prefix("font-weight:")) + .unwrap_or_default(); match name { - "b" | "strong" => self.marks.bold = true, + // A page copied whole can be wrapped in a `b` whose weight is normal. + "b" | "strong" => self.marks.bold |= weight != "normal", "i" | "em" => self.marks.italic = true, "s" | "del" | "strike" => self.marks.strike = true, "code" => self.marks.code = true, "a" => self.marks.link = href, "span" => { - let weight = style - .split(';') - .find_map(|rule| rule.strip_prefix("font-weight:")) - .unwrap_or_default(); if weight == "bold" || weight.parse::().is_ok_and(|weight| weight >= 600) { self.marks.bold = true; } @@ -239,6 +253,15 @@ impl Builder { self.open.push(open); } + /// What an end tag left out would have closed: up to the innermost `parent`, if there is one. + fn close_to(&mut self, parent: impl Fn(&Open) -> bool) { + if self.open.iter().any(&parent) { + while self.open.last().is_some_and(|open| !parent(open)) { + self.close(); + } + } + } + /// Closes what is open down to the block `name` opened. fn close_until(&mut self, name: &str) { let matches = |open: &Open| match open { @@ -289,6 +312,10 @@ impl Builder { checked: false, blocks, }); + } else { + for block in blocks { + self.block(block); + } } } Open::Code(text) => self.block(Block::CodeBlock { @@ -311,10 +338,20 @@ impl Builder { } fn block(&mut self, block: Block) { - if let Some(Open::Blocks(blocks) | Open::Quote(blocks) | Open::Item(blocks)) = - self.open.last_mut() - { - blocks.push(block); + match self.open.last_mut() { + Some(Open::Blocks(blocks) | Open::Quote(blocks) | Open::Item(blocks)) => { + blocks.push(block); + } + // A list right in a list is of its last item. + Some(Open::List { items, .. }) => match items.last_mut() { + Some(item) => item.blocks.push(block), + None => items.push(Item { + checked: false, + blocks: vec![block], + }), + }, + Some(Open::Cell(cell)) => add_text(&block, cell), + _ => {} } } @@ -396,6 +433,31 @@ impl Builder { } } +/// A cell holds text alone: that of the block, on a line of its own. +fn add_text(block: &Block, cell: &mut Cell) { + match block { + Block::Paragraph(content) | Block::Heading { content, .. } => { + if !cell.is_empty() { + cell.push(Inline::HardBreak); + } + cell.extend(content.iter().cloned()); + } + Block::CodeBlock { text, .. } => { + add_text(&Block::Paragraph(vec![Inline::text(text)]), cell); + } + Block::Quote(blocks) => blocks.iter().for_each(|each| add_text(each, cell)), + Block::List { items, .. } => items + .iter() + .flat_map(|item| &item.blocks) + .for_each(|each| add_text(each, cell)), + Block::Table(rows) => rows + .iter() + .flatten() + .for_each(|content| add_text(&Block::Paragraph(content.clone()), cell)), + Block::Image { .. } | Block::Rule => {} + } +} + /// A block's text without the spaces its markup left at its ends. fn trim(content: &mut Vec) { while matches!(content.last(), Some(Inline::HardBreak)) { @@ -439,6 +501,77 @@ mod tests { assert!(!formatted(" ")); } + /// Windows hands the fragment alone, which a browser may start with a word. + #[test] + fn the_words_before_the_first_tag_are_kept() { + assert_eq!(crate::write(&from_html("du gras")), "du **gras**"); + assert_eq!(crate::write(&from_html("du texte")), "du texte"); + assert_eq!(from_html("Version:0.9\r\n").blocks, []); + } + + #[test] + fn a_cell_keeps_the_text_of_the_blocks_in_it() { + for (cell, expected) in [ + ("

a

", "a"), + ("

a

b

", "a\nb"), + ("a

b

", "a\nb"), + ("
  • a
  • b
", "a\nb"), + ("

a

", "a"), + ("
a b
", "a b"), + ("
ab
", "a\nb"), + ] { + let document = from_html(&format!("
{cell}
")); + let [Block::Table(rows)] = document.blocks.as_slice() else { + panic!("a table: {document:?}"); + }; + assert_eq!(inlines::plain(&rows[0][0]), expected, "{cell}"); + assert_eq!((rows.len(), rows[0].len()), (1, 1), "{cell}"); + } + let bold = from_html("

a

"); + assert_eq!(crate::write(&bold), "| **a** |\n| ----- |"); + } + + #[test] + fn a_list_right_in_a_list_is_of_its_last_item() { + let markdown = |html: &str| crate::write(&from_html(html)); + + assert_eq!( + markdown("
  • a
    • b
"), + "- a\n - b" + ); + assert_eq!(markdown("
    • a
"), "- - a"); + assert_eq!(markdown("
  • a
  • "), "a"); + } + + #[test] + fn an_end_tag_left_out_is_read_where_html_puts_it() { + let markdown = |html: &str| crate::write(&from_html(html)); + + assert_eq!(markdown("
    • a
    • b
    c"), "- a\n- b\n\nc"); + assert_eq!( + markdown("
    • a
      • b
    • c
    "), + "- a\n - b\n- c" + ); + assert_eq!( + markdown("
    ab
    cd
    "), + "| a | b |\n| --- | --- |\n| c | d |" + ); + } + + #[test] + fn a_bold_tag_of_normal_weight_is_not_bold() { + let markdown = |html: &str| crate::write(&from_html(html)); + + assert_eq!( + markdown("a b"), + "a **b**" + ); + assert_eq!( + markdown("ab"), + "**ab**" + ); + } + #[test] fn a_windows_header_before_the_markup_is_dropped() { let html = "Version:0.9\r\nStartHTML:0000000105\r\ngras"; From 5f6084a2620bc4ccc8888f4ab64ec48309c1d96d Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 08:05:59 +0100 Subject: [PATCH 58/95] Notes: Shift+Tab, Delete and Backspace keep the caret in place (#1787) * Notes: Shift+Tab, Delete and Backspace keep the caret in place Co-Authored-By: Claude Opus 5.5 * Take the list's block once, and hold Shift+Tab in the editor Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/richtext/src/edit.rs | 66 ++++++++----------- crates/richtext/src/edit/tests.rs | 53 ++++++++++++++- crates/richtext/src/tree.rs | 5 ++ crates/ui/src/notes/overlays/editor/rich.rs | 16 ++--- .../src/notes/overlays/editor/rich/tests.rs | 12 ++++ 5 files changed, 101 insertions(+), 51 deletions(-) diff --git a/crates/richtext/src/edit.rs b/crates/richtext/src/edit.rs index b377a1892..63a8a3b12 100644 --- a/crates/richtext/src/edit.rs +++ b/crates/richtext/src/edit.rs @@ -492,7 +492,7 @@ pub fn split(document: &mut Document, selection: &Selection) -> Selection { && rest == [0] { if empty { - return lift_item(document, &list, item); + return lift_item(document, &selection); } let right = take_from(document, &path, offset); cut(document, &path, offset..usize::MAX); @@ -564,35 +564,34 @@ fn lift_from_quote(document: &mut Document, path: &[usize]) -> Selection { /// Shift+Tab, Backspace at its start, Enter in it empty: the item one level up. In a nested list it /// becomes an item of the list above, the ones after it nested under it; at the top it leaves the /// list, which is cut in two around it. -pub fn lift_item(document: &mut Document, list: &[usize], item: usize) -> Selection { - let Some((blocks, index)) = tree::siblings_mut(document, list) else { - return Selection::default(); +pub fn lift_item(document: &mut Document, selection: &Selection) -> Selection { + let Position { path, offset } = selection.head.clone(); + let Some((list, item, rest)) = tree::innermost_item(document, &path) else { + return selection.clone(); }; - let Block::List { kind, items } = &mut blocks[index] else { - return Selection::default(); + let Some(Block::List { kind, items }) = tree::block_mut(document, &list) else { + return selection.clone(); }; let kind = *kind; let after: Vec = items.drain(item + 1..).collect(); let mut lifted = items.remove(item); let emptied = items.is_empty(); - let parent = tree::innermost_item(document, list).filter(|(_, _, rest)| rest.len() == 1); + let parent = tree::innermost_item(document, &list).filter(|(_, _, rest)| rest.len() == 1); if let Some((outer, outer_item, _)) = parent { if !after.is_empty() { lifted.blocks.push(Block::List { kind, items: after }); } - let Some((blocks, index)) = tree::siblings_mut(document, &outer) else { - return Selection::default(); - }; - if let Block::List { items, .. } = &mut blocks[index] { + if let Some(Block::List { items, .. }) = tree::block_mut(document, &outer) { items.insert(outer_item + 1, lifted); } - if emptied && let Some((blocks, index)) = tree::siblings_mut(document, list) { + if emptied && let Some((blocks, index)) = tree::siblings_mut(document, &list) { blocks.remove(index); } - return caret([outer.as_slice(), &[outer_item + 1, 0]].concat(), 0); + let lifted = [outer.as_slice(), &[outer_item + 1], rest.as_slice()].concat(); + return caret(lifted, offset); } - let Some((blocks, index)) = tree::siblings_mut(document, list) else { - return Selection::default(); + let Some((blocks, index)) = tree::siblings_mut(document, &list) else { + return selection.clone(); }; let mut at = index + 1; let first = at; @@ -608,11 +607,12 @@ pub fn lift_item(document: &mut Document, list: &[usize], item: usize) -> Select blocks.remove(index); landed -= 1; } - let mut path = list.to_vec(); + let mut path = list; if let Some(last) = path.last_mut() { - *last = landed; + *last = landed + rest.first().copied().unwrap_or(0); } - caret(path, 0) + path.extend(rest.get(1..).unwrap_or_default()); + caret(path, offset) } /// Tab in an item: it goes under the item above, into its nested list of the same kind. @@ -668,10 +668,8 @@ pub fn delete_backward(document: &mut Document, selection: &Selection) -> Select cut(document, &path, offset - 1..offset); return caret(path, offset - 1); } - if let Some((list, item, rest)) = tree::innermost_item(document, &path) - && rest == [0] - { - return lift_item(document, &list, item); + if tree::innermost_item(document, &path).is_some_and(|(_, _, rest)| rest == [0]) { + return lift_item(document, selection); } if let Some(Block::Heading { content, .. }) = tree::block(document, &path) { let content = content.clone(); @@ -696,20 +694,14 @@ fn join_backward(document: &mut Document, path: &[usize]) -> Selection { return caret(path.to_vec(), 0); }; if !leaf { + // The leaf's path moves; its rank among the leaves does not. + let rank = tree::leaves(document).iter().position(|each| each == path); if let Some((blocks, index)) = tree::siblings_mut(document, &before) { blocks.remove(index); } prune(&mut document.blocks); - let moved = if same_parent(&before, path) { - let mut moved = path.to_vec(); - if let Some(last) = moved.last_mut() { - *last -= 1; - } - moved - } else { - path.to_vec() - }; - return caret(moved, 0); + let moved = rank.and_then(|rank| tree::leaves(document).into_iter().nth(rank)); + return caret(moved.unwrap_or_else(|| path.to_vec()), 0); } if is_cell(document, &before) || matches!(tree::leaf(document, &before), Some(Leaf::Code(_))) { return caret(path.to_vec(), 0); @@ -724,11 +716,8 @@ fn join_backward(document: &mut Document, path: &[usize]) -> Selection { caret(before, length) } -fn same_parent(a: &[usize], b: &[usize]) -> bool { - a.len() == b.len() && a[..a.len() - 1] == b[..b.len() - 1] -} - -/// Delete: the `char` after the caret, or at a block's end, the next block joined onto it. +/// Delete: the `char` after the caret, or at a block's end, the next block joined onto it and the +/// caret left where it is. pub fn delete_forward(document: &mut Document, selection: &Selection) -> Selection { if !selection.is_empty() { return delete_selection(document, selection); @@ -747,7 +736,8 @@ pub fn delete_forward(document: &mut Document, selection: &Selection) -> Selecti match next { Some(next) if !is_cell(document, next) && !is_cell(document, &path) => { let next = next.clone(); - join_backward(document, &next) + join_backward(document, &next); + selection.clone() } _ => selection.clone(), } diff --git a/crates/richtext/src/edit/tests.rs b/crates/richtext/src/edit/tests.rs index 68ed6c71d..d3c60217a 100644 --- a/crates/richtext/src/edit/tests.rs +++ b/crates/richtext/src/edit/tests.rs @@ -72,9 +72,9 @@ fn tab_nests_an_item_under_the_one_above_and_shift_tab_takes_it_back() { let after = sink_item(&mut document, &caret_at(&[0, 1, 0], 1)); assert_eq!(write(&document), "- un\n - deux\n- trois"); assert_eq!(after, caret_at(&[0, 0, 1, 0, 0], 1)); - let after = lift_item(&mut document, &[0, 0, 1], 0); + let after = lift_item(&mut document, &after); assert_eq!(write(&document), "- un\n- deux\n- trois"); - assert_eq!(after, caret_at(&[0, 1, 0], 0)); + assert_eq!(after, caret_at(&[0, 1, 0], 1)); } #[test] @@ -151,7 +151,7 @@ fn a_heading_at_its_start_becomes_a_paragraph_and_a_break_is_typed() { #[test] fn a_nested_item_lifted_takes_the_ones_after_it_along() { let mut document = read("- un\n - a\n - b\n- deux"); - let after = lift_item(&mut document, &[0, 0, 1], 0); + let after = lift_item(&mut document, &caret_at(&[0, 0, 1, 0, 0], 0)); assert_eq!(write(&document), "- un\n- a\n - b\n- deux"); assert_eq!(after, caret_at(&[0, 1, 0], 0)); } @@ -295,3 +295,50 @@ fn copied_as_markdown_reads_back_to_the_same_blocks() { "2. second\n3. third" ); } + +/// Shift+Tab from the middle of a line: the caret is still there. +#[test] +fn a_lifted_item_keeps_the_caret_where_it_was_in_it() { + for (markdown, path, landed) in [ + ("- un\n- deux", vec![0, 1, 0], vec![1]), + ("- un\n\n deux\n- trois", vec![0, 0, 1], vec![1]), + ( + "- un\n - deux\n\n trois", + vec![0, 0, 1, 0, 1], + vec![0, 1, 1], + ), + ("- un\n > deux", vec![0, 0, 1, 0], vec![1, 0]), + ] { + let mut document = read(markdown); + let after = lift_item(&mut document, &caret_at(&path, 3)); + assert_eq!(after, caret_at(&landed, 3), "{markdown}"); + assert!(tree::leaf(&document, &landed).is_some(), "{markdown}"); + } + let mut document = read("un"); + let before = caret_at(&[0], 1); + assert_eq!(lift_item(&mut document, &before), before); +} + +#[test] +fn an_image_taken_out_with_its_quote_leaves_the_caret_at_its_line() { + let mut document = read("un\n\n> ![x](y)\n\ndeux"); + let after = delete_backward(&mut document, &caret_at(&[2], 0)); + assert_eq!(write(&document), "un\n\ndeux"); + assert_eq!(after, caret_at(&[1], 0)); +} + +#[test] +fn delete_leaves_the_caret_where_it_is() { + for (markdown, left) in [ + ("un\n\n---\n\ndeux", "un\n\ndeux"), + ("un\n\ndeux", "undeux"), + ] { + let mut document = read(markdown); + let after = delete_forward(&mut document, &caret_at(&[0], 2)); + assert_eq!(write(&document), left); + assert_eq!(after, caret_at(&[0], 2)); + } + let mut document = read("```\nun\n```\n\ndeux"); + let end = caret_at(&[0], 2); + assert_eq!(delete_forward(&mut document, &end), end); +} diff --git a/crates/richtext/src/tree.rs b/crates/richtext/src/tree.rs index e3399beab..20ee3a90c 100644 --- a/crates/richtext/src/tree.rs +++ b/crates/richtext/src/tree.rs @@ -128,6 +128,11 @@ fn container_mut<'a>(blocks: &'a mut Vec, path: &[usize]) -> Option<&'a m } } +pub fn block_mut<'a>(document: &'a mut Document, path: &[usize]) -> Option<&'a mut Block> { + let (blocks, index) = siblings_mut(document, path)?; + blocks.get_mut(index) +} + pub fn block<'a>(document: &'a Document, path: &[usize]) -> Option<&'a Block> { let (last, parent) = path.split_last()?; container(&document.blocks, parent)?.get(*last) diff --git a/crates/ui/src/notes/overlays/editor/rich.rs b/crates/ui/src/notes/overlays/editor/rich.rs index 58db0f0be..01bdcbf45 100644 --- a/crates/ui/src/notes/overlays/editor/rich.rs +++ b/crates/ui/src/notes/overlays/editor/rich.rs @@ -846,16 +846,12 @@ fn tab(view: &mut RichEditor, back: bool) { } return; } - let item = tree::innermost_item(&view.document, &path); - match (item, back) { - (Some(_), false) => view.change(Step::Other, edit::sink_item), - (Some((list, item, _)), true) => { - view.change(Step::Other, |document, _| { - edit::lift_item(document, &list, item) - }); - } - (None, false) => view.type_text("\t"), - (None, true) => untab(view), + let in_item = tree::innermost_item(&view.document, &path).is_some(); + match (in_item, back) { + (true, false) => view.change(Step::Other, edit::sink_item), + (true, true) => view.change(Step::Other, edit::lift_item), + (false, false) => view.type_text("\t"), + (false, true) => untab(view), } } diff --git a/crates/ui/src/notes/overlays/editor/rich/tests.rs b/crates/ui/src/notes/overlays/editor/rich/tests.rs index 4e50f2de1..f8e8c8c3d 100644 --- a/crates/ui/src/notes/overlays/editor/rich/tests.rs +++ b/crates/ui/src/notes/overlays/editor/rich/tests.rs @@ -853,3 +853,15 @@ fn select_all_lights_every_row_of_a_wrapped_item() { assert!(covered, "row {row:?} is lit"); } } + +/// The caret where it was in the line, for what is typed next. +#[test] +fn shift_tab_takes_a_nested_item_back_from_the_middle_of_its_line() { + let (mut harness, id) = note("- one\n - two"); + at_end(&mut harness); + press(&mut harness, Modifiers::NONE, Key::ArrowLeft); + press(&mut harness, Modifiers::SHIFT, Key::Tab); + type_in(&mut harness, "-"); + click_id(&mut harness, "editor-close"); + assert_eq!(stored(&harness, &id), "- one\n- tw-o"); +} From 7305693be73b3b331ff62f8bd87305d58d5c6af4 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 08:11:11 +0100 Subject: [PATCH 59/95] Code editor: unit tests rewritten for the buffer and the search (#1795) Co-authored-by: Claude Opus 5.5 --- crates/text/src/buffer/tests.rs | 639 +++++++++++++++++++++++++++----- crates/text/src/diff.rs | 15 + crates/text/src/highlight.rs | 84 +++++ crates/text/src/indent.rs | 14 + crates/text/src/search.rs | 134 ++++--- crates/text/src/shield.rs | 32 ++ crates/text/src/words.rs | 21 ++ 7 files changed, 796 insertions(+), 143 deletions(-) diff --git a/crates/text/src/buffer/tests.rs b/crates/text/src/buffer/tests.rs index 83a4520f0..7c55cba5e 100644 --- a/crates/text/src/buffer/tests.rs +++ b/crates/text/src/buffer/tests.rs @@ -12,6 +12,26 @@ fn at(text: &str, caret: usize) -> Buffer { buffer } +fn over(text: &str, anchor: usize, head: usize) -> Buffer { + let mut buffer = Buffer::new(text); + buffer.select(Selection { anchor, head }); + buffer +} + +fn query(search: &str, replace: &str) -> Query { + Query { + search: search.into(), + replace: replace.into(), + ..Query::default() + } +} + +fn selected(buffer: &Buffer) -> (usize, usize) { + (buffer.selection().anchor, buffer.selection().head) +} + +// ── Undo ── + #[test] fn a_word_typed_is_undone_in_one_step_and_the_next_word_in_another() { let mut buffer = Buffer::new(""); @@ -21,91 +41,379 @@ fn a_word_typed_is_undone_in_one_step_and_the_next_word_in_another() { assert_eq!(buffer.text(), "SELECT"); buffer.undo(); assert_eq!(buffer.text(), ""); +} + +#[test] +fn what_was_undone_is_redone_with_its_selection() { + let mut buffer = Buffer::new(""); + typed(&mut buffer, "SELECT 1"); + buffer.undo(); + buffer.undo(); + buffer.redo(); - assert_eq!(buffer.text(), "SELECT"); - assert_eq!(buffer.selection(), Selection::caret(6)); + assert_eq!( + (buffer.text().as_str(), selected(&buffer)), + ("SELECT", (6, 6)) + ); + buffer.redo(); + assert_eq!( + (buffer.text().as_str(), selected(&buffer)), + ("SELECT 1", (8, 8)) + ); + assert!(buffer.redo().is_none()); +} + +#[test] +fn spaces_typed_in_a_row_are_one_step_with_the_word_they_start() { + let mut buffer = Buffer::new(""); + typed(&mut buffer, "a b"); + + buffer.undo(); + + assert_eq!(buffer.text(), "a"); +} + +#[test] +fn a_line_typed_starts_a_step_of_its_own() { + let mut buffer = Buffer::new(""); + typed(&mut buffer, "ab\ncd"); + + buffer.undo(); + + assert_eq!(buffer.text(), "ab"); } #[test] fn typing_after_the_caret_moved_starts_a_step_of_its_own() { let mut buffer = Buffer::new(""); typed(&mut buffer, "ab"); - buffer.move_to(0, false); + buffer.move_to(2, false); typed(&mut buffer, "x"); buffer.undo(); assert_eq!(buffer.text(), "ab"); } +#[test] +fn typing_after_an_undo_starts_a_step_of_its_own() { + let mut buffer = Buffer::new(""); + typed(&mut buffer, "a b"); + buffer.undo(); + typed(&mut buffer, "c"); + + buffer.undo(); + assert_eq!(buffer.text(), "a"); +} + #[test] fn a_new_edit_drops_what_could_be_redone() { let mut buffer = Buffer::new(""); typed(&mut buffer, "a"); buffer.undo(); typed(&mut buffer, "b"); + assert!(buffer.redo().is_none()); assert_eq!(buffer.text(), "b"); } #[test] -fn backspace_takes_a_whole_grapheme_and_a_crlf_at_once() { - let mut buffer = at("cafe\u{301}", 5); - buffer.delete(Direction::Backward, Unit::Grapheme); - assert_eq!(buffer.text(), "caf"); +fn letters_erased_one_after_the_other_are_one_step_either_way() { + for (caret, direction) in [(5, Direction::Backward), (0, Direction::Forward)] { + let mut buffer = at("hello", caret); + for _ in 0..3 { + buffer.delete(direction, Unit::Grapheme); + } + assert_eq!(buffer.len(), 2); + + buffer.undo(); + assert_eq!( + (buffer.text().as_str(), selected(&buffer)), + ("hello", (caret, caret)) + ); + } +} - let mut buffer = at("a\r\nb", 3); +#[test] +fn letters_typed_then_erased_are_two_steps() { + let mut buffer = Buffer::new(""); + typed(&mut buffer, "ab"); buffer.delete(Direction::Backward, Unit::Grapheme); + + buffer.undo(); assert_eq!(buffer.text(), "ab"); } #[test] -fn erasing_letter_by_letter_is_undone_in_one_step() { - let mut buffer = at("hello", 5); - for _ in 0..3 { - buffer.delete(Direction::Backward, Unit::Grapheme); +fn a_paste_is_a_step_of_its_own() { + let mut buffer = Buffer::new(""); + typed(&mut buffer, "a"); + buffer.insert("pasted"); + typed(&mut buffer, "b"); + + buffer.undo(); + assert_eq!(buffer.text(), "apasted"); + buffer.undo(); + assert_eq!(buffer.text(), "a"); +} + +#[test] +fn only_so_many_steps_are_kept_the_oldest_going_first() { + let mut buffer = Buffer::new(""); + for _ in 0..502 { + buffer.insert("ab"); } - assert_eq!(buffer.text(), "he"); + + let undone = std::iter::from_fn(|| buffer.undo()).count(); + + assert_eq!((undone, buffer.text().as_str()), (500, "abab")); +} + +#[test] +fn nothing_to_undo_is_no_edit() { + assert!(Buffer::new("a").undo().is_none()); +} + +// ── The selection ── + +#[test] +fn a_selection_stays_within_the_text() { + assert_eq!(selected(&over("abc", 9, 1)), (3, 1)); + assert_eq!(over("abc", 9, 1).selected_text(), "bc"); +} + +#[test] +fn the_caret_moved_keeps_its_anchor_only_when_it_extends() { + let mut buffer = over("abcdef", 1, 2); + + buffer.move_to(4, true); + assert_eq!(selected(&buffer), (1, 4)); + buffer.move_to(5, false); + assert_eq!(selected(&buffer), (5, 5)); + buffer.select_all(); + assert_eq!(selected(&buffer), (0, 6)); +} + +#[test] +fn what_is_typed_takes_the_place_of_the_selection() { + let mut buffer = over("abcd", 3, 1); + + buffer.insert("é!"); + + assert_eq!( + (buffer.text().as_str(), selected(&buffer)), + ("aé!d", (3, 3)) + ); buffer.undo(); - assert_eq!(buffer.text(), "hello"); + assert_eq!( + (buffer.text().as_str(), selected(&buffer)), + ("abcd", (3, 1)) + ); } +// ── Lines ── + #[test] -fn a_word_goes_with_the_spaces_before_it() { - let mut buffer = at("let user_id = 1", 11); - buffer.delete(Direction::Backward, Unit::Word); - assert_eq!(buffer.text(), "let = 1"); +fn lines_are_counted_as_an_editor_does() { + let buffer = Buffer::new("a\r\nbé\n"); - let mut buffer = at("a.b(c)", 0); - assert_eq!(buffer.step(0, Direction::Forward, Unit::Word), 1); - assert_eq!(buffer.step(1, Direction::Forward, Unit::Word), 2); - buffer.move_to(6, false); - assert_eq!(buffer.step(6, Direction::Backward, Unit::Word), 5); + assert_eq!(buffer.line_count(), 3); + assert_eq!( + [buffer.line(0), buffer.line(1), buffer.line(2)], + ["a", "bé", ""] + ); + assert_eq!([0, 1, 2].map(|line| buffer.line_start(line)), [0, 3, 6]); + assert_eq!([0, 1, 2].map(|line| buffer.line_end(line)), [1, 5, 6]); + assert_eq!( + [0, 3, 5, 6, 99].map(|at| buffer.line_of(at)), + [0, 1, 1, 2, 2] + ); + assert!(Buffer::new("").is_empty() && !buffer.is_empty()); } #[test] -fn a_line_deleted_takes_its_line_ending() { - let mut buffer = at("a\nb\nc", 2); - buffer.delete(Direction::Forward, Unit::Line); - assert_eq!(buffer.text(), "a\nc"); +fn an_edit_its_undo_and_its_redo_say_the_first_line_they_touched() { + let mut buffer = at("a\nb\nc", 4); + + assert_eq!(buffer.insert("!").first_line, 2); + assert_eq!(buffer.undo().unwrap().first_line, 2); + assert_eq!(buffer.redo().unwrap().first_line, 2); + assert_eq!( + buffer.replace_all(&query("b", "x")).1.unwrap().first_line, + 1 + ); + assert_eq!(buffer.undo().unwrap().first_line, 1); +} + +// ── Moving by a unit ── + +/// `é` as `e` and a combining accent, a family of joined emoji, `\r\n`: one each. +#[test] +fn a_step_by_grapheme_never_stops_inside_one() { + for (text, bounds) in [ + ("ab", vec![0, 1, 2]), + ("e\u{301}x", vec![0, 2, 3]), + ("👩‍👩‍👧!", vec![0, 5, 6]), + ("a\r\nb", vec![0, 1, 3, 4]), + ("\n\n", vec![0, 1, 2]), + ] { + let buffer = Buffer::new(text); + for pair in bounds.windows(2) { + assert_eq!( + buffer.step(pair[0], Direction::Forward, Unit::Grapheme), + pair[1], + "{text:?}" + ); + assert_eq!( + buffer.step(pair[1], Direction::Backward, Unit::Grapheme), + pair[0], + "{text:?}" + ); + } + let end = *bounds.last().unwrap(); + assert_eq!(buffer.step(end, Direction::Forward, Unit::Grapheme), end); + assert_eq!(buffer.step(0, Direction::Backward, Unit::Grapheme), 0); + } +} + +/// Over the spaces, then over one run of word characters or of punctuation. +#[test] +fn a_step_by_word_goes_over_one_run() { + let text = "let user_id=(1)"; + let forward = [(0, 3), (3, 12), (12, 14), (14, 15), (15, 16), (16, 16)]; + let backward = [(16, 15), (15, 14), (14, 12), (12, 5), (5, 0), (0, 0)]; + let buffer = Buffer::new(text); + + for (from, to) in forward { + assert_eq!( + buffer.step(from, Direction::Forward, Unit::Word), + to, + "from {from}" + ); + } + for (from, to) in backward { + assert_eq!( + buffer.step(from, Direction::Backward, Unit::Word), + to, + "from {from}" + ); + } +} + +#[test] +fn a_step_by_word_goes_past_a_line_ending_whole() { + for ending in ["\n", "\r\n"] { + let text = format!("ab {ending} cd"); + let buffer = Buffer::new(&text); + let after = 4 + ending.len(); + + assert_eq!(buffer.step(2, Direction::Forward, Unit::Word), 4); + assert_eq!(buffer.step(4, Direction::Forward, Unit::Word), after); + assert_eq!( + buffer.step(after + 2, Direction::Backward, Unit::Word), + after + ); + assert_eq!(buffer.step(after, Direction::Backward, Unit::Word), 4); + } +} + +#[test] +fn a_step_by_line_goes_to_its_ends() { + let buffer = Buffer::new("a\nbcd\r\ne"); + + assert_eq!(buffer.step(3, Direction::Backward, Unit::Line), 2); + assert_eq!(buffer.step(3, Direction::Forward, Unit::Line), 5); +} + +// ── Deleting ── + +#[test] +fn a_deletion_takes_a_grapheme_a_word_or_a_line() { + for (text, caret, direction, unit, left) in [ + ("cafe\u{301}", 5, Direction::Backward, Unit::Grapheme, "caf"), + ("a\r\nb", 3, Direction::Backward, Unit::Grapheme, "ab"), + ("a\r\nb", 1, Direction::Forward, Unit::Grapheme, "ab"), + ( + "let user_id = 1", + 11, + Direction::Backward, + Unit::Word, + "let = 1", + ), + ("let x", 3, Direction::Forward, Unit::Word, "let"), + ("a\nb\nc", 2, Direction::Forward, Unit::Line, "a\nc"), + ("a\nb\nc", 2, Direction::Backward, Unit::Line, "a\nc"), + ("a\nb", 3, Direction::Forward, Unit::Line, "a\n"), + ] { + let mut buffer = at(text, caret); + assert!(buffer.delete(direction, unit).is_some()); + assert_eq!(buffer.text(), left, "{text:?}"); + } +} + +#[test] +fn a_selection_is_deleted_whole_whatever_the_unit() { + for unit in [Unit::Grapheme, Unit::Word, Unit::Line] { + let mut buffer = over("abcd", 3, 1); + buffer.delete(Direction::Forward, unit); + assert_eq!((buffer.text().as_str(), selected(&buffer)), ("ad", (1, 1))); + } } #[test] fn nothing_to_delete_is_no_edit() { - let mut buffer = at("a", 0); - assert!(buffer.delete(Direction::Backward, Unit::Grapheme).is_none()); - assert!(buffer.undo().is_none()); + assert!( + at("a", 0) + .delete(Direction::Backward, Unit::Grapheme) + .is_none() + ); + assert!(at("a", 1).delete(Direction::Forward, Unit::Word).is_none()); + assert!(at("", 0).delete(Direction::Forward, Unit::Line).is_none()); } +// ── Moving lines, commenting, indenting ── + #[test] fn lines_move_up_and_down_with_the_caret() { - let mut buffer = at("a\nb\nc", 2); - buffer.move_lines(Direction::Backward); - assert_eq!(buffer.text(), "b\na\nc"); - assert_eq!(buffer.selection(), Selection::caret(0)); + let mut buffer = at("a\nbcd\nc", 3); + + assert_eq!( + buffer.move_lines(Direction::Backward).unwrap().first_line, + 0 + ); + assert_eq!( + (buffer.text().as_str(), selected(&buffer)), + ("bcd\na\nc", (1, 1)) + ); + buffer.move_lines(Direction::Forward); buffer.move_lines(Direction::Forward); + assert_eq!( + (buffer.text().as_str(), selected(&buffer)), + ("a\nc\nbcd", (5, 5)) + ); +} + +#[test] +fn the_first_line_does_not_move_up_nor_the_last_down() { + assert!(at("a\nb", 0).move_lines(Direction::Backward).is_none()); + assert!(at("a\nb", 3).move_lines(Direction::Forward).is_none()); +} + +/// A selection ending at the start of a line leaves that line where it is. +#[test] +fn every_line_a_selection_touches_moves() { + let mut buffer = over("a\nb\nc\nd", 2, 6); + buffer.move_lines(Direction::Forward); - assert_eq!(buffer.text(), "a\nc\nb"); - assert!(buffer.move_lines(Direction::Forward).is_none()); + assert_eq!( + (buffer.text().as_str(), selected(&buffer)), + ("a\nd\nb\nc", (4, 8)) + ); + buffer.move_lines(Direction::Backward); + buffer.move_lines(Direction::Backward); + assert_eq!( + (buffer.text().as_str(), selected(&buffer)), + ("b\nc\na\nd", (0, 4)) + ); } /// Joined with `\n` alone, they left the text with both endings and the caret one character off. @@ -114,93 +422,234 @@ fn lines_moved_in_a_crlf_text_keep_their_endings() { let mut buffer = at("a\r\nbc\r\nd", 4); buffer.move_lines(Direction::Backward); - assert_eq!(buffer.text(), "bc\r\na\r\nd"); - assert_eq!(buffer.selection(), Selection::caret(1)); + assert_eq!( + (buffer.text().as_str(), selected(&buffer)), + ("bc\r\na\r\nd", (1, 1)) + ); buffer.move_lines(Direction::Forward); buffer.move_lines(Direction::Forward); - assert_eq!(buffer.text(), "a\r\nd\r\nbc"); - assert_eq!(buffer.selection(), Selection::caret(7)); + assert_eq!( + (buffer.text().as_str(), selected(&buffer)), + ("a\r\nd\r\nbc", (7, 7)) + ); +} + +fn commented(text: &str, anchor: usize, head: usize) -> (String, (usize, usize)) { + let mut buffer = over(text, anchor, head); + buffer.toggle_comment("//"); + (buffer.text(), selected(&buffer)) } #[test] -fn a_step_by_word_goes_past_a_line_ending_whole() { - for ending in ["\n", "\r\n"] { - let text = format!("ab {ending}cd"); - let buffer = Buffer::new(&text); - let after = 4 + ending.len(); +fn a_comment_goes_before_every_line_selected_and_not_before_a_blank_one() { + assert_eq!( + commented("a\n b\n\n \nc", 0, 10), + ("// a\n // b\n\n \n// c".to_string(), (0, 19)) + ); +} - assert_eq!(buffer.step(2, Direction::Forward, Unit::Word), 4); - assert_eq!(buffer.step(4, Direction::Forward, Unit::Word), after); - assert_eq!(buffer.step(after, Direction::Backward, Unit::Word), 4); - } +#[test] +fn a_comment_comes_off_only_when_every_line_has_it() { + assert_eq!(commented("// a\n //b\n\n// c", 0, 16).0, "a\n b\n\nc"); + assert_eq!(commented("// a\nb", 0, 6).0, "// // a\n// b"); } #[test] -fn a_comment_goes_on_every_line_then_comes_off() { - let mut buffer = Buffer::new("a\n b\n\nc"); - buffer.select_all(); - buffer.toggle_comment("//"); - assert_eq!(buffer.text(), "// a\n // b\n\n// c"); - buffer.select_all(); - buffer.toggle_comment("//"); - assert_eq!(buffer.text(), "a\n b\n\nc"); +fn a_comment_at_a_caret_takes_its_line_and_keeps_its_column() { + assert_eq!( + commented("a\nbc\nd", 3, 3), + ("a\n// bc\nd".to_string(), (3, 3)) + ); + assert_eq!( + commented("a\n// bc\nd", 7, 7), + ("a\nbc\nd".to_string(), (4, 4)) + ); + assert_eq!(commented("// a", 4, 4), ("a".to_string(), (1, 1))); +} + +#[test] +fn a_comment_leaves_the_line_a_selection_ends_at_the_start_of() { + assert_eq!( + commented("a\nb\nc", 0, 2), + ("// a\nb\nc".to_string(), (0, 4)) + ); } #[test] fn tab_and_shift_tab_are_one_step_each() { let mut buffer = Buffer::new("a\nb"); buffer.select_all(); + buffer.indent(" "); assert_eq!(buffer.text(), " a\n b"); - buffer.outdent(" "); + assert!(buffer.outdent(" ").is_some()); assert_eq!(buffer.text(), "a\nb"); + assert!(buffer.outdent(" ").is_none()); buffer.undo(); assert_eq!(buffer.text(), " a\n b"); } +// ── Searching and replacing ── + #[test] -fn search_counts_seeks_and_wraps() { - let query = Query { - search: "id".into(), - ..Query::default() - }; - let mut buffer = at("id x id x id", 4); - assert!(buffer.seek(&query, 4, Direction::Forward)); - assert_eq!(buffer.selection().range(), 5..7); - let count = buffer.count(&query); - assert_eq!((count.total, count.current), (3, Some(2))); - buffer.seek(&query, 11, Direction::Forward); - assert_eq!(buffer.selection().range(), 0..2, "wraps round to the start"); - buffer.seek(&query, 0, Direction::Backward); - assert_eq!(buffer.selection().range(), 10..12); -} - -#[test] -fn replace_one_selects_first_then_replaces_and_replace_all_is_one_step() { - let query = Query { - search: "a".into(), - replace: "xyz".into(), - ..Query::default() - }; +fn a_search_is_counted_with_the_match_the_selection_is_on() { + let mut buffer = over("id x id x id", 5, 7); + + let on = buffer.count(&query("id", "")); + assert_eq!((on.total, on.current, on.capped), (3, Some(2), false)); + buffer.move_to(6, false); + assert_eq!(buffer.count(&query("id", "")).current, None); +} + +#[test] +fn a_count_stops_at_its_cap() { + let matches = |count: usize| Buffer::new(&"a ".repeat(count)).count(&query("a", "")); + + assert!(!matches(search::COUNT_CAP - 1).capped); + let capped = matches(search::COUNT_CAP + 5); + assert_eq!((capped.total, capped.capped), (search::COUNT_CAP, true)); +} + +#[test] +fn a_seek_selects_the_next_match_that_way_and_wraps_round() { + use Direction::{Backward, Forward}; + let mut buffer = Buffer::new("id x id x id"); + for (from, direction, found) in [ + (4, Forward, 5..7), + (5, Forward, 5..7), + (11, Forward, 0..2), + (7, Backward, 5..7), + (6, Backward, 0..2), + (0, Backward, 10..12), + ] { + assert!(buffer.seek(&query("id", ""), from, direction)); + assert_eq!(buffer.selection().range(), found, "from {from}"); + } +} + +#[test] +fn a_seek_that_finds_nothing_leaves_the_selection() { + let mut buffer = over("abc", 1, 2); + + assert!(!buffer.seek(&query("z", ""), 0, Direction::Forward)); + assert_eq!(selected(&buffer), (1, 2)); +} + +#[test] +fn replacing_one_selects_a_match_first_then_replaces_it_and_selects_the_next() { let mut buffer = at("a b a", 0); - assert!(buffer.replace_one(&query).is_none()); - assert_eq!(buffer.selection().range(), 0..1); - buffer.replace_one(&query); - assert_eq!(buffer.text(), "xyz b a"); - assert_eq!(buffer.selection().range(), 6..7); - let mut buffer = Buffer::new("a b a"); - let (count, _) = buffer.replace_all(&query); - assert_eq!((count, buffer.text().as_str()), (2, "xyz b xyz")); + assert!(buffer.replace_one(&query("a", "xyz")).is_none()); + assert_eq!( + (buffer.text().as_str(), selected(&buffer)), + ("a b a", (0, 1)) + ); + assert!(buffer.replace_one(&query("a", "xyz")).is_some()); + assert_eq!( + (buffer.text().as_str(), selected(&buffer)), + ("xyz b a", (6, 7)) + ); +} + +/// The replacement holds what is searched: it is not replaced again. +#[test] +fn replacing_one_goes_past_what_it_wrote() { + let mut buffer = over("a a", 0, 1); + + buffer.replace_one(&query("a", "aa")); + + assert_eq!( + (buffer.text().as_str(), selected(&buffer)), + ("aa a", (3, 4)) + ); +} + +#[test] +fn replacing_all_is_one_step_of_undo() { + let mut buffer = at("é a b a", 7); + + let (count, _) = buffer.replace_all(&query("a", "xyz")); + assert_eq!((count, buffer.text().as_str()), (2, "é xyz b xyz")); + assert_eq!(selected(&buffer), (7, 7)); buffer.undo(); - assert_eq!(buffer.text(), "a b a"); + assert_eq!( + (buffer.text().as_str(), selected(&buffer)), + ("é a b a", (7, 7)) + ); + buffer.redo(); + assert_eq!(buffer.text(), "é xyz b xyz"); } #[test] -fn an_edit_says_the_line_it_starts_on() { - let mut buffer = at("a\nb\nc", 4); - assert_eq!(buffer.insert("!").first_line, 2); - assert_eq!(buffer.line_count(), 3); - assert_eq!(buffer.line(2), "!c"); +fn replacing_all_keeps_the_caret_within_what_is_left() { + let mut buffer = at("aaaa", 4); + + buffer.replace_all(&query("a", "")); + + assert_eq!((buffer.text().as_str(), selected(&buffer)), ("", (0, 0))); +} + +#[test] +fn replacing_all_of_nothing_is_no_edit() { + let mut buffer = Buffer::new("a"); + + assert_eq!(buffer.replace_all(&query("z", "x")), (0, None)); + assert!(buffer.undo().is_none()); +} + +#[test] +fn a_regular_expression_s_groups_are_replaced_in_each_match() { + let swap = Query { + regexp: true, + ..query(r"(\w+):(\d+)", "$2px $1") + }; + let mut buffer = Buffer::new("a:1 b:22"); + + buffer.replace_all(&swap); + + assert_eq!(buffer.text(), "1px a 22px b"); +} + +#[test] +fn a_letter_typed_over_a_selection_is_a_step_of_its_own() { + let mut buffer = over("abc", 0, 2); + typed(&mut buffer, "xy"); + + buffer.undo(); + assert_eq!(buffer.text(), "xc"); + buffer.undo(); + assert_eq!(buffer.text(), "abc"); +} + +#[test] +fn a_line_typed_after_a_space_starts_a_step_of_its_own() { + let mut buffer = Buffer::new(""); + typed(&mut buffer, "a \nb"); + + buffer.undo(); + assert_eq!(buffer.text(), "a "); +} + +#[test] +fn what_was_redone_is_undone_again_and_typing_after_it_is_a_step_of_its_own() { + let mut buffer = Buffer::new(""); + typed(&mut buffer, "a"); + buffer.undo(); + buffer.redo(); + typed(&mut buffer, "b"); + + buffer.undo(); + assert_eq!(buffer.text(), "a"); + buffer.undo(); + assert_eq!(buffer.text(), ""); +} + +/// A carriage return alone is a space like another, for a word. +#[test] +fn a_step_by_word_goes_over_a_carriage_return_alone() { + assert_eq!( + Buffer::new("a\r b").step(1, Direction::Forward, Unit::Word), + 4 + ); } diff --git a/crates/text/src/diff.rs b/crates/text/src/diff.rs index 2970eff95..c1f464af4 100644 --- a/crates/text/src/diff.rs +++ b/crates/text/src/diff.rs @@ -83,4 +83,19 @@ mod tests { 2100 ); } + + #[test] + fn lines_added_at_either_end_are_marked() { + assert_eq!(changed_lines("a\nb", "x\na\nb"), [0]); + assert_eq!(changed_lines("a\nb", "a\nb\nx"), [2]); + assert_eq!(changed_lines("", "a\nb"), [0, 1]); + assert_eq!(changed_lines("a\na", "a\na\na"), [2]); + } + + /// The longest run of lines kept: the fewest marked. + #[test] + fn a_line_moved_is_the_only_one_marked() { + assert_eq!(changed_lines("a\nb\nc\nd", "b\nc\nd\na"), [3]); + assert_eq!(changed_lines("a\nb\nc\nd\ne", "e\na\nb\nx\nd"), [0, 3]); + } } diff --git a/crates/text/src/highlight.rs b/crates/text/src/highlight.rs index 20a129074..8b2c4f8b4 100644 --- a/crates/text/src/highlight.rs +++ b/crates/text/src/highlight.rs @@ -436,4 +436,88 @@ mod tests { ); } } + + #[test] + fn two_stretches_of_one_class_apart_are_two() { + warm(); + let lines = highlight("[1, 2]\n", "JSON"); + + let literals: Vec<_> = lines[0] + .iter() + .filter(|(_, token)| *token == Token::Literal) + .collect(); + assert_eq!(literals, [&(1..2, Token::Literal), &(4..5, Token::Literal)]); + } + + #[test] + fn two_classes_side_by_side_are_two_stretches() { + warm(); + let lines = highlight("x=\"a\"//b\n", "TypeScript"); + + let tokens: Vec = lines[0].iter().map(|(_, token)| *token).collect(); + assert!( + tokens.ends_with(&[Token::String, Token::Comment]), + "{:?}", + lines[0] + ); + assert!( + lines[0] + .windows(2) + .all(|pair| pair[0].0.end <= pair[1].0.start) + ); + } + + /// Read past the end of a block, its state is kept for the next. + #[test] + fn lines_read_past_a_block_keep_its_state_once() { + warm(); + let lines: Vec = (0..600).map(|n| format!("let a{n} = {n};\n")).collect(); + let line_of = |at: usize| lines.get(at).cloned(); + let mut highlighter = Highlighter::new("JavaScript").unwrap(); + + highlighter.lines(line_of, 0..EVERY - 1); + assert_eq!(highlighter.reach(), 0); + highlighter.lines(line_of, 0..EVERY * 2); + assert_eq!(highlighter.reach(), EVERY * 2); + highlighter.lines(line_of, 0..EVERY * 2); + assert_eq!(highlighter.reach(), EVERY * 2); + } + + /// As many lines as the budget, block by block; a text's end is an end. + #[test] + fn states_are_kept_within_a_budget() { + warm(); + let lines: Vec = (0..EVERY * 3).map(|_| "let a;\n".to_owned()).collect(); + let line_of = |at: usize| lines.get(at).cloned(); + let mut highlighter = Highlighter::new("JavaScript").unwrap(); + + assert!(!highlighter.extend(line_of, EVERY * 2, EVERY)); + assert_eq!(highlighter.reach(), EVERY); + assert!(highlighter.extend(line_of, EVERY * 2, EVERY)); + assert_eq!(highlighter.reach(), EVERY * 2); + assert!(highlighter.extend(line_of, EVERY * 50, usize::MAX)); + } + + /// A scope is read whole: `stringy` is no `string`. + #[test] + fn a_scope_gives_the_class_of_the_first_rule_it_falls_under() { + for (scope, token) in [ + ("comment.line", Some(Token::Comment)), + ("string", Some(Token::String)), + ("stringy.quoted", None), + ("constant.character.escape.js", Some(Token::String)), + ("constant.numeric", Some(Token::Literal)), + ("variable.function.js", Some(Token::Keyword)), + ("variable.other", Some(Token::Property)), + ("meta.block", None), + ] { + assert_eq!(class(Scope::new(scope).unwrap()), token, "{scope}"); + } + } + + #[test] + fn a_grammar_is_there_by_its_name() { + warm(); + assert!(is_ready() && has_syntax("Rust") && !has_syntax("rust")); + } } diff --git a/crates/text/src/indent.rs b/crates/text/src/indent.rs index 335e21989..763f8cbfb 100644 --- a/crates/text/src/indent.rs +++ b/crates/text/src/indent.rs @@ -256,4 +256,18 @@ mod tests { fn offsets_are_characters_not_bytes() { assert_eq!(tab("é[]", " "), some("é []")); } + + /// The caret at the start of a line is of that line, not of the one above. + #[test] + fn a_caret_at_a_line_s_start_is_of_that_line() { + assert_eq!(shift_tab(" a\n[] b", " "), some(" a\n[]b")); + assert_eq!(tab("a\n[]b", " "), some("a\n []b")); + } + + /// At a level already, Tab goes a whole one further. + #[test] + fn tab_at_a_level_goes_to_the_next() { + assert_eq!(tab(" []a", " "), some(" []a")); + assert_eq!(tab("[]", " "), some(" []")); + } } diff --git a/crates/text/src/search.rs b/crates/text/src/search.rs index 37f9a139d..39775861c 100644 --- a/crates/text/src/search.rs +++ b/crates/text/src/search.rs @@ -144,85 +144,123 @@ mod tests { } } + fn pattern(search: &str) -> Query { + Query { + regexp: true, + ..query(search) + } + } + + fn found(text: &str, query: &Query) -> Vec> { + find(text, query, COUNT_CAP) + } + #[test] fn a_text_is_found_ignoring_case_unless_asked() { - assert_eq!(find("Host host", &query("host"), COUNT_CAP), [0..4, 5..9]); let exact = Query { case_sensitive: true, - ..query("host") + ..query("été") }; - assert_eq!(find("Host host", &exact, COUNT_CAP), vec![5..9]); + + assert_eq!(found("Été été", &query("été")), [0..3, 4..7]); + assert_eq!(found("Été été", &exact), vec![4..7]); } + /// An underscore and an accented letter are of a word. #[test] fn whole_words_skip_a_match_inside_a_word() { let whole = Query { whole_word: true, ..query("id") }; - assert_eq!( - find("id user_id idx (id)", &whole, COUNT_CAP), - [0..2, 16..18] - ); + + assert_eq!(found("id user_id idx éid (id)", &whole), [0..2, 20..22]); } #[test] fn a_regular_expression_reads_its_metacharacters_and_a_text_does_not() { - let pattern = Query { - regexp: true, - ..query(r"\d+") - }; - assert_eq!(find("a 12 b 345", &pattern, COUNT_CAP), [2..4, 7..10]); - assert_eq!(find("a.b axb", &query("a.b"), COUNT_CAP), vec![0..3]); - assert!( - !Query { - regexp: true, - ..query("(") - } - .is_valid() - ); + assert_eq!(found("a 12 b 345", &pattern(r"\d+")), [2..4, 7..10]); + assert_eq!(found("a.b axb", &query("a.b")), vec![0..3]); } + /// A line each, as an editor reads them. #[test] - fn ranges_are_characters_and_the_cap_stops_the_count() { - assert_eq!(find("éé x", &query("x"), COUNT_CAP), vec![3..4]); - assert_eq!(find("aaaa", &query("a"), 2).len(), 2); + fn a_regular_expression_s_anchors_are_the_line_s() { + assert_eq!(found("ab\nab", &pattern("^a")), [0..1, 3..4]); + assert_eq!(found("ab\nab", &pattern("b$")), [1..2, 4..5]); } #[test] - fn a_replacement_names_the_groups_in_a_regular_expression_only() { - let swap = Query { - regexp: true, - replace: "$2=$1 ($&)".into(), - ..query(r"(\w+):(\w+)") - }; - assert_eq!(swap.replacement("port:5432"), "5432=port (port:5432)"); - for (template, replaced) in [ + fn a_match_of_nothing_is_none() { + assert!(found("ab", &pattern("x*")).is_empty()); + assert_eq!(found("xab", &pattern("x*")), vec![0..1]); + } + + #[test] + fn nothing_is_found_of_an_empty_search_or_a_pattern_that_does_not_read() { + assert!(found("ab", &query("")).is_empty()); + assert!(found("a(b", &pattern("(")).is_empty()); + assert!(query("").is_valid() && query("(").is_valid() && pattern("a").is_valid()); + assert!(!pattern("(").is_valid()); + } + + #[test] + fn ranges_are_characters_not_bytes() { + assert_eq!(found("éé x🦀 x", &query("x")), [3..4, 6..7]); + } + + #[test] + fn as_many_matches_as_asked_are_found() { + assert_eq!(find("aaaa", &query("a"), 2), [0..1, 1..2]); + assert_eq!(find("aa", &query("a"), 2).len(), 2); + } + + fn replaced(search: &str, replace: &str, found: &str) -> String { + Query { + replace: replace.into(), + ..pattern(search) + } + .replacement(found) + } + + /// `$1px` was read as a group named `1px`, and replaced by nothing (#1776). + #[test] + fn a_replacement_names_the_match_and_its_groups() { + for (template, expected) in [ + ("$2=$1 ($&)", "5432=port (port:5432)"), ("$1px", "portpx"), ("$1_$2", "port_5432"), ("$12", "port2"), ("$01", "port"), ("$3 $0", "$3 $0"), ("$$1 $total $", "$1 $total $"), - ("{$&}", "{port:5432}"), ("é$2é", "é5432é"), + ("", ""), ] { - let query = Query { - replace: template.into(), - ..swap.clone() - }; - assert_eq!(query.replacement("port:5432"), replaced, "{template}"); + assert_eq!( + replaced(r"(\w+):(\w+)", template, "port:5432"), + expected, + "{template}" + ); + } + } + + #[test] + fn a_group_that_took_no_part_is_empty() { + assert_eq!(replaced("a(b)?", "[$1]", "a"), "[]"); + } + + #[test] + fn a_replacement_is_as_written_where_no_group_can_be_read() { + assert_eq!(query_replacing("a", "$1$&").replacement("a"), "$1$&"); + assert_eq!(replaced("(", "$1", "a"), "$1"); + assert_eq!(replaced("(b)", "$1", "a"), "$1"); + } + + fn query_replacing(search: &str, replace: &str) -> Query { + Query { + replace: replace.into(), + ..query(search) } - let optional = Query { - regexp: true, - replace: "[$1]".into(), - ..query(r"a(b)?") - }; - assert_eq!(optional.replacement("a"), "[]"); - let plain = Query { - replace: "$1".into(), - ..query("a") - }; - assert_eq!(plain.replacement("a"), "$1"); } } diff --git a/crates/text/src/shield.rs b/crates/text/src/shield.rs index d7d236a5e..f892f47a9 100644 --- a/crates/text/src/shield.rs +++ b/crates/text/src/shield.rs @@ -191,4 +191,36 @@ mod tests { let stand_in = one.stand_ins().next().unwrap().to_owned(); assert!(unshield_fields(&format!("{stand_in} {stand_in}"), 0, &one).is_none()); } + + /// At its edges a caret stays outside the field; inside, it goes to its start. + #[test] + fn a_caret_at_the_edge_of_a_field_stays_at_that_edge() { + let shielded = |cursor: usize| shield_fields("ab {{field}} cd", cursor).unwrap().cursor; + + assert_eq!([2, 3, 4, 11, 12, 13].map(shielded), [2, 3, 3, 3, 12, 13]); + } + + /// Two letters, one of each: one letter twice would be found inside itself. + #[test] + fn the_marker_is_two_letters_that_differ() { + for text in ["{{a}}", "qz {{a}}", "qz qj qk qv qw {{a}}"] { + let marker = shield_fields(text, 0).unwrap().marker; + let letters: Vec = marker.chars().collect(); + assert!( + letters.len() == 2 && letters[0] != letters[1] && !text.contains(&marker), + "{marker}" + ); + } + } + + /// Each field's own length, before and after the caret. + #[test] + fn the_caret_comes_back_past_fields_that_were_lengthened() { + let text = "{{}}-{{}} end"; + for cursor in [4, 5, 9, 13] { + let shielded = shield_fields(text, cursor).unwrap(); + let back = unshield_fields(&shielded.text, shielded.cursor, &shielded); + assert_eq!(back, Some((text.to_owned(), cursor)), "{cursor}"); + } + } } diff --git a/crates/text/src/words.rs b/crates/text/src/words.rs index 160248cb8..2d1fd1505 100644 --- a/crates/text/src/words.rs +++ b/crates/text/src/words.rs @@ -115,4 +115,25 @@ mod tests { assert_eq!(count_words(""), 0); assert_eq!(count_words(" \n\n "), 0); } + + /// On a blank line there is nothing to take. + #[test] + fn a_double_click_past_a_line_takes_its_last_run_and_nothing_of_a_blank_one() { + for (text, at, taken) in [ + ("ab\n\ncd", 2, "ab"), + ("ab\n\ncd", 3, ""), + ("ab\n\ncd", 4, "cd"), + ("\n", 0, ""), + ("\n", 1, ""), + ("a \nb", 2, " "), + ] { + assert_eq!(word(text, at), taken, "{text:?} {at}"); + } + } + + #[test] + fn a_number_and_a_word_of_any_script_are_words() { + assert_eq!(count_words("3 été Привет 日本 a-b l'a 'x'"), 7); + assert_eq!(count_words("-- * __ !"), 0); + } } From 179ac164fed5c2762acecf16f61b6fbb958c66e8 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 08:16:50 +0100 Subject: [PATCH 60/95] Request scripts: the global _ is lodash after a require (#1770) Co-authored-by: Claude Opus 5.5 --- crates/engine/src/http/scripts/engine.rs | 22 ++++++++++++++++++++++ crates/engine/src/http/scripts/prelude.js | 18 ++++++++++++------ 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/http/scripts/engine.rs b/crates/engine/src/http/scripts/engine.rs index b9ca95188..cacac9590 100644 --- a/crates/engine/src/http/scripts/engine.rs +++ b/crates/engine/src/http/scripts/engine.rs @@ -823,6 +823,28 @@ mod tests { }); } + /// lodash reads `_` while it loads, and was given itself half made (#1769). + #[test] + fn a_library_s_global_is_what_its_require_answers() { + hosted(|| { + for (global, library) in [ + ("_", "lodash"), + ("CryptoJS", "crypto-js"), + ("tv4", "tv4"), + ("cheerio", "cheerio"), + ("moment", "moment"), + ] { + for same in [ + format!("require('{library}') === {global}"), + format!("{global} === require('{library}')"), + ] { + let outcome = run(&format!("if (!({same})) throw new Error('not the same');")); + assert_eq!(outcome.failure, None, "{same}"); + } + } + }); + } + #[test] fn send_request_goes_to_the_host_and_answers_by_callback_or_promise() { hosted(|| { diff --git a/crates/engine/src/http/scripts/prelude.js b/crates/engine/src/http/scripts/prelude.js index dcb74ab94..f02a0d2de 100644 --- a/crates/engine/src/http/scripts/prelude.js +++ b/crates/engine/src/http/scripts/prelude.js @@ -14,7 +14,7 @@ configurable: true, get() { const value = load(); - define(target, name, value); + if (value !== undefined) define(target, name, value); return value; }, set(value) { @@ -299,6 +299,7 @@ // ── require ────────────────────────────────────────────────────────────────────────────── const modules = new Map(); + const loading = new Set(); const ALIASES = { 'csv-parse/lib/sync': 'csv-parse/sync', 'path-browserify': 'path' }; const OWN = { atob: () => atobOf, @@ -311,7 +312,9 @@ if (typeof factory !== 'function') return undefined; const module = { exports: {} }; modules.set(name, module); + loading.add(name); factory(module, module.exports, requireOf); + loading.delete(name); return module.exports; } @@ -344,11 +347,14 @@ define(global, 'require', requireOf); lazy(global, 'Buffer', () => requireOf('buffer').Buffer); - lazy(global, '_', () => requireOf('lodash')); - lazy(global, 'CryptoJS', () => requireOf('crypto-js')); - lazy(global, 'tv4', () => requireOf('tv4')); - lazy(global, 'cheerio', () => requireOf('cheerio')); - lazy(global, 'moment', () => requireOf('moment')); + // lodash reads `_` while it loads: it finds no global, and not its own exports half made. + const libraryGlobal = (name, library) => + lazy(global, name, () => (loading.has(library) ? undefined : requireOf(library))); + libraryGlobal('_', 'lodash'); + libraryGlobal('CryptoJS', 'crypto-js'); + libraryGlobal('tv4', 'tv4'); + libraryGlobal('cheerio', 'cheerio'); + libraryGlobal('moment', 'moment'); // ── Lists of key and value: headers, a query, a form ───────────────────────────────────── From 0a22875207e5c9fdde761a9c0f3530cb84e28621 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 08:17:06 +0100 Subject: [PATCH 61/95] JSON explorer: unit tests rewritten for the readers and the model (#1774) * Rewrite the tests of the JSON explorer: readers, positions, opening, search, tree and layout Co-Authored-By: Claude Opus 5.5 * The edges of what opens whole, of a nesting of objects and of the values a YAML holds Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/json.rs | 31 ++ crates/engine/src/json/model.rs | 696 ++++++++++++++++++----------- crates/engine/src/json/parse.rs | 229 ++++++---- crates/engine/src/json/position.rs | 76 +++- crates/engine/src/json/read.rs | 48 +- crates/engine/src/json/toml.rs | 139 +++--- crates/engine/src/json/xml.rs | 197 +++++--- crates/engine/src/json/yaml.rs | 281 +++++++----- 8 files changed, 1077 insertions(+), 620 deletions(-) diff --git a/crates/engine/src/json.rs b/crates/engine/src/json.rs index 84cfa5b88..f16871871 100644 --- a/crates/engine/src/json.rs +++ b/crates/engine/src/json.rs @@ -10,3 +10,34 @@ pub mod read; mod toml; pub(crate) mod xml; pub(crate) mod yaml; + +#[cfg(test)] +pub(crate) mod testing { + //! What the readers' tests read of a tree. + + use super::parse::{Node, Value}; + + pub(crate) fn members(node: &Node) -> &[(String, Node)] { + match &node.value { + Value::Object(members) => members, + other => panic!("an object, not {other:?}"), + } + } + + pub(crate) fn keys(node: &Node) -> Vec<&str> { + members(node).iter().map(|(key, _)| key.as_str()).collect() + } + + pub(crate) fn array(node: &Node) -> &[Node] { + match &node.value { + Value::Array(items) => items, + other => panic!("a list, not {other:?}"), + } + } + + /// The text a value was read from. + pub(crate) fn slice(text: &str, node: &Node) -> String { + let units: Vec = text.encode_utf16().collect(); + String::from_utf16(&units[node.span.start as usize..node.span.end as usize]).unwrap() + } +} diff --git a/crates/engine/src/json/model.rs b/crates/engine/src/json/model.rs index cf9ee525d..d0c447342 100644 --- a/crates/engine/src/json/model.rs +++ b/crates/engine/src/json/model.rs @@ -571,6 +571,7 @@ fn count(value: usize) -> u32 { #[cfg(test)] mod tests { + use super::super::parse::JsonErrorReason; use super::*; const INVOICE: &str = r#"{ @@ -589,6 +590,18 @@ mod tests { } }"#; + /// Every container of the invoice, in the document's order. + const CONTAINERS: [&str; 8] = [ + "$", + "$.data", + "$.data.object", + "$.data.object.customer", + "$.data.object.lines", + "$.data.object.lines[0]", + "$.data.object.lines[0].period", + "$.data.object.lines[1]", + ]; + fn query(text: &str, search: &str, opening: JsonOpening) -> JsonQuery { JsonQuery { text: text.to_string(), @@ -602,364 +615,458 @@ mod tests { explore(&query(text, "", JsonOpening::Initial)) } - fn node<'a>(view: &'a JsonView, path: &str) -> &'a JsonNode { + fn opening(text: &str, opening: JsonOpening) -> JsonView { + explore(&query(text, "", opening)) + } + + fn paths(paths: &[&str]) -> JsonOpening { + JsonOpening::Paths { + paths: paths.iter().map(|path| (*path).to_string()).collect(), + reveal: None, + } + } + + fn searched(search: &str) -> JsonView { + explore(&query(INVOICE, search, JsonOpening::Initial)) + } + + /// The nodes drawn, by path. + fn drawn(view: &JsonView) -> Vec<&str> { view.graph .nodes .iter() - .find(|node| node.path == path) - .unwrap_or_else(|| panic!("no node at {path}")) + .map(|node| node.path.as_str()) + .collect() + } + + fn node<'a>(view: &'a JsonView, path: &str) -> &'a JsonNode { + let found = view.graph.nodes.iter().find(|node| node.path == path); + found.unwrap_or_else(|| panic!("no node at {path}")) + } + + fn numbers(count: usize) -> String { + let numbers: Vec = (0..count).map(|i| i.to_string()).collect(); + format!("[{}]", numbers.join(",")) } - /// `n` objects in one array: a document that is not small. - fn many(n: usize) -> String { - let items: Vec = (0..n).map(|i| format!(r#"{{"i": {i}}}"#)).collect(); + /// `count` objects in one array. + fn objects(count: usize) -> String { + let items: Vec = (0..count).map(|i| format!(r#"{{"i": {i}}}"#)).collect(); format!("[{}]", items.join(",")) } + /// `count` arrays of `each` objects, in one object. + fn arrays(count: usize, each: usize) -> String { + let arrays: Vec = (0..count) + .map(|i| format!(r#""a{i}": {}"#, objects(each))) + .collect(); + format!("{{{}}}", arrays.join(",")) + } + + // ── What is open ── + #[test] fn a_small_document_opens_whole() { let view = explored(INVOICE); - let paths: Vec<&str> = view - .graph - .nodes - .iter() - .map(|node| node.path.as_str()) - .collect(); - assert_eq!( - paths, - [ - "$", - "$.data", - "$.data.object", - "$.data.object.customer", - "$.data.object.lines", - "$.data.object.lines[0]", - "$.data.object.lines[0].period", - "$.data.object.lines[1]", - ] - ); - assert!(view.error.is_none()); - assert!(!view.graph.folded); + assert_eq!(drawn(&view), CONTAINERS); + assert!(view.error.is_none() && !view.graph.folded); } + /// Sixty-four containers, then one more: the root, its arrays, their objects. #[test] - fn a_node_lists_its_values_as_rows_and_opens_its_containers() { - let view = explored(INVOICE); - let root = node(&view, "$"); - let values: Vec<(&str, &str, JsonKind)> = root - .rows - .iter() - .map(|row| (row.key.as_str(), row.value.as_str(), row.kind)) - .collect(); - - assert_eq!( - values, - [ - ("id", "\"evt_1PqX4c\"", JsonKind::String), - ("type", "\"invoice.paid\"", JsonKind::String), - ("livemode", "false", JsonKind::Boolean), - ("data", "{ … }", JsonKind::Object), - ] - ); - assert_eq!( - (root.label.as_str(), root.kind, root.size), - ("$", JsonKind::Object, 4) - ); - assert_eq!(root.rows[3].child, Some(node(&view, "$.data").id)); - assert!(root.rows[3].opens && !root.rows[0].opens); + fn a_document_past_what_opens_whole_opens_on_its_first_level() { + let (whole, past) = (explored(&arrays(3, 20)), explored(&arrays(2, 31))); - let lines = node(&view, "$.data.object.lines"); - assert_eq!( - (lines.label.as_str(), lines.kind, lines.size), - ("lines", JsonKind::Array, 2) - ); - assert_eq!(node(&view, "$.data.object.lines[0]").label, "[0]"); - assert_eq!(node(&view, "$.data").parent, Some(root.id)); + assert_eq!(whole.graph.nodes.len(), OPEN_WHOLE_UP_TO); + assert_eq!(drawn(&past), ["$", "$.a0", "$.a1"]); } #[test] - fn a_value_keeps_where_it_is_in_the_text() { - let view = explored(INVOICE); - let row = &node(&view, "$").rows[0]; + fn the_paths_asked_open_and_none_under_a_closed_one() { + let view = opening(INVOICE, paths(&["$.data", "$.data.object.customer"])); - assert_eq!( - &INVOICE[row.span.start as usize..row.span.end as usize], - "\"evt_1PqX4c\"" - ); + assert_eq!(drawn(&view), ["$", "$.data"]); + assert_eq!(node(&view, "$.data").rows[0].child, None); } - /// « Copier la valeur » put `"Lyon"` in the clipboard, its quotes with it (COD-23). + /// Its rows count what they hold. #[test] - fn a_string_carries_its_own_text_unquoted_and_nothing_else_does() { - let view = explored(r#"{"ville": "Ly\"on\u00e9", "n": 4, "o": {"a": 1}}"#); - let root = node(&view, "$"); - let texts: Vec> = root.rows.iter().map(|row| row.text.as_deref()).collect(); + fn no_path_asked_opens_the_root_alone() { + let view = opening(INVOICE, paths(&[])); - assert_eq!(texts, [Some("Ly\"oné"), None, None]); - let line = view - .tree - .iter() - .find(|line| line.path == "$.ville") - .unwrap(); - assert_eq!(line.text.as_deref(), Some("Ly\"oné")); + assert_eq!(drawn(&view), ["$"]); + let data = &node(&view, "$").rows[3]; + assert_eq!( + (data.path.as_str(), data.child, data.size), + ("$.data", None, 1) + ); } #[test] - fn counts_the_keys_the_depth_and_the_bytes() { - let stats = explored(INVOICE).stats; + fn a_path_revealed_opens_everything_above_it() { + let reveal = |path: &str| JsonOpening::Paths { + paths: Vec::new(), + reveal: Some(path.to_string()), + }; - assert_eq!(stats.keys, 15); - assert_eq!(stats.depth, 5); - assert_eq!(stats.bytes, u32::try_from(INVOICE.len()).unwrap()); + let view = opening(INVOICE, reveal("$.data.object.lines[1].description")); + let expected = [ + "$", + "$.data", + "$.data.object", + "$.data.object.lines", + "$.data.object.lines[1]", + ]; + assert_eq!(drawn(&view), expected); + assert_eq!(drawn(&opening(INVOICE, reveal("$.gone"))), ["$"]); } + /// 3,021 containers, each array within a node's rows: the arrays stay folded, and it is said. #[test] - fn a_larger_document_opens_on_its_first_level() { - let view = explored(&many(100)); + fn opening_everything_folds_arrays_past_what_can_be_drawn() { + let view = opening(&arrays(20, 150), JsonOpening::All); - assert_eq!(view.graph.nodes.len(), 101); + assert!(view.graph.folded); + assert_eq!(view.graph.nodes.len(), 21); + let first = &view.graph.nodes[1]; assert!( - view.graph.nodes[1..] + first + .rows .iter() - .all(|node| node.rows[0].child.is_none()) + .all(|row| row.opens && row.child.is_none()) ); - assert!(!view.graph.folded); } + /// The cap keeps the levels nearest the root, and nothing says the arrays were folded. #[test] - fn opens_the_paths_asked_and_none_under_a_closed_one() { - let opening = JsonOpening::Paths { - paths: vec!["$.data".into(), "$.data.object.customer".into()], - reveal: None, - }; - let view = explore(&query(INVOICE, "", opening)); - let paths: Vec<&str> = view - .graph - .nodes + fn opening_by_paths_stops_at_what_can_be_drawn() { + let text = arrays(20, 150); + let every: Vec = explore(&query(&text, "i", JsonOpening::All)) + .matches .iter() - .map(|node| node.path.as_str()) + .filter_map(|path| path.strip_suffix(".i").map(str::to_string)) + .chain((0..20).map(|i| format!("$.a{i}"))) .collect(); - assert_eq!(paths, ["$", "$.data"]); - assert_eq!(node(&view, "$.data").rows[0].child, None); + let view = opening( + &text, + JsonOpening::Paths { + paths: every, + reveal: None, + }, + ); + + let arrays = view + .graph + .nodes + .iter() + .filter(|node| node.kind == JsonKind::Array); + assert_eq!(arrays.count(), 20); + assert!(view.graph.nodes.len() <= MAX_NODES); } #[test] - fn no_path_asked_opens_the_root_alone_its_rows_counting_what_they_hold() { - let opening = JsonOpening::Paths { - paths: Vec::new(), - reveal: None, - }; - let view = explore(&query(INVOICE, "", opening)); + fn no_more_rows_are_drawn_than_a_graph_can_hold() { + // 120 arrays of 200 numbers: 24,000 rows asked, 120 nodes. + let arrays: Vec = (0..120).map(|_| numbers(ROWS_PER_NODE)).collect(); + let view = opening(&format!("[{}]", arrays.join(",")), JsonOpening::All); - assert_eq!(view.graph.nodes.len(), 1); - let data = &node(&view, "$").rows[3]; - assert_eq!( - (data.path.as_str(), data.child, data.size), - ("$.data", None, 1) - ); - assert_eq!(node(&view, "$").rows[0].size, 0); - assert_eq!(view.tree.len(), 5); + let rows: usize = view.graph.nodes.iter().map(|node| node.rows.len()).sum(); + assert!(rows <= MAX_ROWS, "{rows}"); + assert!(view.graph.folded); } #[test] - fn opening_everything_folds_arrays_past_what_can_be_drawn() { - // Twenty arrays of 150 objects: 3,021 containers, the arrays each within a node's rows. - let arrays: Vec = (0..20) - .map(|i| format!(r#""a{i}": {}"#, many(150))) - .collect(); - let view = explore(&query( - &format!("{{{}}}", arrays.join(",")), - "", - JsonOpening::All, - )); + fn only_the_rows_shown_can_open() { + let view = opening(&objects(MAX_NODES + 50), JsonOpening::All); - assert!(view.graph.folded); - assert_eq!(view.graph.nodes.len(), 21); - assert!( - view.graph.nodes[1] - .rows - .iter() - .all(|row| row.opens && row.child.is_none()) - ); + assert!(!view.graph.folded); + assert_eq!(view.graph.nodes.len(), 1 + ROWS_PER_NODE); } + // ── A node ── + #[test] - fn explores_a_yaml_document_in_the_same_model_under_the_same_caps() { - let items = (0..150) - .map(|i| format!(" - i: {i}\n")) - .collect::>() - .concat(); - let lists = (0..20) - .map(|i| format!("a{i}:\n{items}")) - .collect::>() - .concat(); - let yaml = |text: &str, opening| { - explore(&JsonQuery { - format: StructureFormat::Yaml, - ..query(text, "", opening) + fn a_node_lists_its_values_as_rows_of_one_line() { + let text = r#"{"s": "paid", "n": 4900, "t": true, "f": false, "z": null, "o": {"a": 1}, "l": [1, 2, 3]}"#; + let view = explored(text); + + let rows: Vec<_> = node(&view, "$") + .rows + .iter() + .map(|row| { + ( + row.key.as_str(), + row.value.as_str(), + row.kind, + row.size, + row.opens, + ) }) - }; + .collect(); + assert_eq!( + rows, + [ + ("s", "\"paid\"", JsonKind::String, 0, false), + ("n", "4900", JsonKind::Number, 0, false), + ("t", "true", JsonKind::Boolean, 0, false), + ("f", "false", JsonKind::Boolean, 0, false), + ("z", "null", JsonKind::Null, 0, false), + ("o", "{ … }", JsonKind::Object, 1, true), + ("l", "[ 3 ]", JsonKind::Array, 3, true), + ] + ); + } - let view = yaml(&lists, JsonOpening::All); - assert!(view.graph.folded); - assert_eq!(view.graph.nodes.len(), 21); - assert_eq!(view.graph.nodes[1].path, "$.a0"); + #[test] + fn a_node_says_what_it_is_under_and_links_the_rows_it_opened() { + let view = explored(INVOICE); + let (root, data, lines) = ( + node(&view, "$"), + node(&view, "$.data"), + node(&view, "$.data.object.lines"), + ); - let view = yaml("name: api\nports: [80, 443]\n", JsonOpening::Initial); assert_eq!( - view.tree - .iter() - .map(|line| line.path.as_str()) - .collect::>(), - ["$", "$.name", "$.ports", "$.ports[0]", "$.ports[1]"] + (root.label.as_str(), root.kind, root.size, root.parent), + ("$", JsonKind::Object, 4, None) ); - assert_eq!(view.notices, []); assert_eq!( - yaml("a: [1\n", JsonOpening::Initial) - .error - .map(|error| error.reason), - Some(super::super::parse::JsonErrorReason::Malformed) + (data.parent, root.rows[3].child), + (Some(root.id), Some(data.id)) ); + assert_eq!( + (lines.label.as_str(), lines.kind, lines.size), + ("lines", JsonKind::Array, 2) + ); + assert_eq!(node(&view, "$.data.object.lines[0]").label, "[0]"); + assert_eq!(lines.rows[1].key, "[1]"); } #[test] - fn only_the_rows_shown_can_open() { - let view = explore(&query(&many(MAX_NODES + 50), "", JsonOpening::All)); - - assert!(!view.graph.folded); - assert_eq!(view.graph.nodes.len(), 1 + ROWS_PER_NODE); + fn a_long_array_shows_its_first_rows_and_counts_the_rest() { + for (count, rows, hidden, height) in [ + (ROWS_PER_NODE, 200, 0, 201), + (ROWS_PER_NODE + 1, 200, 1, 202), + (500, 200, 300, 202), + ] { + let view = explored(&numbers(count)); + let root = node(&view, "$"); + assert_eq!( + (root.rows.len(), root.hidden_rows, root.height), + (rows, hidden, height) + ); + } } #[test] - fn a_long_array_shows_its_first_rows_and_counts_the_rest() { - let numbers: Vec = (0..500).map(|i| i.to_string()).collect(); - let view = explored(&format!("[{}]", numbers.join(","))); - let root = node(&view, "$"); + fn a_value_keeps_where_it_is_in_the_text() { + let view = explored(INVOICE); + let row = &node(&view, "$").rows[0]; - assert_eq!(root.rows.len(), ROWS_PER_NODE); - assert_eq!(root.hidden_rows, 300); - assert_eq!(root.height, 1 + 200 + 1); + assert_eq!( + &INVOICE[row.span.start as usize..row.span.end as usize], + "\"evt_1PqX4c\"" + ); } + /// « Copier la valeur » put `"Lyon"` in the clipboard, its quotes with it (COD-23). #[test] - fn finds_keys_and_values_folded_like_every_search() { - let view = explore(&query(INVOICE, "mensuel", JsonOpening::Initial)); + fn a_string_carries_its_own_text_unquoted_and_nothing_else_does() { + let view = explored(r#"{"ville": "Ly\"oné", "n": 4, "o": {"a": 1}}"#); - assert_eq!(view.matches, ["$.data.object.lines[0].description"]); - assert_eq!(view.match_count, 1); - assert!(node(&view, "$.data.object.lines[0]").rows[0].hit); + let texts: Vec<_> = node(&view, "$") + .rows + .iter() + .map(|row| row.text.as_deref()) + .collect(); + assert_eq!(texts, [Some("Ly\"oné"), None, None]); + let lines: Vec<_> = view.tree.iter().map(|line| line.text.as_deref()).collect(); + assert_eq!(lines, [None, Some("Ly\"oné"), None, None, None]); + } - let accents = explore(&query(INVOICE, "EXEMPLE", JsonOpening::Initial)); - assert_eq!(accents.matches, ["$.data.object.customer.email"]); + #[test] + fn a_value_is_cut_to_one_line_of_what_a_row_holds() { + let shown = |text: &str| { + node(&explored(&format!("[{text}]")), "$").rows[0] + .value + .clone() + }; + let long = |count: usize| format!("\"{}\"", "x".repeat(count)); - let keys = explore(&query(INVOICE, "period", JsonOpening::Initial)); - assert_eq!(keys.matches, ["$.data.object.lines[0].period"]); - assert!(node(&keys, "$.data.object.lines[0].period").hit); + assert_eq!(shown(r#""a\nb\tc""#), "\"a b c\""); + assert_eq!(shown(&long(VALUE_CHARS)), long(VALUE_CHARS)); + assert_eq!( + shown(&long(VALUE_CHARS + 1)), + format!("\"{}…\"", "x".repeat(VALUE_CHARS - 1)) + ); + assert_eq!( + shown(&"1".repeat(60)), + format!("{}…", "1".repeat(VALUE_CHARS - 1)) + ); } #[test] - fn reveals_a_path_by_opening_everything_above_it() { - let opening = JsonOpening::Paths { - paths: Vec::new(), - reveal: Some("$.data.object.lines[1].description".into()), - }; - let view = explore(&query(INVOICE, "", opening)); - let paths: Vec<&str> = view - .graph - .nodes + fn a_key_that_is_no_identifier_is_quoted_in_its_path() { + let view = explored( + r#"{"a key": 1, "it's": 2, "b\\s": 3, "1a": 4, "ok_1": 5, "$x": 6, "_": 7, "é": 8, "": 9}"#, + ); + + let paths: Vec<&str> = node(&view, "$") + .rows .iter() - .map(|node| node.path.as_str()) + .map(|row| row.path.as_str()) .collect(); - assert_eq!( paths, [ - "$", - "$.data", - "$.data.object", - "$.data.object.lines", - "$.data.object.lines[1]" + "$['a key']", + r"$['it\'s']", + r"$['b\\s']", + "$['1a']", + "$.ok_1", + "$.$x", + "$._", + "$['é']", + "$['']" ] ); } - #[test] - fn finds_what_is_not_open_too() { - let opening = JsonOpening::Paths { - paths: Vec::new(), - reveal: None, - }; - let view = explore(&query(INVOICE, "stockage", opening)); + // ── The layout ── - assert_eq!(view.matches, ["$.data.object.lines[1].description"]); - assert_eq!(view.graph.nodes.len(), 1); + #[test] + fn levels_go_left_to_right_each_as_wide_as_its_widest_node() { + let view = explored(INVOICE); + let column = |path: &str| (node(&view, path).x, node(&view, path).width); + + let (root, data) = (column("$"), column("$.data")); + assert_eq!(root.0, 0); + assert_eq!(data.0, root.1 + COLUMN_GAP); + let (customer, lines) = ( + column("$.data.object.customer"), + column("$.data.object.lines"), + ); + assert_eq!(customer.0, lines.0); + assert_eq!( + column("$.data.object.lines[0]").0, + customer.0 + customer.1.max(lines.1) + COLUMN_GAP + ); + let period = column("$.data.object.lines[0].period"); + assert_eq!(view.graph.width, period.0 + period.1); } + /// Under its header line, beside the row that opens it, whenever the nodes above leave room. #[test] - fn places_levels_left_to_right_and_children_by_their_rows() { + fn a_child_is_beside_its_row_and_below_the_one_before_it() { let view = explored(INVOICE); - let root = node(&view, "$"); - let data = node(&view, "$.data"); - let customer = node(&view, "$.data.object.customer"); - let lines = node(&view, "$.data.object.lines"); + let (data, customer, lines) = ( + node(&view, "$.data"), + node(&view, "$.data.object.customer"), + node(&view, "$.data.object.lines"), + ); - assert_eq!(root.x, 0); - assert_eq!(data.x, root.width + COLUMN_GAP); - // `data` is the root's fourth row, under its header line. - assert_eq!(data.y, root.y + 1 + 3); - assert_eq!(customer.x, lines.x); - assert!(lines.y >= customer.y + customer.height + NODE_GAP); - assert!(view.graph.width >= lines.x + lines.width); - assert!(view.graph.height >= lines.y + lines.height); + assert_eq!(data.y, 1 + 3); + assert_eq!(customer.y, node(&view, "$.data.object").y + 1 + 1); + assert_eq!(lines.y, customer.y + customer.height + NODE_GAP); + let bottom = view + .graph + .nodes + .iter() + .map(|node| node.y + node.height) + .max(); + assert_eq!(Some(view.graph.height), bottom); } #[test] - fn sizes_a_node_to_its_widest_row_within_bounds() { - let view = explored(r#"{"a": 1}"#); - assert_eq!(node(&view, "$").width, MIN_WIDTH); + fn a_node_is_as_wide_as_its_widest_row_within_bounds() { + let width = |text: &str| node(&explored(text), "$").width; - let wide = explored(&format!(r#"{{"key": "{}"}}"#, "x".repeat(200))); - assert_eq!(node(&wide, "$").width, MAX_WIDTH); + assert_eq!(width(r#"{"a": 1}"#), MIN_WIDTH); + assert_eq!(width(r#"{"a key of some length": 1234}"#), 20 + 4 + 5); + assert_eq!(width(r#"{"a key of some length": {}}"#), 20 + 5 + 8); assert_eq!( - node(&wide, "$").rows[0].value.chars().count(), - VALUE_CHARS + 2 + width(&format!(r#"{{"key": "{}"}}"#, "x".repeat(200))), + MAX_WIDTH ); + let long = explored(r#"{"a label longer than its rows": {"a": 1}}"#); + assert_eq!(long.graph.nodes[1].width, 28 + 12); } + // ── The search ── + #[test] - fn a_value_on_several_lines_is_shown_on_one() { - let view = explored(r#"["a\nb"]"#); + fn a_search_finds_keys_and_values_folded_like_every_search() { + for (search, found) in [ + ("mensuel", "$.data.object.lines[0].description"), + ("EXEMPLE", "$.data.object.customer.email"), + (" Period ", "$.data.object.lines[0].period"), + ("4900", "$.data.object.amount_paid"), + ("false", "$.livemode"), + ] { + let view = searched(search); + assert_eq!(view.matches, [found], "{search}"); + assert_eq!(view.match_count, 1); + } + } - assert_eq!(node(&view, "$").rows[0].value, "\"a b\""); + #[test] + fn a_search_of_nothing_or_of_the_root_finds_nothing() { + for search in ["", " ", "$", "nowhere"] { + assert_eq!(searched(search).match_count, 0, "{search:?}"); + } } #[test] - fn a_key_that_is_no_identifier_is_quoted_in_its_path() { - let view = explored(r#"{"a key": {"it's": {"ok_1": {}}}}"#); + fn what_a_search_found_is_marked_in_the_graph_and_the_tree() { + let view = searched("period"); - assert!( - view.graph - .nodes - .iter() - .any(|node| node.path == r"$['a key']['it\'s'].ok_1") - ); + assert!(node(&view, "$.data.object.lines[0].period").hit); + assert!(node(&view, "$.data.object.lines[0]").rows[1].hit); + assert!(!node(&view, "$.data.object.lines[0]").rows[0].hit); + let marked: Vec<&str> = view + .tree + .iter() + .filter(|line| line.hit) + .map(|line| line.key.as_str()) + .collect(); + assert_eq!(marked, ["period"]); } + /// Stepping to one opens its ancestors. #[test] - fn the_tree_lists_what_is_open_in_the_documents_order() { - let opening = JsonOpening::Paths { - paths: vec!["$.data".into()], - reveal: None, - }; - let view = explore(&query(INVOICE, "", opening)); - let lines: Vec<(u32, &str, bool, bool)> = view + fn a_search_covers_what_is_not_open_in_the_document_s_order() { + let view = explore(&query(INVOICE, "description", paths(&[]))); + + let expected = [ + "$.data.object.lines[0].description", + "$.data.object.lines[1].description", + ]; + assert_eq!(view.matches, expected); + assert_eq!(view.graph.nodes.len(), 1); + } + + #[test] + fn the_matches_listed_are_capped_and_all_counted() { + let text = objects(MAX_MATCHES + 10); + + let view = explore(&query(&text, "i", JsonOpening::Initial)); + + assert_eq!((view.matches.len(), view.match_count), (MAX_MATCHES, 1010)); + } + + // ── The tree, the counts ── + + #[test] + fn the_tree_lists_what_is_open_in_the_document_s_order() { + let view = opening(INVOICE, paths(&["$.data"])); + + let lines: Vec<_> = view .tree .iter() .map(|line| (line.depth, line.key.as_str(), line.opens, line.open)) .collect(); - assert_eq!( lines, [ @@ -976,25 +1083,49 @@ mod tests { #[test] fn the_tree_stops_at_what_a_list_can_hold() { - let numbers: Vec = (0..6000).map(|i| i.to_string()).collect(); - let all = explore(&query( - &format!("[{}]", numbers.join(",")), - "", - JsonOpening::All, - )); + let whole = opening(&numbers(MAX_TREE_LINES - 1), JsonOpening::All); + let cut = opening(&numbers(MAX_TREE_LINES), JsonOpening::All); + + assert_eq!( + (whole.tree.len(), whole.tree_truncated), + (MAX_TREE_LINES, false) + ); + assert_eq!((cut.tree.len(), cut.tree_truncated), (MAX_TREE_LINES, true)); + } - assert_eq!(all.tree.len(), MAX_TREE_LINES); - assert!(all.tree_truncated); + #[test] + fn the_keys_the_levels_and_the_bytes_are_counted() { + for (text, keys, depth) in [ + (INVOICE, 15, 5), + ("42", 0, 0), + ("[]", 0, 0), + (r#"{"a": {"b": 1}}"#, 2, 1), + (r#"[{"é": [[1]]}]"#, 1, 3), + ] { + let stats = explored(text).stats; + assert_eq!( + (stats.keys, stats.depth, stats.bytes as usize), + (keys, depth, text.len()), + "{text}" + ); + } } #[test] fn an_invalid_document_says_where_and_draws_nothing() { let view = explored("{\"a\": }"); - let error = view.error.expect("an error"); + let error = view.error.unwrap(); assert_eq!((error.line, error.column), (1, 7)); - assert!(view.graph.nodes.is_empty() && view.tree.is_empty()); - assert_eq!(view.stats.bytes, 7); + assert!(view.graph.nodes.is_empty() && view.tree.is_empty() && view.matches.is_empty()); + assert_eq!( + view.stats, + JsonStats { + keys: 0, + depth: 0, + bytes: 7 + } + ); } #[test] @@ -1002,7 +1133,54 @@ mod tests { let view = explored("42"); assert!(view.graph.nodes.is_empty()); - assert_eq!(view.tree.len(), 1); + assert_eq!((view.tree.len(), view.tree[0].value.as_str()), (1, "42")); assert_eq!((view.graph.width, view.graph.height), (0, 0)); } + + /// One model, a reader per format: the caps are the model's. + #[test] + fn another_format_is_explored_in_the_same_model_under_the_same_caps() { + let yaml = |text: &str, opening| { + explore(&JsonQuery { + format: StructureFormat::Yaml, + ..query(text, "", opening) + }) + }; + let items = (0..150) + .map(|i| format!(" - i: {i}\n")) + .collect::>() + .concat(); + let lists = (0..20) + .map(|i| format!("a{i}:\n{items}")) + .collect::>() + .concat(); + + let capped = yaml(&lists, JsonOpening::All); + assert_eq!((capped.graph.folded, capped.graph.nodes.len()), (true, 21)); + + let small = yaml("name: api\nports: [80]\n---\nb: 1\n", JsonOpening::Initial); + let tree: Vec<&str> = small.tree.iter().map(|line| line.path.as_str()).collect(); + assert_eq!(tree, ["$", "$.name", "$.ports", "$.ports[0]"]); + assert_eq!(small.notices, [JsonNotice::FirstDocumentOnly]); + + let broken = yaml("a: [1\n", JsonOpening::Initial); + assert_eq!( + broken.error.map(|error| error.reason), + Some(JsonErrorReason::Malformed) + ); + } + + #[test] + fn a_date_is_a_kind_of_its_own() { + let view = explore(&JsonQuery { + format: StructureFormat::Toml, + ..query("d = 1979-05-27\n", "1979", JsonOpening::Initial) + }); + + let row = &node(&view, "$").rows[0]; + assert_eq!( + (row.kind, row.value.as_str(), row.hit), + (JsonKind::Datetime, "1979-05-27", true) + ); + } } diff --git a/crates/engine/src/json/parse.rs b/crates/engine/src/json/parse.rs index 9a027cd0f..f7275a5fc 100644 --- a/crates/engine/src/json/parse.rs +++ b/crates/engine/src/json/parse.rs @@ -346,132 +346,199 @@ fn count(value: usize) -> u32 { mod tests { use super::*; + fn read(text: &str) -> Value { + parse(text).unwrap().value + } + + fn string(text: &str) -> Value { + Value::String(text.to_string()) + } + + fn number(text: &str) -> Value { + Value::Number(text.to_string()) + } + fn error(text: &str) -> JsonError { parse(text).expect_err("an invalid document") } - /// The cursor stays on a character boundary, or the error's own message cuts inside one. - #[test] - fn an_escape_before_an_accent_is_said_where_it_is() { - let failed = error(r#"{"a": "x\é"}"#); + fn items(text: &str) -> Vec { + match read(text) { + Value::Array(items) => items, + other => panic!("{other:?}"), + } + } - assert_eq!(failed.reason, JsonErrorReason::InvalidEscape); + #[test] + fn every_kind_of_value_is_read_with_blanks_around_it() { + for (text, value) in [ + (" \n 42 \t\r", number("42")), + ("\"é\"", string("é")), + ("true", Value::Bool(true)), + ("false", Value::Bool(false)), + ("null", Value::Null), + ("[ ]", Value::Array(Vec::new())), + ("{ }", Value::Object(Vec::new())), + ] { + assert_eq!(read(text), value, "{text}"); + } } + /// In the order they were written, a key said twice twice. #[test] - fn keeps_every_value_and_where_it_sits() { - let root = parse(r#"{"a": [1, "é", true, null], "b": {}}"#).unwrap(); - let Value::Object(members) = &root.value else { + fn members_keep_their_order_and_their_doubles() { + let Value::Object(members) = read(r#"{"b": 1, "a" : [2 , 3] , "b": { "c": 4 }}"#) else { panic!("an object"); }; - assert_eq!(members[0].0, "a"); - let Value::Array(items) = &members[0].1.value else { - panic!("an array"); - }; - assert_eq!(items[0].value, Value::Number("1".into())); - assert_eq!(items[1].value, Value::String("é".into())); - assert_eq!(items[2].value, Value::Bool(true)); - assert_eq!(items[3].value, Value::Null); - assert_eq!(members[0].1.span, Span { start: 6, end: 26 }); - assert_eq!(root.span, Span { start: 0, end: 36 }); + let keys: Vec<&str> = members.iter().map(|(key, _)| key.as_str()).collect(); + assert_eq!(keys, ["b", "a", "b"]); + assert!( + matches!(&members[1].1.value, Value::Array(items) if items[1].value == number("3")) + ); + assert!( + matches!(&members[2].1.value, Value::Object(inner) if inner[0].1.value == number("4")) + ); } + /// `1e3` stays `1e3`, and a number past `f64` loses nothing. #[test] - fn counts_offsets_in_utf16_units() { - let root = parse(r#"["😀", 1]"#).unwrap(); - let Value::Array(items) = root.value else { - panic!("an array"); - }; - - // The emoji is one character, two UTF-16 units and four bytes. - assert_eq!(items[0].span, Span { start: 1, end: 5 }); - assert_eq!(items[1].span, Span { start: 7, end: 8 }); + fn a_number_is_kept_as_written() { + for text in [ + "0", + "-0", + "10", + "-1.50", + "1e3", + "1E+3", + "-1.5e-10", + "123456789012345678901234567890", + ] { + assert_eq!(read(text), number(text)); + } } #[test] - fn decodes_escapes_and_surrogate_pairs() { - let root = parse(r#""a\"b\\c\/\né😀\ud800""#).unwrap(); - - assert_eq!(root.value, Value::String("a\"b\\c/\né😀\u{fffd}".into())); + fn an_escape_is_read_as_its_character() { + for (text, read_as) in [ + (r#""a\"b\\c\/d""#, "a\"b\\c/d"), + (r#""\b\f\n\r\t""#, "\u{8}\u{c}\n\r\t"), + (r#""\u00e9\u00E9""#, "éé"), + (r#""\ud83d\ude00!""#, "😀!"), + ("\"\u{1f600}\"", "😀"), + ] { + assert_eq!(read(text), string(read_as), "{text}"); + } } - /// What followed half a pair was dropped with it. + /// Valid JSON, but no character: what follows is read as any other (#1772). #[test] fn half_a_surrogate_pair_is_one_replacement_and_what_follows_is_read() { - for (text, read) in [ + for (text, read_as) in [ (r#""\ud83d""#, "\u{fffd}"), (r#""\ud83db""#, "\u{fffd}b"), (r#""\ud83d\u0041b""#, "\u{fffd}Ab"), (r#""\ud83d\n""#, "\u{fffd}\n"), - (r#""\ud83d\ud83d\ude00""#, "\u{fffd}\u{1f600}"), + (r#""\ud83d\ud83d\ude00""#, "\u{fffd}😀"), (r#""\ude00\u0041""#, "\u{fffd}A"), ] { - assert_eq!( - parse(text).unwrap().value, - Value::String(read.into()), - "{text}" - ); + assert_eq!(read(text), string(read_as), "{text}"); } } + /// The front's strings count in UTF-16: an emoji is two units, and four bytes. #[test] - fn keeps_a_number_as_written() { - assert_eq!( - parse("-1.5e+10").unwrap().value, - Value::Number("-1.5e+10".into()) - ); + fn a_value_says_where_it_sits_in_utf16_units() { + let text = r#" ["😀", "é", {"a": 1}] "#; + let root = parse(text).unwrap(); + + let spans: Vec<(u32, u32)> = items(text) + .iter() + .map(|item| (item.span.start, item.span.end)) + .collect(); + assert_eq!(root.span, Span { start: 1, end: 22 }); + assert_eq!(spans, [(2, 6), (8, 11), (13, 21)]); } #[test] - fn says_where_a_document_breaks() { - let broken = error("{\n \"a\": 1,,\n}"); - - assert_eq!(broken.reason, JsonErrorReason::UnexpectedCharacter); - assert_eq!((broken.line, broken.column, broken.offset), (2, 10, 11)); + fn what_is_wrong_is_named() { + use JsonErrorReason as Reason; + for (text, reason) in [ + ("", Reason::UnexpectedEnd), + ("[1,", Reason::UnexpectedEnd), + ("[1", Reason::UnexpectedEnd), + ("{", Reason::UnexpectedEnd), + ("{\"a", Reason::UnexpectedEnd), + ("{\"a\"", Reason::UnexpectedEnd), + ("{\"a\":", Reason::UnexpectedEnd), + ("{\"a\":1", Reason::UnexpectedEnd), + ("{\"a\":1,", Reason::UnexpectedEnd), + ("\"\\", Reason::UnexpectedEnd), + ("\"\\u12", Reason::UnexpectedEnd), + ("\"\\ud83d\\u00", Reason::UnexpectedEnd), + ("tru", Reason::UnexpectedEnd), + ("nul!", Reason::UnexpectedCharacter), + ("?", Reason::UnexpectedCharacter), + ("[,]", Reason::UnexpectedCharacter), + ("[1 2]", Reason::UnexpectedCharacter), + ("[1,]", Reason::UnexpectedCharacter), + ("{1: 2}", Reason::UnexpectedCharacter), + ("{\"a\" 1}", Reason::UnexpectedCharacter), + ("{\"a\":1 \"b\":2}", Reason::UnexpectedCharacter), + ("{\"a\":1,}", Reason::UnexpectedCharacter), + ("-", Reason::InvalidNumber), + ("-a", Reason::InvalidNumber), + ("1.", Reason::InvalidNumber), + ("1.e3", Reason::InvalidNumber), + ("1e", Reason::InvalidNumber), + ("1e+", Reason::InvalidNumber), + ("\"\\x\"", Reason::InvalidEscape), + ("\"\\u12G4\"", Reason::InvalidEscape), + ("\"a\nb\"", Reason::ControlCharacter), + ("\"\u{1f}\"", Reason::ControlCharacter), + ("01", Reason::TrailingCharacters), + ("{} {}", Reason::TrailingCharacters), + ("1 // a comment", Reason::TrailingCharacters), + ] { + assert_eq!(error(text).reason, reason, "{text}"); + } } #[test] - fn names_what_went_wrong() { - assert_eq!(error("").reason, JsonErrorReason::UnexpectedEnd); - assert_eq!(error("[1,").reason, JsonErrorReason::UnexpectedEnd); - assert_eq!(error("01").reason, JsonErrorReason::TrailingCharacters); - assert_eq!(error("1.").reason, JsonErrorReason::InvalidNumber); - assert_eq!(error("-").reason, JsonErrorReason::InvalidNumber); - assert_eq!(error("1e").reason, JsonErrorReason::InvalidNumber); - assert_eq!(error(r#""\x""#).reason, JsonErrorReason::InvalidEscape); - assert_eq!(error(r#""\u12G4""#).reason, JsonErrorReason::InvalidEscape); - assert_eq!(error("\"a\nb\"").reason, JsonErrorReason::ControlCharacter); - assert_eq!(error("{} {}").reason, JsonErrorReason::TrailingCharacters); - assert_eq!( - error("{\"a\" 1}").reason, - JsonErrorReason::UnexpectedCharacter - ); - assert_eq!(error("{1: 2}").reason, JsonErrorReason::UnexpectedCharacter); - assert_eq!(error("[1 2]").reason, JsonErrorReason::UnexpectedCharacter); - assert_eq!(error("tru").reason, JsonErrorReason::UnexpectedEnd); - assert_eq!(error("nul!").reason, JsonErrorReason::UnexpectedCharacter); - assert_eq!(error("{\"a\":1").reason, JsonErrorReason::UnexpectedEnd); - assert_eq!(error("{\"a").reason, JsonErrorReason::UnexpectedEnd); - assert_eq!(error("{").reason, JsonErrorReason::UnexpectedEnd); - assert_eq!(error("\"\\").reason, JsonErrorReason::UnexpectedEnd); - assert_eq!(error("\"\\u12").reason, JsonErrorReason::UnexpectedEnd); - assert_eq!(error("?").reason, JsonErrorReason::UnexpectedCharacter); + fn an_error_says_its_line_its_column_and_its_offset() { + for (text, at) in [ + ("{\n \"a\": 1,,\n}", (2, 10, 11)), + ("?", (1, 1, 0)), + ("[\n\n", (3, 1, 3)), + ("[\"😀\" ?]", (1, 7, 6)), + ] { + let broken = error(text); + assert_eq!((broken.line, broken.column, broken.offset), at, "{text}"); + } } + /// The cursor stays on a character boundary, or the error's own message cuts inside one. #[test] - fn refuses_a_nesting_deeper_than_it_can_walk() { - let deep = "[".repeat(10_000); + fn an_escape_before_an_accent_is_said_on_that_accent() { + let failed = error(r#"{"a": "x\é"}"#); - assert_eq!(error(&deep).reason, JsonErrorReason::TooDeep); + assert_eq!(failed.reason, JsonErrorReason::InvalidEscape); + assert_eq!((failed.line, failed.column), (1, 10)); } #[test] - fn reads_a_scalar_document_and_blank_around_it() { + fn a_nesting_deeper_than_can_be_walked_is_refused() { + let nested = |depth: usize| format!("{}{}", "[".repeat(depth), "]".repeat(depth)); + let objects = |depth: usize| format!("{}1{}", "{\"a\":".repeat(depth), "}".repeat(depth)); + + assert!(parse(&nested(MAX_DEPTH + 1)).is_ok()); assert_eq!( - parse(" \n 42 \t").unwrap().value, - Value::Number("42".into()) + error(&nested(MAX_DEPTH + 2)).reason, + JsonErrorReason::TooDeep ); - assert_eq!(parse("[]").unwrap().value, Value::Array(Vec::new())); + assert_eq!(error(&"[".repeat(10_000)).reason, JsonErrorReason::TooDeep); + assert!(parse(&objects(MAX_DEPTH)).is_ok()); + let too_deep = error(&objects(MAX_DEPTH + 1)); + assert_eq!(too_deep.reason, JsonErrorReason::TooDeep); } } diff --git a/crates/engine/src/json/position.rs b/crates/engine/src/json/position.rs index dc96299a9..3d2488e41 100644 --- a/crates/engine/src/json/position.rs +++ b/crates/engine/src/json/position.rs @@ -86,29 +86,79 @@ fn count(value: usize) -> u32 { mod tests { use super::*; - #[test] - fn counts_in_utf16_across_lines_and_wide_characters() { - let positions = Positions::new("é: 1\n🦀: [2]\nz"); + const TEXT: &str = "é: 1\n🦀: [2]\nz"; - assert_eq!(positions.byte_at(2, 3), "é: 1\n🦀: ".len()); - assert_eq!(positions.utf16(positions.byte_at(2, 3)), 9); - assert_eq!(positions.utf16(positions.byte_at(3, 0)), 13); - assert_eq!(positions.byte_at(9, 0), positions.text().len()); + #[test] + fn a_line_and_a_column_of_characters_are_a_byte() { + let positions = Positions::new(TEXT); + + for (line, column, before) in [ + (0, 0, ""), + (1, 0, ""), + (1, 1, "é"), + (2, 0, "é: 1\n"), + (2, 3, "é: 1\n🦀: "), + (3, 1, TEXT), + (2, 99, TEXT), + (9, 0, TEXT), + ] { + assert_eq!( + positions.byte_at(line, column), + before.len(), + "{line}:{column}" + ); + } } + /// The crab is two units, the accent one: whatever their bytes. #[test] - fn places_an_error_by_line_and_column_in_utf16() { - let positions = Positions::new("a: 1\n🦀: :"); - let error = positions.error(JsonErrorReason::Malformed, "a: 1\n🦀: ".len()); + fn a_byte_is_an_offset_in_utf16_units() { + let positions = Positions::new(TEXT); + + for (before, units) in [ + ("", 0), + ("é", 1), + ("é: 1", 4), + ("é: 1\n", 5), + ("é: 1\n🦀", 7), + ("é: 1\n🦀: [2]\n", 13), + (TEXT, 14), + ] { + assert_eq!(positions.utf16(before.len()), units, "{before:?}"); + } + } - assert_eq!((error.line, error.column, error.offset), (2, 5, 9)); + #[test] + fn an_error_says_its_line_and_column_from_one() { + let positions = Positions::new(TEXT); + + for (before, at) in [ + ("", (1, 1, 0)), + ("é: ", (1, 4, 3)), + ("é: 1\n", (2, 1, 5)), + ("é: 1\n🦀: ", (2, 5, 9)), + (TEXT, (3, 2, 14)), + ] { + let error = positions.error(JsonErrorReason::Malformed, before.len()); + assert_eq!((error.line, error.column, error.offset), at, "{before:?}"); + } } #[test] - fn keeps_a_span_inside_the_text_and_on_characters() { + fn a_span_stays_inside_the_text_and_on_its_characters() { let positions = Positions::new("é"); - assert_eq!(positions.span(1, 99), Span { start: 0, end: 1 }); + assert_eq!(positions.span(0, 99), Span { start: 0, end: 1 }); + assert_eq!(positions.span(1, 2), Span { start: 0, end: 1 }); + // An end before its start is that start. assert_eq!(positions.span(2, 0), Span { start: 1, end: 1 }); } + + #[test] + fn an_empty_text_has_one_line_and_no_unit() { + let positions = Positions::new(""); + + assert_eq!((positions.byte_at(1, 0), positions.utf16(5)), (0, 0)); + assert_eq!(positions.error(JsonErrorReason::Malformed, 5).line, 1); + } } diff --git a/crates/engine/src/json/read.rs b/crates/engine/src/json/read.rs index ff883853b..6ac639804 100644 --- a/crates/engine/src/json/read.rs +++ b/crates/engine/src/json/read.rs @@ -51,16 +51,50 @@ pub fn explorable_format(language: Language) -> Option { #[cfg(test)] mod tests { + use super::super::parse::Value; use super::*; #[test] fn only_the_languages_with_a_reader_are_explored() { - assert_eq!( - explorable_format(Language::Yml), - Some(StructureFormat::Yaml) - ); - assert_eq!(explorable_format(Language::Xml), Some(StructureFormat::Xml)); - assert_eq!(explorable_format(Language::Html), None); - assert_eq!(explorable_format(Language::Jsonld), None); + for (language, format) in [ + (Language::Json, Some(StructureFormat::Json)), + (Language::Yml, Some(StructureFormat::Yaml)), + (Language::Toml, Some(StructureFormat::Toml)), + (Language::Xml, Some(StructureFormat::Xml)), + (Language::Html, None), + (Language::Jsonld, None), + (Language::Tex, None), + ] { + assert_eq!(explorable_format(language), format, "{language:?}"); + } + } + + /// Each reader's own text, refused by the three others. + #[test] + fn a_text_is_read_by_the_reader_of_its_format() { + let texts = [ + (StructureFormat::Json, r#"{"a": "b"}"#), + (StructureFormat::Yaml, "a: b"), + (StructureFormat::Toml, "a = \"b\""), + (StructureFormat::Xml, "b"), + ]; + for (format, text) in texts { + let read = read(text, format).unwrap(); + assert!(read.notices.is_empty()); + let Value::Object(members) = read.root.value else { + panic!("{format:?}"); + }; + assert_eq!( + (members[0].0.as_str(), &members[0].1.value), + ("a", &Value::String("b".to_string())) + ); + } + for format in [ + StructureFormat::Json, + StructureFormat::Toml, + StructureFormat::Xml, + ] { + assert!(read("a: b", format).is_err(), "{format:?}"); + } } } diff --git a/crates/engine/src/json/toml.rs b/crates/engine/src/json/toml.rs index c5aea884d..64c741df4 100644 --- a/crates/engine/src/json/toml.rs +++ b/crates/engine/src/json/toml.rs @@ -83,89 +83,73 @@ fn table( #[cfg(test)] mod tests { use super::*; + use crate::json::testing::{array, keys, members, slice}; const CONFIG: &str = "title = \"Réglages\"\nwhen = 1979-05-27T07:32:00Z\nsite.name = \"api\"\n[server]\nport = 8_080 # comment\n[a.b]\nc = 0x1F\n[[products]]\nname = \"hammer\"\n[[products]]\ninline = { x = 1.5, y = [true, false] }\nname = \"nail\"\n"; - fn members(node: &Node) -> &[(String, Node)] { - let Value::Object(members) = &node.value else { - panic!("a table, not {:?}", node.value); - }; - members - } - - fn slice(text: &str, node: &Node) -> String { - let units: Vec = text.encode_utf16().collect(); - String::from_utf16(&units[node.span.start as usize..node.span.end as usize]).unwrap() + fn root(text: &str) -> Node { + read(text).expect("a readable document").root } - fn root() -> Node { - read(CONFIG).expect("a readable document").root + fn value(text: &str) -> Value { + members(&root(text))[0].1.value.clone() } + /// The crate's map is sorted: the text's order is put back. #[test] - fn keeps_the_order_the_tables_and_keys_were_written_in() { - let root = root(); + fn the_tables_and_keys_keep_the_order_they_were_written_in() { + let root = root(CONFIG); assert_eq!( - members(&root) - .iter() - .map(|(key, _)| key.as_str()) - .collect::>(), + keys(&root), ["title", "when", "site", "server", "a", "products"] ); - let Value::Array(products) = &members(&root)[5].1.value else { - panic!("an array of tables"); - }; - assert_eq!( - members(&products[1]) - .iter() - .map(|(key, _)| key.as_str()) - .collect::>(), - ["inline", "name"] - ); + let products = array(&members(&root)[5].1); + assert_eq!(keys(&products[1]), ["inline", "name"]); } + /// A `[table]` on its header, an implicit one on its key. #[test] - fn places_tables_arrays_of_tables_dotted_keys_and_inline_tables_where_they_were_written() { - let root = root(); + fn every_value_is_where_it_was_written() { + let root = root(CONFIG); let top = members(&root); + let products = array(&top[5].1); + assert_eq!(slice(CONFIG, &root), CONFIG); + assert_eq!(slice(CONFIG, &top[0].1), "\"Réglages\""); assert_eq!(slice(CONFIG, &top[2].1), "site"); assert_eq!(slice(CONFIG, &members(&top[2].1)[0].1), "\"api\""); assert_eq!(slice(CONFIG, &top[3].1), "[server]"); assert_eq!(slice(CONFIG, &members(&top[4].1)[0].1), "[a.b]"); - let Value::Array(products) = &top[5].1.value else { - panic!("an array of tables"); - }; assert_eq!(slice(CONFIG, &products[1]), "[[products]]"); - assert_eq!( - slice(CONFIG, &members(&products[1])[0].1), - "{ x = 1.5, y = [true, false] }" - ); - assert_eq!(root.span.start, 0); + let inline = &members(&products[1])[0].1; + assert_eq!(slice(CONFIG, inline), "{ x = 1.5, y = [true, false] }"); + assert_eq!(slice(CONFIG, &members(inline)[1].1), "[true, false]"); } #[test] - fn shows_numbers_and_datetimes_as_written() { - let root = root(); - let top = members(&root); - - assert_eq!( - top[1].1.value, - Value::Datetime("1979-05-27T07:32:00Z".into()) - ); - assert_eq!(members(&top[3].1)[0].1.value, Value::Number("8_080".into())); - assert_eq!( - members(&members(&top[4].1)[0].1)[0].1.value, - Value::Number("0x1F".into()) - ); - assert_eq!(top[0].1.value, Value::String("Réglages".into())); + fn a_value_is_read_by_its_kind_numbers_and_dates_as_written() { + for (text, read) in [ + ("a = 8_080", Value::Number("8_080".to_string())), + ("a = 0x1F", Value::Number("0x1F".to_string())), + ("a = -1.5e3", Value::Number("-1.5e3".to_string())), + ("a = inf", Value::Number("inf".to_string())), + ("a = true", Value::Bool(true)), + ("a = 'l\\'", Value::String("l\\".to_string())), + ("a = \"\"\"\nb\"\"\"", Value::String("b".to_string())), + ("a = 07:32:00", Value::Datetime("07:32:00".to_string())), + ("a = 1979-05-27", Value::Datetime("1979-05-27".to_string())), + ("a = []", Value::Array(Vec::new())), + ("a = {}", Value::Object(Vec::new())), + ] { + assert_eq!(value(text), read, "{text}"); + } } #[test] - fn counts_offsets_in_utf16_over_wide_characters() { + fn offsets_count_in_utf16_over_wide_characters() { let text = "\"🦀\" = \"crabe\"\nnext = 1\n"; - let root = read(text).unwrap().root; + let root = root(text); let top = members(&root); assert_eq!(top[0].0, "🦀"); @@ -174,27 +158,42 @@ mod tests { } #[test] - fn says_where_an_unreadable_document_breaks() { - let error = read("a = 1\nb = \n").expect_err("a key with no value"); - - assert_eq!(error.reason, JsonErrorReason::Malformed); - assert_eq!(error.line, 2); - assert!(error.column >= 4); + fn an_empty_document_is_an_empty_table() { + assert_eq!(root("").value, Value::Object(Vec::new())); + assert_eq!(root("# a comment\n").value, Value::Object(Vec::new())); } #[test] - fn refuses_a_nesting_deeper_than_it_can_walk() { - let deep = format!("a = {}1{}", "[".repeat(300), "]".repeat(300)); - - let error = read(&deep).expect_err("too deep"); - assert!(matches!( - error.reason, - JsonErrorReason::TooDeep | JsonErrorReason::Malformed - )); + fn an_unreadable_document_says_where_it_breaks() { + for (text, line) in [("a = 1\nb = \n", 2), ("a = 1\na = 2", 2), ("\n\n[a", 3)] { + let error = read(text).expect_err(text); + assert_eq!( + (error.reason, error.line), + (JsonErrorReason::Malformed, line), + "{text}" + ); + } } + /// The crate bounds each of a key, a header and a bracket: together they go past it. #[test] - fn reads_an_empty_document_as_an_empty_table() { - assert_eq!(read("").unwrap().root.value, Value::Object(Vec::new())); + fn a_nesting_deeper_than_can_be_walked_is_refused() { + let path = |name: &str| vec![name; 79].join("."); + let nested = |brackets: usize, inner: &str| { + let (open, close) = ("[".repeat(brackets), "]".repeat(brackets)); + format!("[{}]\n{} = {open}{inner}{close}", path("a"), path("b")) + }; + + assert!(read(&nested(79, "1")).is_ok()); + let too_deep = nested(39, &format!("{{ {} = 1 }}", path("c"))); + assert_eq!( + read(&too_deep).expect_err("too deep").reason, + JsonErrorReason::TooDeep + ); + let brackets = format!("a = {}1{}", "[".repeat(300), "]".repeat(300)); + assert_eq!( + read(&brackets).expect_err("too deep").reason, + JsonErrorReason::Malformed + ); } } diff --git a/crates/engine/src/json/xml.rs b/crates/engine/src/json/xml.rs index f86e326aa..b0c17e61c 100644 --- a/crates/engine/src/json/xml.rs +++ b/crates/engine/src/json/xml.rs @@ -316,129 +316,186 @@ pub(crate) fn to_value(node: &Node) -> serde_json::Value { #[cfg(test)] mod tests { use super::*; + use crate::json::testing::{array, keys, members, slice}; const ORDER: &str = "\n\n\n\n Pro · mensuel\n Stockage\n payée & vite livrée\n \n \n\n"; - fn members(node: &Node) -> &[(String, Node)] { - let Value::Object(members) = &node.value else { - panic!("an object, not {:?}", node.value); - }; - members + fn root(text: &str) -> Node { + read(text).expect("a readable document").root } - fn slice(text: &str, node: &Node) -> String { - let units: Vec = text.encode_utf16().collect(); - String::from_utf16(&units[node.span.start as usize..node.span.end as usize]).unwrap() + /// The one root of a document. + fn top(text: &str) -> Node { + members(&root(text))[0].1.clone() } - fn order() -> Node { - let root = document(ORDER).ok().expect("a readable document"); - members(&root)[0].1.clone() + fn json(text: &str) -> serde_json::Value { + to_value(&root(text)) } #[test] - fn follows_the_converters_convention_prefixes_included() { - let root = document(ORDER).ok().unwrap(); - assert_eq!(members(&root)[0].0, "shop:order"); + fn a_document_is_an_object_of_its_one_root_prefix_included() { + let root = root(ORDER); + + assert_eq!(keys(&root), ["shop:order"]); + assert_eq!(slice(ORDER, &root), ORDER); + let expected = ["@xmlns:shop", "@id", "line", "note", "raw", "empty"]; + assert_eq!(keys(&members(&root)[0].1), expected); + } + + /// What the converter and the diff read too. + #[test] + fn an_element_reads_by_what_it_holds() { + for (text, read) in [ + ("", serde_json::json!(null)), + ("", serde_json::json!(null)), + (" \n ", serde_json::json!(null)), + ("x", serde_json::json!("x")), + (" x y ", serde_json::json!("x y")), + ("", serde_json::json!({ "@x": "1" })), + ( + "t", + serde_json::json!({ "@x": "1", "#text": "t" }), + ), + ("1", serde_json::json!({ "b": "1" })), + ( + "tu", + serde_json::json!({ "b": null, "#text": "tu" }), + ), + ( + "123", + serde_json::json!({ "b": ["1", "2", "3"], "c": null }), + ), + ("", serde_json::json!({ "b": "" })), + ("x ]]>y", serde_json::json!("x y")), + ("x", serde_json::json!("x")), + ] { + assert_eq!(json(text), serde_json::json!({ "a": read }), "{text}"); + } + } + + #[test] + fn references_are_resolved_in_a_text_and_in_an_attribute() { + let read = json("&<>"'😀A"); - let order = order(); - assert_eq!( - members(&order) - .iter() - .map(|(key, _)| key.as_str()) - .collect::>(), - ["@xmlns:shop", "@id", "line", "note", "raw", "empty"] - ); - let Value::Array(lines) = &members(&order)[2].1.value else { - panic!("repeated siblings as a list"); - }; - assert_eq!(members(&lines[1])[1].0, "#text"); assert_eq!( - members(&lines[1])[1].1.value, - Value::String("Stockage".into()) + read, + serde_json::json!({ "a": { "@k": "1 < 2 é", "#text": "&<>\"'😀A" } }) ); - assert_eq!(members(&order)[5].1.value, Value::Null); } #[test] - fn keeps_mixed_content_and_cdata_as_text() { - let order = order(); + fn mixed_content_keeps_its_text_beside_its_children() { + let order = top(ORDER); let note = members(&members(&order)[3].1); - assert_eq!(note[0].0, "b"); - assert_eq!(note[1].0, "#text"); - assert_eq!(note[1].1.value, Value::String("payée & livrée".into())); - assert_eq!(members(&order)[4].1.value, Value::String("a < b".into())); + assert_eq!((note[0].0.as_str(), note[1].0.as_str()), ("b", "#text")); + assert_eq!( + note[1].1.value, + Value::String("payée & livrée".to_string()) + ); } + /// A text-only element on its text, an attribute on its value, a list from its first to its + /// last. #[test] - fn places_each_value_where_it_was_written() { - let order = order(); + fn every_value_is_where_it_was_written() { + let order = top(ORDER); let top = members(&order); + let lines = array(&top[2].1); assert_eq!(slice(ORDER, &top[1].1), "42"); - let Value::Array(lines) = &top[2].1.value else { - panic!("a list"); - }; assert_eq!( slice(ORDER, &lines[0]), "Pro · mensuel" ); assert_eq!(slice(ORDER, &members(&lines[0])[1].1), "Pro · mensuel"); + let both = "Pro · mensuel\n Stockage"; + assert_eq!(slice(ORDER, &top[2].1), both); assert_eq!( - slice(ORDER, &top[2].1), - "Pro · mensuel\n Stockage" + slice(ORDER, &members(&top[3].1)[1].1), + "payée & vite livrée" ); assert_eq!(slice(ORDER, &top[4].1), "a < b"); assert_eq!(slice(ORDER, &top[5].1), ""); } #[test] - fn counts_offsets_in_utf16_over_wide_characters() { + fn a_text_with_blanks_around_it_is_placed_without_them() { + let text = "\n x & y w"; + let a = top(text); + let inner = members(&a); + + assert_eq!(slice(text, &inner[0].1), "x & y"); + assert_eq!(slice(text, &members(&inner[1].1)[0].1), "eé"); + assert_eq!(slice(text, &members(&inner[1].1)[1].1), "z]]>w"); + } + + #[test] + fn offsets_count_in_utf16_over_wide_characters() { let text = "🦀x"; - let root = document(text).ok().unwrap(); - let r = members(&members(&root)[0].1); + let r = top(text); + let inner = members(&r); - assert_eq!((r[0].1.span.start, r[0].1.span.end), (6, 8)); - assert_eq!(slice(text, &members(&r[1].1)[0].1), "é"); + assert_eq!((inner[0].1.span.start, inner[0].1.span.end), (6, 8)); + assert_eq!(slice(text, &members(&inner[1].1)[0].1), "é"); } #[test] - fn says_where_an_unreadable_document_breaks() { - let error = read("\n ").expect_err("a mismatched end tag"); - assert_eq!(error.reason, JsonErrorReason::Malformed); - assert_eq!(error.line, 2); - - assert!(read("").is_err()); - assert!(read("text").is_err()); - assert!(read(" ").is_err()); - assert_eq!( - read("").expect_err("unclosed").reason, - JsonErrorReason::Malformed - ); + fn an_unreadable_document_says_where_it_breaks() { + for (text, line) in [ + ("\n ", 2), + ("\n", 2), + ("\n", 2), + ("text", 1), + ("\ntext", 1), + ("\n&", 2), + ("", 1), + ("", 1), + (" ", 1), + ("&#xZZ;", 1), + ("", 1), + ("", 1), + ("", 1), + ("", 1), + ] { + let error = read(text).expect_err(text); + assert_eq!( + (error.reason, error.line), + (JsonErrorReason::Malformed, line), + "{text}" + ); + } } #[test] - fn refuses_a_nesting_deeper_than_it_can_walk() { - let deep = format!("{}{}", "".repeat(300), "".repeat(300)); + fn a_nesting_deeper_than_can_be_walked_is_refused() { + let nested = |depth: usize| format!("{}{}", "".repeat(depth), "".repeat(depth)); + assert!(read(&nested(MAX_DEPTH)).is_ok()); assert_eq!( - read(&deep).expect_err("too deep").reason, + read(&nested(MAX_DEPTH + 1)).expect_err("too deep").reason, JsonErrorReason::TooDeep ); } + /// A tree of another format goes through the same conversion. #[test] - fn hands_the_converter_the_same_value() { - let value = to_value( - &document("23") - .ok() - .unwrap(), - ); + fn a_number_a_date_and_a_boolean_are_handed_as_values() { + let node = |value: Value| Node { + value, + span: Span { start: 0, end: 0 }, + }; + let list = Value::Array(vec![ + node(Value::Number("1".to_string())), + node(Value::Datetime("1979-05-27".to_string())), + node(Value::Bool(true)), + node(Value::Null), + ]); assert_eq!( - value, - serde_json::json!({ "a": { "@x": "1", "b": ["2", "3"], "c": null } }) + to_value(&node(list)), + serde_json::json!(["1", "1979-05-27", true, null]) ); } } diff --git a/crates/engine/src/json/yaml.rs b/crates/engine/src/json/yaml.rs index bb00c4cd0..b151f3a87 100644 --- a/crates/engine/src/json/yaml.rs +++ b/crates/engine/src/json/yaml.rs @@ -349,182 +349,223 @@ fn indentation(line: &str) -> usize { #[cfg(test)] mod tests { use super::*; + use crate::json::testing::{array, keys, members, slice}; - fn read_ok(text: &str) -> Read { - read(text).expect("a readable document") + fn root(text: &str) -> Node { + read(text).expect("a readable document").root } - fn members(node: &Node) -> &[(String, Node)] { - let Value::Object(members) = &node.value else { - panic!("a mapping, not {:?}", node.value); - }; - members - } - - fn slice(text: &str, node: &Node) -> String { - let units: Vec = text.encode_utf16().collect(); - String::from_utf16(&units[node.span.start as usize..node.span.end as usize]).unwrap() + fn refused(text: &str) -> JsonErrorReason { + read(text).expect_err("an unreadable document").reason } #[test] - fn reads_nested_maps_and_sequences_in_their_order() { - let text = "name: api\nports:\n - 80\n - 443\nenv:\n debug: true\n level: ~\n"; - let root = read_ok(text).root; + fn maps_and_sequences_are_read_in_their_order() { + let root = root("name: api\nports:\n - 80\n - 443\nenv:\n debug: true\n level: ~\n"); let top = members(&root); + assert_eq!(keys(&root), ["name", "ports", "env"]); + assert_eq!(top[0].1.value, Value::String("api".to_string())); + assert_eq!(array(&top[1].1)[1].value, Value::Number("443".to_string())); + let env = members(&top[2].1); assert_eq!( - top.iter().map(|(key, _)| key.as_str()).collect::>(), - ["name", "ports", "env"] + (&env[0].1.value, &env[1].1.value), + (&Value::Bool(true), &Value::Null) ); - assert_eq!(top[0].1.value, Value::String("api".into())); - let Value::Array(ports) = &top[1].1.value else { - panic!("a sequence"); - }; - assert_eq!(ports[1].value, Value::Number("443".into())); - let env = members(&top[2].1); - assert_eq!(env[0].1.value, Value::Bool(true)); - assert_eq!(env[1].1.value, Value::Null); } + /// The core schema: quoted, or tagged as a string, it stays one. #[test] - fn keeps_every_value_where_it_was_written() { - let text = "a: 'it''s'\nb: \"x\\\"y\" # comment\nc: plain text # note\nd: [1, {e: 2}]\nf: |\n line one\n line two\ng: 3\n"; - let root = read_ok(text).root; - let top = members(&root); - - assert_eq!(slice(text, &top[0].1), "'it''s'"); - assert_eq!(slice(text, &top[1].1), "\"x\\\"y\""); - assert_eq!(slice(text, &top[2].1), "plain text"); - assert_eq!(slice(text, &top[3].1), "[1, {e: 2}]"); - assert_eq!(slice(text, &top[4].1), "|\n line one\n line two"); - assert_eq!(slice(text, &top[5].1), "3"); + fn a_plain_scalar_is_typed_and_a_quoted_one_stays_a_string() { + let string = |text: &str| Value::String(text.to_string()); + let number = |text: &str| Value::Number(text.to_string()); + for (text, value) in [ + ("12", number("12")), + ("-1.5e3", number("-1.5e3")), + ("0x1F", number("0x1F")), + ("true", Value::Bool(true)), + ("FALSE", Value::Bool(false)), + ("~", Value::Null), + ("null", Value::Null), + ("yes", string("yes")), + ("a b", string("a b")), + ("'12'", string("12")), + ("\"true\"", string("true")), + ("!!str 12", string("12")), + ] { + assert_eq!( + members(&root(&format!("a: {text}\n")))[0].1.value, + value, + "{text}" + ); + } + assert_eq!(members(&root("a: |\n 12\n"))[0].1.value, string("12\n")); + assert_eq!(members(&root("a:\n"))[0].1.value, Value::Null); } + /// The parser marks only where a node starts: its end is read from the text, by its style. #[test] - fn ends_a_block_collection_on_its_last_value_not_on_a_comment_after_it() { - let text = "outer:\n inner: 1\n # trailing\nnext: 2\n"; - let root = read_ok(text).root; - - assert_eq!(slice(text, &members(&root)[0].1), "inner: 1"); + fn every_value_is_where_it_was_written() { + for written in [ + "'it''s'", + "'open and ''closed'''", + "\"x\\\"y\"", + "plain text", + "3", + "[1, {e: 2}]", + "{a: [1]}", + "|\n line one\n\n line two", + ">\n folded", + "|-\n kept", + ] { + let text = format!("a: {written} # note\nb: 1\n").replace("\n ", "\n "); + let text = if written.contains('\n') { + format!("a: {written}\nb: 1\n") + } else { + text + }; + let root = root(&text); + assert_eq!(slice(&text, &members(&root)[0].1), written, "{text}"); + } } #[test] - fn counts_offsets_in_utf16_over_wide_characters() { - let text = "🦀: \"crabe\"\né: [é]\n"; - let root = read_ok(text).root; - let top = members(&root); + fn a_plain_scalar_over_several_lines_is_placed_on_its_first() { + let text = "a: one\n two\nb: 1\n"; + let root = root(text); - assert_eq!((top[0].1.span.start, top[0].1.span.end), (4, 11)); - assert_eq!(top[1].0, "é"); - assert_eq!(slice(text, &top[1].1), "[é]"); + assert_eq!( + members(&root)[0].1.value, + Value::String("one two".to_string()) + ); + assert_eq!(slice(text, &members(&root)[0].1), "one"); } #[test] - fn reads_an_alias_as_what_it_names_and_keeps_a_merge_key_as_read() { - let text = "base: &base\n retries: 3\nservice:\n <<: *base\n name: api\n"; - let root = read_ok(text).root; - let service = members(&members(&root)[1].1); + fn a_block_ending_the_document_is_placed_to_its_last_line() { + let text = "a:\n b: |\n one\n two"; + let root = root(text); - assert_eq!(service[0].0, "<<"); - assert_eq!(members(&service[0].1)[0].0, "retries"); - // The alias points at what it names: "show in code" goes to the anchor. - assert_eq!(slice(text, &service[0].1), "retries: 3"); - assert_eq!(slice(text, &members(&root)[1].1), "<<: *base\n name: api"); + let b = &members(&members(&root)[0].1)[0].1; + assert_eq!(slice(text, b), "|\n one\n two"); } #[test] - fn explores_the_first_document_of_a_stream_and_says_so() { - let read = read_ok("a: 1\n---\nb: 2\n"); + fn a_block_collection_ends_on_its_last_value_not_on_a_comment_after_it() { + let text = "outer:\n inner: 1\n # trailing\nlist:\n - a\n - b\n\nnext: 2\n"; + let root = root(text); + let top = members(&root); - assert_eq!(members(&read.root)[0].0, "a"); - assert_eq!(read.notices, [JsonNotice::FirstDocumentOnly]); - assert!(read_ok("a: 1\n").notices.is_empty()); + assert_eq!(slice(text, &top[0].1), "inner: 1"); + assert_eq!(slice(text, &top[1].1), "- a\n - b"); } #[test] - fn types_plain_scalars_and_leaves_quoted_ones_strings() { - let root = read_ok("a: 0x1F\nb: '12'\nc: !!str 12\nd: 1.5e3\ne: yes\nf: FALSE\n").root; - let values: Vec<&Value> = members(&root).iter().map(|(_, node)| &node.value).collect(); + fn offsets_count_in_utf16_over_wide_characters() { + let text = "🦀: \"crabe\"\né: [é]\n"; + let root = root(text); + let top = members(&root); + assert_eq!((top[0].1.span.start, top[0].1.span.end), (4, 11)); assert_eq!( - values, - [ - &Value::Number("0x1F".into()), - &Value::String("12".into()), - &Value::String("12".into()), - &Value::Number("1.5e3".into()), - &Value::String("yes".into()), - &Value::Bool(false), - ] + (top[1].0.as_str(), slice(text, &top[1].1)), + ("é", "[é]".to_string()) ); } + /// "Show in code" goes to the anchor; a merge key is kept as read. #[test] - fn names_a_collection_used_as_a_key_by_its_text() { - let root = read_ok("? [a, b]\n: pair\n").root; + fn an_alias_is_read_as_what_it_names_and_placed_there() { + let text = "base: &base\n retries: 3\nservice:\n <<: *base\n name: api\n"; + let root = root(text); + let service = &members(&root)[1].1; + let inner = members(service); + + assert_eq!(keys(service), ["<<", "name"]); + assert_eq!(keys(&inner[0].1), ["retries"]); + assert_eq!(slice(text, &inner[0].1), "retries: 3"); + assert_eq!(slice(text, service), "<<: *base\n name: api"); + } - assert_eq!(members(&root)[0].0, "[a, b]"); + #[test] + fn an_alias_is_read_in_a_list_and_as_a_key() { + let text = "a: &a x\nlist: [*a, {k: *a}]\n*a : y\n"; + let root = root(text); + let list = array(&members(&root)[1].1); + + assert_eq!(list[0].value, Value::String("x".to_string())); + assert_eq!(members(&list[1])[0].1.value, Value::String("x".to_string())); + assert_eq!(slice(text, &members(&root)[1].1), "[*a, {k: *a}]"); + assert_eq!(members(&root)[2].0, "*a"); } #[test] - fn reads_an_empty_document_as_null() { - assert_eq!(read_ok("").root.value, Value::Null); - assert_eq!(read_ok("# only a comment\n").root.value, Value::Null); + fn a_collection_used_as_a_key_is_named_by_its_text_on_one_line() { + assert_eq!(members(&root("? [a,\n b]\n: pair\n"))[0].0, "[a, b]"); } #[test] - fn says_where_an_unreadable_document_breaks() { - let error = read("a: 1\nb: [1, 2\n").expect_err("an unclosed sequence"); + fn the_first_document_of_a_stream_is_read_and_the_rest_said() { + let several = read("a: 1\n---\nb: 2\n").unwrap(); + + assert_eq!(keys(&several.root), ["a"]); + assert_eq!(several.notices, [JsonNotice::FirstDocumentOnly]); + assert!(read("---\na: 1\n...\n").unwrap().notices.is_empty()); + } - assert_eq!(error.reason, JsonErrorReason::Malformed); - assert!(error.line >= 2 && error.column >= 1); + #[test] + fn an_empty_document_is_null() { + for text in ["", "# only a comment\n", "---\n"] { + assert_eq!(root(text).value, Value::Null, "{text:?}"); + } + } - let error = read("ok: 1\n🦀: \"open\n").expect_err("an unclosed string"); - assert_eq!(error.reason, JsonErrorReason::Malformed); - assert!(error.line >= 2); + #[test] + fn an_unreadable_document_says_where_it_breaks() { + for text in [ + "a: 1\nb: [1, 2\n", + "ok: 1\n🦀: \"open\n", + "a: 1\n b: 2\n", + "a: 1\nb: *nowhere\n", + ] { + let error = read(text).expect_err(text); + assert_eq!(error.reason, JsonErrorReason::Malformed, "{text}"); + assert!(error.line >= 2 && error.column >= 1, "{text}: {error:?}"); + } } #[test] - fn refuses_a_nesting_deeper_than_it_can_walk() { + fn a_nesting_deeper_than_can_be_walked_is_refused() { let flow = format!("{}1{}", "[".repeat(300), "]".repeat(300)); - let block = (0..300) - .map(|level| format!("{}a:", " ".repeat(level))) - .collect::>() - .join("\n"); + let block = |depth: usize| { + let lines: Vec = (0..depth) + .map(|level| format!("{}a:", " ".repeat(level))) + .collect(); + lines.join("\n") + }; - assert_eq!( - read(&flow).expect_err("too deep").reason, - JsonErrorReason::TooDeep - ); - assert_eq!( - read(&block).expect_err("too deep").reason, - JsonErrorReason::TooDeep - ); + assert_eq!(refused(&flow), JsonErrorReason::TooDeep); + assert!(read(&block(MAX_DEPTH)).is_ok()); + assert_eq!(refused(&block(MAX_DEPTH + 1)), JsonErrorReason::TooDeep); } #[test] - fn stops_a_document_of_aliases_to_aliases_before_it_multiplies() { - let mut text = String::from("a0: &a0 [x, x, x, x, x, x, x, x, x, x]\n"); + fn a_document_of_aliases_to_aliases_stops_before_it_multiplies() { + let mut lines = vec!["a0: &a0 [x, x, x, x, x, x, x, x, x, x]".to_string()]; for level in 1..8 { - let previous = level - 1; - let aliases = vec![format!("*a{previous}"); 10].join(", "); - text.push_str( - &[ - "a", - &level.to_string(), - ": &a", - &level.to_string(), - " [", - &aliases, - "]\n", - ] - .concat(), - ); + let aliases = vec![format!("*a{}", level - 1); 10].join(", "); + lines.push(format!("a{level}: &a{level} [{aliases}]")); } - assert_eq!( - read(&text).expect_err("too large").reason, - JsonErrorReason::TooLarge - ); + assert_eq!(refused(&lines.join("\n")), JsonErrorReason::TooLarge); + } + + #[test] + fn a_document_of_too_many_values_stops_too() { + // The list itself is a value. + let list = |items: usize| "- x\n".repeat(items); + + assert!(read(&list(MAX_VALUES - 1)).is_ok()); + assert_eq!(refused(&list(MAX_VALUES)), JsonErrorReason::TooLarge); } } From 6b250a88d877cedfb660a8670e1a9725ad517637 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 08:36:49 +0100 Subject: [PATCH 62/95] Drawings: unit tests rewritten for the editor, geometry and scene (#1794) Co-authored-by: Claude Opus 5.5 --- crates/drawing/src/edit/tests.rs | 758 ++++++++++++++++++++++++++---- crates/drawing/src/geometry.rs | 157 ++++++- crates/drawing/src/marks.rs | 52 ++ crates/drawing/src/scene.rs | 4 +- crates/drawing/src/scene/tests.rs | 98 ++++ crates/drawing/src/text/tests.rs | 13 + 6 files changed, 977 insertions(+), 105 deletions(-) diff --git a/crates/drawing/src/edit/tests.rs b/crates/drawing/src/edit/tests.rs index bae19af09..9e00068be 100644 --- a/crates/drawing/src/edit/tests.rs +++ b/crates/drawing/src/edit/tests.rs @@ -91,11 +91,24 @@ fn an_arrow_started_and_ended_on_shapes_stays_on_their_edges() { assert_eq!(arrow.to(), object(&editor, 1).id()); assert_eq!(arrow.ends(), Some([201.0, 130.0, 399.0, 130.0])); assert_eq!(arrow.path().last(), Some(&PathCommand::Close)); +} - drag(&mut editor, at(150.0, 130.0), at(150.0, 130.0)); - drag(&mut editor, at(150.0, 130.0), at(150.0, 330.0)); - let moved = object(&editor, 2).ends().unwrap(); - assert!(moved[1] > 130.0, "the arrow followed: {moved:?}"); +#[test] +fn an_arrow_follows_a_shape_moved_at_either_of_its_ends() { + for (pressed, moved) in [(50.0, 1), (350.0, 3)] { + let mut editor = joined(); + drag(&mut editor, at(pressed, 10.0), at(pressed, 210.0)); + assert!(ends(&editor)[moved] > 150.0, "{:?}", ends(&editor)); + } +} + +#[test] +fn an_arrow_follows_while_its_shape_is_still_held() { + let mut editor = joined(); + editor.press(at(350.0, 10.0), false); + editor.drag(at(350.0, 110.0)); + + assert!(ends(&editor)[3] > 100.0, "{:?}", ends(&editor)); } #[test] @@ -112,73 +125,158 @@ fn an_arrow_on_nothing_ends_where_it_was_let_go() { } #[test] -fn an_arrow_cannot_end_on_the_shape_it_started_on_nor_on_a_text() { +fn an_arrow_cannot_end_on_the_shape_it_started_on() { let mut editor = with_a_rectangle(); editor.set_tool(Tool::Arrow); drag(&mut editor, at(120.0, 130.0), at(180.0, 130.0)); + assert_eq!(object(&editor, 1).from(), object(&editor, 0).id()); assert_eq!(object(&editor, 1).to(), None); +} - editor.set_tool(Tool::Text); - editor.press(at(300.0, 300.0), false); - editor.set_text("words"); - editor.leave_text(); - editor.set_tool(Tool::Arrow); - drag(&mut editor, at(0.0, 0.0), at(350.0, 300.0)); - assert_eq!(object(&editor, 3).to(), None); +#[test] +fn a_text_an_arrow_and_a_shape_without_a_name_hold_no_arrow() { + let body = r#"{"scene":{"objects":[ + {"type":"Textbox","id":"a","left":100,"top":100,"width":100,"height":40,"text":"words"}, + {"type":"Path","id":"b","ends":[0,0,20,0],"left":300,"top":100,"width":100,"height":40,"path":[["M",0,0],["L",20,0]]}, + {"type":"Rect","left":500,"top":100,"width":100,"height":40} + ]}}"#; + for x in [100.0, 300.0, 500.0] { + let mut editor = Editor::open(body, Arc::new(fonts())); + editor.set_tool(Tool::Arrow); + drag(&mut editor, at(0.0, 400.0), at(x, 100.0)); + assert_eq!(object(&editor, 3).to(), None, "{x}"); + } } #[test] fn a_shape_removed_lets_its_arrows_go() { - let mut editor = with_a_rectangle(); - editor.set_tool(Tool::Arrow); - drag(&mut editor, at(150.0, 130.0), at(400.0, 130.0)); - editor.press(at(150.0, 130.0), false); - editor.release(at(150.0, 130.0)); + for (pressed, kept) in [(50.0, 300.0), (350.0, 0.0)] { + let mut editor = joined(); + drag(&mut editor, at(pressed, 10.0), at(pressed, 10.0)); + let drawn = ends(&editor); + + assert!(editor.remove_selection()); + + let arrow = object(&editor, 1); + assert_eq!(editor.shapes(), 2); + assert_eq!([arrow.from(), arrow.to()].into_iter().flatten().count(), 1); + assert_eq!(object(&editor, 0).centre().x, kept + 50.0); + assert_eq!(arrow.ends(), Some(drawn), "it stays where it was"); + } +} + +#[test] +fn several_removed_at_once_are_one_step_of_the_history() { + let mut editor = joined(); + editor.press(at(50.0, 10.0), true); + editor.release(at(50.0, 10.0)); + assert_eq!(editor.selected(), [2, 0]); assert!(editor.remove_selection()); + assert_eq!(object(&editor, 0).centre(), at(350.0, 30.0)); + assert_eq!((editor.shapes(), editor.selected().len()), (1, 0)); + editor.undo(); + assert_eq!(editor.shapes(), 3); +} - assert_eq!(editor.shapes(), 1); - assert_eq!(object(&editor, 0).from(), None); +#[test] +fn with_nothing_selected_or_a_text_typed_into_nothing_is_removed() { + let mut editor = with_a_rectangle(); + editor.deselect(); + assert!(!editor.remove_selection()); + + editor.set_tool(Tool::Text); + editor.press(at(300.0, 300.0), false); assert!(!editor.remove_selection()); + assert_eq!(editor.shapes(), 2); } -#[test] -fn the_pen_leaves_a_smoothed_line_unfilled_and_a_click_leaves_none() { +fn with_the_pen(points: &[Point]) -> Editor { let mut editor = editor(); editor.set_tool(Tool::Pen); - editor.press(at(0.0, 0.0), false); - assert!(editor.pen_line().is_some()); - for step in 1..10 { - editor.drag(at(f64::from(step) * 5.0, f64::from(step % 2) * 4.0)); + editor.press(points[0], false); + for point in &points[1..] { + editor.drag(*point); } - editor.release(at(50.0, 0.0)); + editor.release(points[points.len() - 1]); + editor +} + +#[test] +fn the_pen_leaves_a_smoothed_line_round_and_unfilled() { + let points: Vec = (0..10) + .map(|step| at(f64::from(step) * 5.0, f64::from(step % 2) * 4.0)) + .collect(); + let editor = with_the_pen(&points); let line = object(&editor, 0); assert_eq!(line.kind(), Kind::Path); - assert_eq!(line.line_cap(), "round"); + assert_eq!((line.line_cap(), line.line_join()), ("round", "round")); assert_eq!(line.stroke_width(), 2.5); assert!(matches!(line.path()[1], PathCommand::Quad(..))); + assert!(editor.body().contains(r#""fill":null"#)); +} + +#[test] +fn the_pen_stays_in_hand_and_each_line_is_a_step_of_the_history() { + let mut editor = with_the_pen(&[at(0.0, 0.0), at(30.0, 0.0), at(60.0, 20.0)]); + assert_eq!(editor.tool(), Tool::Pen); + assert!(editor.can_undo() && editor.take_unsaved()); +} - drag(&mut editor, at(9.0, 9.0), at(9.0, 9.0)); - assert_eq!(editor.shapes(), 1); +#[test] +fn a_click_of_the_pen_leaves_nothing() { + let mut editor = with_the_pen(&[at(9.0, 9.0), at(9.0, 9.0)]); + + assert_eq!(editor.shapes(), 0); + assert!(!editor.take_unsaved()); } #[test] -fn a_text_is_typed_where_clicked_and_left_empty_it_goes() { +fn the_pen_s_line_is_shown_while_it_is_drawn() { + let mut editor = editor(); + assert_eq!(editor.pen_line(), None); + editor.set_tool(Tool::Pen); + editor.press(at(0.0, 0.0), false); + editor.drag(at(5.0, 0.0)); + + assert_eq!(editor.pen_line(), Some(&[at(0.0, 0.0), at(5.0, 0.0)][..])); + editor.release(at(5.0, 0.0)); + assert_eq!(editor.pen_line(), None); +} + +#[test] +fn a_text_is_typed_where_clicked_its_left_edge_there() { let mut editor = editor(); editor.set_tool(Tool::Text); editor.press(at(10.0, 20.0), false); + let text = object(&editor, 0); assert_eq!(editor.tool(), Tool::Select); - assert!(editor.editing().is_some()); - assert_eq!(editor.frame(), None); - assert_eq!(object(&editor, 0).centre(), at(100.0, 20.0)); + assert_eq!(text.centre(), at(100.0, 20.0)); + assert_eq!( + (text.text(), text.font_size(), text.stroke_width()), + (Some(""), 18.0, 0.0) + ); + assert_eq!(text.font_family(), "Inter Variable, sans-serif"); + assert!(editor.editing().is_some_and(|(index, _)| index == 0)); + assert_eq!(editor.frame(), None, "typed into, it has no handles"); +} - editor.leave_text(); - assert_eq!(editor.shapes(), 0); - assert!(!editor.can_undo()); +#[test] +fn a_text_left_empty_goes_and_the_history_never_knew_it() { + for typed in ["", " \n"] { + let mut editor = editor(); + editor.set_tool(Tool::Text); + editor.press(at(10.0, 20.0), false); + editor.set_text(typed); + + editor.leave_text(); + assert_eq!((editor.shapes(), editor.selected().len()), (0, 0)); + assert!(!editor.can_undo() && !editor.take_unsaved()); + } } #[test] @@ -201,23 +299,58 @@ fn a_text_emptied_is_saved_and_undone_like_a_deletion() { assert_eq!(object(&editor, 0).text(), Some("words")); } -#[test] -fn a_text_grows_with_its_lines_and_a_second_click_types_in_it_again() { +fn with_a_text(text: &str) -> Editor { let mut editor = editor(); editor.set_tool(Tool::Text); editor.press(at(10.0, 20.0), false); - editor.set_text("one\ntwo"); + editor.set_text(text); editor.leave_text(); + editor +} - assert_eq!(object(&editor, 0).height(), 43.93); - assert!(editor.can_undo()); +#[test] +fn a_text_grows_with_its_lines() { + assert_eq!(object(&with_a_text("one"), 0).height(), 20.34); + assert_eq!(object(&with_a_text("one\ntwo"), 0).height(), 43.93); +} +#[test] +fn a_text_left_is_a_step_of_the_history() { + let mut editor = with_a_text("one"); + + assert!(editor.editing().is_none()); + assert!(editor.can_undo() && editor.take_unsaved()); +} + +#[test] +fn a_click_on_a_text_already_selected_types_in_it() { + let mut editor = with_a_text("one"); let inside = object(&editor, 0).centre(); - editor.press(inside, false); - editor.release(inside); + + editor.deselect(); + drag(&mut editor, inside, inside); + assert!(editor.editing().is_none(), "the first click selects it"); + drag(&mut editor, inside, inside); assert!(editor.editing().is_some()); } +#[test] +fn a_click_on_a_shape_selected_types_nothing() { + let mut editor = with_a_rectangle(); + drag(&mut editor, at(150.0, 130.0), at(150.0, 130.0)); + + assert!(editor.editing().is_none()); +} + +#[test] +fn nothing_is_typed_out_of_a_text() { + let mut editor = with_a_text("one"); + editor.set_text("two"); + editor.leave_text(); + + assert_eq!(object(&editor, 0).text(), Some("one")); +} + #[test] fn a_click_selects_the_topmost_and_on_the_paper_drops_the_selection() { let mut editor = with_a_rectangle(); @@ -234,39 +367,121 @@ fn a_click_selects_the_topmost_and_on_the_paper_drops_the_selection() { assert!(editor.selected().is_empty()); } -#[test] -fn shift_adds_and_takes_away_and_a_marquee_selects_what_it_touches() { +fn with_two_rectangles() -> Editor { let mut editor = with_a_rectangle(); editor.set_tool(Tool::Rectangle); drag(&mut editor, at(300.0, 100.0), at(400.0, 160.0)); editor.deselect(); + editor +} - editor.press(at(150.0, 130.0), true); - editor.release(at(150.0, 130.0)); - editor.press(at(350.0, 130.0), true); - editor.release(at(350.0, 130.0)); +fn shift_click(editor: &mut Editor, on: Point) { + editor.press(on, true); + editor.release(on); +} + +#[test] +fn a_click_with_shift_adds_to_the_selection_and_takes_away() { + let mut editor = with_two_rectangles(); + shift_click(&mut editor, at(150.0, 130.0)); + shift_click(&mut editor, at(350.0, 130.0)); assert_eq!(editor.selected(), [0, 1]); - editor.press(at(150.0, 130.0), true); - editor.release(at(150.0, 130.0)); + shift_click(&mut editor, at(150.0, 130.0)); assert_eq!(editor.selected(), [1]); + shift_click(&mut editor, at(600.0, 600.0)); + assert_eq!(editor.selected(), [1], "the paper takes nothing away"); +} - editor.deselect(); - editor.press(at(50.0, 50.0), false); - editor.drag(at(120.0, 120.0)); - assert!(editor.marquee().is_some()); - editor.release(at(120.0, 120.0)); - assert_eq!(editor.selected(), [0]); +/// With Shift, a handle is what is under it. +#[test] +fn a_click_with_shift_on_a_handle_is_on_the_object() { + let mut editor = with_a_rectangle(); + shift_click(&mut editor, at(199.0, 130.0)); + + assert!(editor.selected().is_empty()); +} + +#[test] +fn a_marquee_selects_what_it_touches() { + for (from, to, selected) in [ + (at(50.0, 50.0), at(120.0, 120.0), vec![0]), + (at(120.0, 120.0), at(50.0, 50.0), vec![0]), + (at(50.0, 50.0), at(320.0, 120.0), vec![0, 1]), + (at(210.0, 100.0), at(290.0, 160.0), vec![]), + (at(250.0, 130.0), at(310.0, 130.0), vec![1]), + (at(350.0, 50.0), at(350.0, 110.0), vec![1]), + (at(50.0, 50.0), at(99.0, 99.0), vec![]), + (at(202.0, 162.0), at(298.0, 300.0), vec![]), + ] { + let mut editor = with_two_rectangles(); + editor.press(from, false); + editor.drag(to); + editor.release(to); + assert_eq!(editor.selected(), selected, "{from:?} {to:?}"); + } +} + +#[test] +fn a_marquee_is_shown_while_it_is_dragged() { + let mut editor = with_two_rectangles(); + assert_eq!(editor.marquee(), None); + editor.press(at(120.0, 250.0), false); + editor.drag(at(50.0, 300.0)); + + let shown = editor.marquee().unwrap(); + assert_eq!( + (shown.left, shown.top, shown.width, shown.height), + (50.0, 250.0, 70.0, 50.0) + ); + editor.release(at(50.0, 300.0)); + assert_eq!(editor.marquee(), None); +} + +#[test] +fn a_marquee_with_shift_adds_to_the_selection_once_each() { + let mut editor = with_two_rectangles(); + shift_click(&mut editor, at(350.0, 130.0)); + editor.press(at(50.0, 50.0), true); + editor.drag(at(320.0, 120.0)); + editor.release(at(320.0, 120.0)); + + assert_eq!(editor.selected(), [1, 0]); } #[test] fn what_is_selected_moves_together() { - let mut editor = with_a_rectangle(); + let mut editor = with_two_rectangles(); + shift_click(&mut editor, at(150.0, 130.0)); + shift_click(&mut editor, at(350.0, 130.0)); drag(&mut editor, at(150.0, 130.0), at(170.0, 140.0)); assert_eq!(object(&editor, 0).centre(), at(170.0, 140.0)); - assert!(editor.can_undo()); + assert_eq!(object(&editor, 1).centre(), at(370.0, 140.0)); + editor.undo(); + assert_eq!(object(&editor, 1).centre(), at(350.0, 130.0), "in one step"); +} + +#[test] +fn a_press_on_what_is_not_selected_moves_it_alone() { + let mut editor = with_two_rectangles(); + shift_click(&mut editor, at(150.0, 130.0)); + + drag(&mut editor, at(350.0, 130.0), at(350.0, 140.0)); + + assert_eq!(editor.selected(), [1]); + assert_eq!(object(&editor, 0).centre(), at(150.0, 130.0)); +} + +#[test] +fn an_arrow_moved_takes_its_ends_along() { + let mut editor = editor(); + editor.set_tool(Tool::Arrow); + drag(&mut editor, at(0.0, 0.0), at(100.0, 40.0)); + drag(&mut editor, at(50.0, 20.0), at(60.0, 25.0)); + + assert_eq!(object(&editor, 0).ends(), Some([10.0, 5.0, 110.0, 45.0])); } #[test] @@ -289,29 +504,97 @@ fn a_corner_keeps_the_proportions_from_the_opposite_corner() { } #[test] -fn a_side_scales_one_way_and_a_text_gets_wider_instead() { +fn a_side_scales_one_way() { + for (grip, (dx, dy), scale) in [ + (Grip::Right, (102.0, 0.0), (2.0, 1.0)), + (Grip::Left, (-102.0, 0.0), (2.0, 1.0)), + (Grip::Bottom, (0.0, 62.0), (1.0, 2.0)), + (Grip::Top, (0.0, -62.0), (1.0, 2.0)), + (Grip::TopLeft, (-102.0, -10.0), (2.0, 2.0)), + (Grip::BottomRight, (10.0, 62.0), (2.0, 2.0)), + ] { + let mut editor = with_a_rectangle(); + let from = editor.frame().unwrap().grip(grip); + drag(&mut editor, from, at(from.x + dx, from.y + dy)); + let shape = object(&editor, 0); + assert_eq!((shape.scale_x(), shape.scale_y()), scale, "{grip:?}"); + } +} + +#[test] +fn the_side_opposite_the_handle_stays_where_it_is() { + let mut editor = with_a_rectangle(); + let before = editor.frame().unwrap(); + + drag(&mut editor, before.grip(Grip::Right), at(301.0, 130.0)); + + let after = editor.frame().unwrap(); + assert!((after.grip(Grip::Left).x - before.grip(Grip::Left).x).abs() < 1.5); +} + +/// Scaled to nothing, it could not be taken again. +#[test] +fn a_handle_dragged_past_the_opposite_side_leaves_a_sliver() { let mut editor = with_a_rectangle(); + let side = editor.frame().unwrap().grip(Grip::Right); + + drag(&mut editor, side, at(-500.0, 130.0)); + + assert_eq!(object(&editor, 0).scale_x(), 0.01); +} + +#[test] +fn several_objects_scale_from_the_side_opposite_the_handle() { + let mut editor = with_two_rectangles(); + shift_click(&mut editor, at(150.0, 130.0)); + shift_click(&mut editor, at(350.0, 130.0)); let frame = editor.frame().unwrap(); let side = frame.grip(Grip::Right); drag(&mut editor, side, at(side.x + frame.width, side.y)); - assert_eq!(object(&editor, 0).scale_x(), 2.0); - assert_eq!(object(&editor, 0).scale_y(), 1.0); - let mut editor = self::editor(); - editor.set_tool(Tool::Text); - editor.press(at(0.0, 100.0), false); - editor.set_text("words enough to wrap across two lines at least"); - editor.leave_text(); + assert_eq!(object(&editor, 1).scale_x(), 2.0); + assert!((object(&editor, 0).centre().x - 201.0).abs() < 0.01); + assert!((object(&editor, 1).centre().x - 601.0).abs() < 0.01); +} + +#[test] +fn a_text_gets_wider_or_narrower_by_its_sides_and_wraps_anew() { + let mut editor = with_a_text("words enough to wrap across two lines at least"); let height = object(&editor, 0).height(); - let frame = editor.frame().unwrap(); + let side = editor.frame().unwrap().grip(Grip::Right); - let side = frame.grip(Grip::Right); drag(&mut editor, side, at(side.x - 90.0, side.y)); - assert_eq!(object(&editor, 0).scale_x(), 1.0); - assert!(object(&editor, 0).width() < 100.0); - assert!(object(&editor, 0).height() > height); + let text = object(&editor, 0); + assert_eq!((text.scale_x(), text.scale_y()), (1.0, 1.0)); + assert!(text.width() < 100.0 && text.height() > height); +} + +#[test] +fn a_text_is_never_narrower_than_a_few_letters() { + let mut editor = with_a_text("words"); + let side = editor.frame().unwrap().grip(Grip::Right); + + drag(&mut editor, side, at(side.x - 400.0, side.y)); + + assert_eq!(object(&editor, 0).width(), 20.0); +} + +#[test] +fn a_text_is_scaled_by_its_corners() { + let mut editor = with_a_text("words"); + let frame = editor.frame().unwrap(); + let corner = frame.grip(Grip::BottomRight); + + drag( + &mut editor, + corner, + at(corner.x + frame.width, corner.y + frame.height), + ); + + assert_eq!(object(&editor, 0).scale_x(), 2.0); + assert_eq!(object(&editor, 0).width(), 180.0); } #[test] @@ -349,41 +632,101 @@ fn several_objects_turn_around_their_frame() { } #[test] -fn a_hue_is_for_what_is_drawn_next_and_what_is_selected() { - let mut editor = with_a_rectangle(); +fn a_hue_is_for_what_is_drawn_next() { + let mut editor = editor(); + editor.set_hue(Hue::Blue); + editor.set_tool(Tool::Rectangle); + drag(&mut editor, at(300.0, 300.0), at(340.0, 340.0)); + assert_eq!(editor.hue(), Hue::Blue); + assert_eq!(object(&editor, 0).hue(), Hue::Blue); +} + +#[test] +fn a_hue_is_for_what_is_selected_now_a_step_of_the_history() { + let mut editor = with_a_rectangle(); editor.set_hue(Hue::Red); assert_eq!(object(&editor, 0).hue(), Hue::Red); + editor.undo(); + assert_eq!(object(&editor, 0).hue(), Hue::Ink); +} + +#[test] +fn with_nothing_selected_a_hue_changes_nothing_drawn() { + let mut editor = with_a_rectangle(); editor.deselect(); - editor.set_hue(Hue::Blue); - assert_eq!(object(&editor, 0).hue(), Hue::Red); - editor.set_tool(Tool::Rectangle); - drag(&mut editor, at(300.0, 300.0), at(340.0, 340.0)); - assert_eq!(object(&editor, 1).hue(), Hue::Blue); - assert_eq!(editor.hue(), Hue::Blue); + editor.take_unsaved(); + editor.set_hue(Hue::Red); + + assert_eq!(object(&editor, 0).hue(), Hue::Ink); + assert!(!editor.take_unsaved()); } #[test] -fn undo_and_redo_walk_the_history_and_a_change_drops_what_was_undone() { +fn undo_and_redo_walk_the_history() { let mut editor = with_a_rectangle(); drag(&mut editor, at(150.0, 130.0), at(250.0, 130.0)); editor.undo(); assert_eq!(object(&editor, 0).centre(), at(150.0, 130.0)); - assert!(editor.can_redo()); - editor.redo(); assert_eq!(object(&editor, 0).centre(), at(250.0, 130.0)); - + assert!(!editor.can_redo()); editor.undo(); editor.undo(); assert_eq!(editor.shapes(), 0); assert!(!editor.can_undo()); +} + +#[test] +fn past_either_end_of_the_history_nothing_changes() { + let mut editor = with_a_rectangle(); + editor.take_unsaved(); editor.redo(); + assert_eq!(editor.shapes(), 1); + assert!(!editor.take_unsaved()); + + let mut empty = self::editor(); + empty.undo(); + assert!(!empty.take_unsaved()); +} + +#[test] +fn what_is_undone_is_to_save_and_drops_the_selection() { + let mut editor = with_a_rectangle(); + editor.take_unsaved(); + let shown = editor.revision(); + + editor.undo(); + assert!(editor.selected().is_empty()); + assert!(editor.take_unsaved()); + assert!(editor.revision() > shown); +} + +#[test] +fn what_is_undone_while_a_text_is_typed_into_leaves_it() { + let mut editor = with_a_text("one"); + let inside = object(&editor, 0).centre(); + drag(&mut editor, inside, inside); + assert!(editor.editing().is_some()); + + editor.undo(); + assert!(editor.editing().is_none()); +} + +#[test] +fn a_change_drops_what_was_undone() { + let mut editor = with_a_rectangle(); + drag(&mut editor, at(150.0, 130.0), at(250.0, 130.0)); + editor.undo(); + assert!(editor.can_redo()); + editor.set_tool(Tool::Ellipse); drag(&mut editor, at(0.0, 0.0), at(40.0, 40.0)); assert!(!editor.can_redo()); + editor.undo(); + assert_eq!(object(&editor, 0).centre(), at(150.0, 130.0)); } #[test] @@ -441,13 +784,46 @@ fn a_click_leaves_an_arrow_where_it_stands_until_its_shape_moves() { #[test] fn escape_gives_back_the_selection_a_tool_took_over() { let mut editor = with_a_rectangle(); - editor.set_tool(Tool::Arrow); assert!(editor.selected().is_empty()); + editor.set_tool(Tool::Pen); editor.back_to_selection(); assert_eq!(editor.tool(), Tool::Select); assert_eq!(editor.selected(), [0]); +} + +#[test] +fn the_selection_kept_goes_with_what_is_drawn_erased_or_undone_since() { + let draws = |editor: &mut Editor| { + editor.set_tool(Tool::Ellipse); + drag(editor, at(400.0, 0.0), at(440.0, 40.0)); + editor.deselect(); + }; + let erases = |editor: &mut Editor| { + editor.set_tool(Tool::Eraser); + drag(editor, at(150.0, 130.0), at(150.0, 130.0)); + }; + let undoes = |editor: &mut Editor| { + editor.set_tool(Tool::Pen); + editor.undo(); + }; + let types = |editor: &mut Editor| { + editor.set_tool(Tool::Text); + editor.press(at(400.0, 0.0), false); + editor.leave_text(); + }; + for since in [draws as fn(&mut Editor), erases, undoes, types] { + let mut editor = with_a_rectangle(); + since(&mut editor); + editor.back_to_selection(); + assert!(editor.selected().is_empty()); + } +} + +#[test] +fn a_selection_dropped_is_told_once() { + let mut editor = with_a_rectangle(); assert!(editor.deselect()); assert!(!editor.deselect()); @@ -756,3 +1132,215 @@ fn an_anchor_no_code_here_wrote_is_the_edge_and_stays_stored() { drag(&mut editor, at(100.0, 100.0), at(100.0, 110.0)); assert!(editor.body().contains(r#""fromAnchor":"corner""#)); } + +#[test] +fn a_shape_drawn_has_the_stroke_and_the_corners_of_its_kind() { + for (tool, kind, corners) in [ + (Tool::Rectangle, Kind::Rect, r#""rx":6,"ry":6"#), + (Tool::Ellipse, Kind::Ellipse, r#""rx":50,"ry":30"#), + (Tool::Diamond, Kind::Polygon, r#""points":["#), + ] { + let mut editor = editor(); + editor.set_tool(tool); + drag(&mut editor, at(0.0, 0.0), at(100.0, 60.0)); + let body = editor.body(); + + assert_eq!(object(&editor, 0).kind(), kind); + assert_eq!(object(&editor, 0).stroke_width(), 2.0); + assert!(object(&editor, 0).stroke_uniform()); + assert!(body.contains(corners), "{body}"); + assert!(body.contains(r#""originX":"center","originY":"center""#)); + assert!(body.contains(r#""type":"#) && body.contains(r#""version":"7.4.0","originX""#)); + } +} + +#[test] +fn a_shape_is_shown_while_it_is_dragged() { + let mut editor = editor(); + editor.set_tool(Tool::Rectangle); + editor.press(at(0.0, 0.0), false); + let shown = editor.revision(); + editor.drag(at(40.0, 20.0)); + + assert_eq!( + (object(&editor, 0).width(), object(&editor, 0).height()), + (40.0, 20.0) + ); + assert!(editor.revision() > shown); + assert!(!editor.can_undo(), "a step of the history once let go"); +} + +/// On the screen: closer, the same click covers less of the scene. +#[test] +fn a_click_is_told_from_a_drag_on_the_screen() { + for (scale, dragged, size) in [ + (1.0, (5.0, 5.0), (140.0, 80.0)), + (1.0, (6.0, 1.0), (6.0, 1.0)), + (1.0, (1.0, 6.0), (1.0, 6.0)), + (4.0, (2.0, 2.0), (2.0, 2.0)), + (0.5, (11.0, 11.0), (140.0, 80.0)), + ] { + let mut editor = editor(); + editor.set_scale(scale); + editor.set_tool(Tool::Rectangle); + drag(&mut editor, at(0.0, 0.0), at(dragged.0, dragged.1)); + let shape = object(&editor, 0); + assert_eq!((shape.width(), shape.height()), size, "{scale} {dragged:?}"); + } +} + +#[test] +fn a_handle_is_taken_from_as_far_on_the_screen_whatever_the_scale() { + for (scale, away, taken) in [ + (1.0, 8.0, true), + (1.0, 8.5, false), + (2.0, 4.0, true), + (2.0, 4.5, false), + ] { + let mut editor = with_a_rectangle(); + editor.set_scale(scale); + let corner = editor.frame().unwrap().grip(Grip::BottomRight); + let near = at(corner.x + away, corner.y + away); + drag(&mut editor, near, at(near.x + 100.0, near.y + 100.0)); + assert_eq!(object(&editor, 0).scale_x() > 1.0, taken, "{scale} {away}"); + } +} + +#[test] +fn an_end_of_an_arrow_is_taken_from_as_far_on_the_screen() { + for (dx, dy, taken) in [ + (8.0, 0.0, true), + (0.0, 8.0, true), + (8.5, 0.0, false), + (0.0, 8.5, false), + ] { + let mut editor = joined(); + let end = at(299.0 + dx, 30.0 + dy); + editor.press(end, false); + editor.drag(at(250.0, 300.0)); + let moved = ends(&editor)[2..] == [250.0, 300.0]; + assert_eq!(moved, taken, "{dx} {dy}"); + } +} + +#[test] +fn the_rotation_handle_stands_as_high_on_the_screen_whatever_the_scale() { + let mut editor = with_a_rectangle(); + assert_eq!(editor.frame().unwrap().grip(Grip::Rotate), at(150.0, 59.0)); + + editor.set_scale(2.0); + assert_eq!(editor.frame().unwrap().grip(Grip::Rotate), at(150.0, 79.0)); +} + +#[test] +fn the_frame_of_a_turned_shape_turns_with_it() { + let mut editor = with_a_rectangle(); + let handle = editor.frame().unwrap().grip(Grip::Rotate); + drag(&mut editor, handle, at(250.0, 130.0)); + + let corners = editor.frame().unwrap().corners(); + for (corner, (x, y)) in + corners + .into_iter() + .zip([(181.0, 79.0), (181.0, 181.0), (119.0, 181.0), (119.0, 79.0)]) + { + assert!( + (corner.x - x).abs() < 1e-6 && (corner.y - y).abs() < 1e-6, + "{corner:?}" + ); + } +} + +#[test] +fn a_turned_shape_is_scaled_along_its_own_sides() { + let mut editor = with_a_rectangle(); + let handle = editor.frame().unwrap().grip(Grip::Rotate); + drag(&mut editor, handle, at(250.0, 130.0)); + // Its right side is now at the bottom. + drag(&mut editor, at(150.0, 181.0), at(150.0, 283.0)); + + let shape = object(&editor, 0); + assert_eq!((shape.scale_x(), shape.scale_y()), (2.0, 1.0)); +} + +#[test] +fn where_an_arrow_is_held_is_told_from_as_far_as_its_side_is_reached() { + let mut editor = joined(); + editor.set_tool(Tool::Arrow); + for (dx, dy, told) in [ + (8.0, 0.0, true), + (8.5, 0.0, false), + (0.0, 8.0, true), + (0.0, 8.5, false), + ] { + let chosen = editor + .attaching(at(401.0 + dx, 30.0 + dy)) + .and_then(|found| found.chosen); + assert_eq!(chosen, told.then_some(at(401.0, 30.0)), "{dx} {dy}"); + } +} + +#[test] +fn a_pen_line_holds_an_arrow_by_its_edge_alone() { + let mut editor = with_the_pen(&[at(0.0, 0.0), at(50.0, 50.0), at(100.0, 0.0)]); + editor.set_tool(Tool::Arrow); + + let found = editor.attaching(at(50.0, 20.0)).unwrap(); + assert!(found.points.is_empty() && found.chosen.is_none()); +} + +#[test] +fn an_arrow_bound_to_a_shape_that_is_gone_stays_where_it_is() { + let body = r#"{"scene":{"objects":[ + {"type":"Rect","id":"a","left":100,"top":100,"width":100,"height":100}, + {"type":"Path","id":"b","from":"gone","ends":[300,100,400,100],"path":[["M",300,100],["L",400,100]]} + ]}}"#; + let mut editor = Editor::open(body, Arc::new(fonts())); + drag(&mut editor, at(100.0, 100.0), at(100.0, 110.0)); + + assert_eq!( + object(&editor, 1).ends(), + Some([300.0, 100.0, 400.0, 100.0]) + ); +} + +#[test] +fn every_gesture_shows_what_it_changes() { + let mut editor = with_a_rectangle(); + for (tool, from, to) in [ + (Tool::Select, at(150.0, 130.0), at(160.0, 130.0)), + (Tool::Select, at(600.0, 600.0), at(650.0, 650.0)), + (Tool::Pen, at(0.0, 0.0), at(50.0, 0.0)), + (Tool::Arrow, at(0.0, 300.0), at(50.0, 300.0)), + (Tool::Eraser, at(600.0, 0.0), at(650.0, 0.0)), + ] { + editor.set_tool(tool); + editor.press(from, false); + let pressed = editor.revision(); + editor.drag(to); + assert!(editor.revision() > pressed, "{tool:?}"); + editor.release(to); + } +} + +#[test] +fn nothing_pressed_a_drag_and_a_release_do_nothing() { + let mut editor = with_a_rectangle(); + let shown = editor.revision(); + editor.drag(at(0.0, 0.0)); + editor.release(at(0.0, 0.0)); + + assert_eq!(editor.revision(), shown); +} + +#[test] +fn the_eraser_tells_what_it_would_take_by_its_frame() { + let editor = with_a_rectangle(); + let frame = editor.erasable(at(150.0, 130.0)).unwrap(); + + assert_eq!( + (frame.centre, frame.width, frame.height), + (at(150.0, 130.0), 102.0, 62.0) + ); + assert!(editor.erasable(at(0.0, 0.0)).is_none()); +} diff --git a/crates/drawing/src/geometry.rs b/crates/drawing/src/geometry.rs index 360f0237a..78b2588c6 100644 --- a/crates/drawing/src/geometry.rs +++ b/crates/drawing/src/geometry.rs @@ -355,16 +355,24 @@ mod tests { } #[test] - fn a_drag_reads_whichever_way_it_went_and_a_diamond_has_its_corners_mid_side() { - assert_eq!( - drag_box(at(50.0, 40.0), at(10.0, 60.0)), - Box { - left: 10.0, - top: 40.0, - width: 40.0, - height: 20.0 - } - ); + fn a_drag_reads_whichever_way_it_went() { + let covered = Box { + left: 10.0, + top: 40.0, + width: 40.0, + height: 20.0, + }; + for (from, to) in [ + (at(50.0, 40.0), at(10.0, 60.0)), + (at(10.0, 40.0), at(50.0, 60.0)), + (at(50.0, 60.0), at(10.0, 40.0)), + ] { + assert_eq!(drag_box(from, to), covered); + } + } + + #[test] + fn a_diamond_has_its_corners_mid_side() { assert_eq!( diamond_points(40.0, 20.0), [at(20.0, 0.0), at(40.0, 10.0), at(20.0, 20.0), at(0.0, 10.0)] @@ -372,14 +380,40 @@ mod tests { } #[test] - fn a_picture_is_scaled_and_framed() { - let wide = Box { - width: 800.0, - height: 200.0, - ..BOX - }; - assert!((picture_scale(&wide, 400.0, 2.0) - 0.5).abs() < f64::EPSILON); - assert!((picture_scale(&BOX, 1600.0, 2.0) - 2.0).abs() < f64::EPSILON); + fn a_picture_s_longest_side_is_brought_to_its_size_never_enlarged_too_much() { + for (width, height, scale) in [ + (800.0, 200.0, 0.5), + (200.0, 800.0, 0.5), + (100.0, 50.0, 2.0), + (0.0, 0.0, 2.0), + ] { + let bounds = Box { + width, + height, + ..BOX + }; + assert_eq!( + picture_scale(&bounds, 400.0, 2.0), + scale, + "{width} {height}" + ); + } + assert_eq!( + picture_scale( + &Box { + width: 0.5, + height: 0.0, + ..BOX + }, + 400.0, + 900.0 + ), + 400.0 + ); + } + + #[test] + fn a_scene_is_framed_by_all_that_is_on_it_with_room_around() { let small = Box { left: 150.0, top: -20.0, @@ -397,4 +431,91 @@ mod tests { ); assert_eq!(scene_box(&[], MARGIN), None); } + + #[test] + fn a_path_is_covered_to_where_its_curves_turn() { + use PathCommand::{Close, Line, Move, Quad}; + + let covered = + |path: &[PathCommand]| path_box(path).map(|b| [b.left, b.top, b.width, b.height]); + + assert_eq!( + covered(&[Move(at(1.0, 2.0)), Line(at(5.0, 9.0)), Close]), + Some([1.0, 2.0, 4.0, 7.0]) + ); + // A curve up to its control and back: it goes half the way. + assert_eq!( + covered(&[Move(at(0.0, 0.0)), Quad(at(10.0, 20.0), at(20.0, 0.0))]), + Some([0.0, 0.0, 20.0, 10.0]) + ); + // The second curve starts where the first ended. + assert_eq!( + covered(&[ + Move(at(0.0, 0.0)), + Quad(at(5.0, 0.0), at(10.0, 0.0)), + Quad(at(20.0, 0.0), at(10.0, 10.0)) + ]), + Some([0.0, 0.0, 15.0, 10.0]) + ); + // A control between its ends turns nowhere. + assert_eq!( + covered(&[Move(at(0.0, 0.0)), Quad(at(1.0, 5.0), at(10.0, 10.0))]), + Some([0.0, 0.0, 10.0, 10.0]) + ); + assert_eq!( + covered(&[Quad(at(9.0, 9.0), at(1.0, 1.0))]), + Some([1.0, 1.0, 0.0, 0.0]) + ); + assert_eq!(covered(&[Close]), None); + assert_eq!(covered(&[]), None); + } + + #[test] + fn a_line_by_hand_is_a_curve_through_the_middles_of_its_points() { + use PathCommand::{Line, Move, Quad}; + + assert_eq!( + smooth_path(&[at(0.0, 0.0), at(10.0, 0.0), at(20.0, 10.0)]), + Some(vec![ + Move(at(0.0, 0.0)), + Quad(at(0.0, 0.0), at(5.0, 0.0)), + Quad(at(10.0, 0.0), at(15.0, 5.0)), + Line(at(20.0, 10.0)), + ]) + ); + } + + /// The first and the last are kept, whatever is between. + #[test] + fn points_too_close_to_the_last_one_kept_are_dropped() { + let near = PEN_DECIMATE / 2.0; + let kept = decimated(&[ + at(0.0, 0.0), + at(near, 0.0), + at(PEN_DECIMATE, 0.0), + at(PEN_DECIMATE + near, 0.0), + at(PEN_DECIMATE * 3.0, 0.0), + at(PEN_DECIMATE * 3.0 + near, 0.0), + ]); + + assert_eq!( + kept, + [ + at(0.0, 0.0), + at(PEN_DECIMATE, 0.0), + at(PEN_DECIMATE * 3.0, 0.0), + at(PEN_DECIMATE * 3.0 + near, 0.0) + ] + ); + assert!(decimated(&[]).is_empty()); + } + + #[test] + fn a_line_that_went_nowhere_is_none() { + let here = at(3.0, 4.0); + for points in [vec![], vec![here], vec![here; 2], vec![here; 5]] { + assert_eq!(smooth_path(&points), None, "{points:?}"); + } + assert!(smooth_path(&[here, at(3.0, 5.0)]).is_some()); + } } diff --git a/crates/drawing/src/marks.rs b/crates/drawing/src/marks.rs index 7db6ec6a5..83e8093ff 100644 --- a/crates/drawing/src/marks.rs +++ b/crates/drawing/src/marks.rs @@ -437,4 +437,56 @@ mod tests { marks_of(r#"{"type":"Polygon","skewX":45,"points":[{"x":0,"y":0},{"x":0,"y":10}]}"#); assert!(near(line(&skewed[0]).0[1], 5.0, 5.0)); } + + #[test] + fn a_path_of_a_lone_point_is_not_drawn_and_each_piece_is_its_own() { + let pieces = |path: &str| { + let marks = marks_of(&format!(r#"{{"type":"Path","path":[{path}]}}"#)); + marks + .iter() + .map(|mark| line(mark).0.len()) + .collect::>() + }; + + assert!(pieces(r#"["M",0,0]"#).is_empty()); + assert!(pieces(r#"["M",0,0],["Z"]"#).is_empty()); + assert_eq!( + pieces(r#"["M",0,0],["L",1,0],["M",5,5],["M",6,6],["L",7,7],["L",8,8]"#), + [2, 3] + ); + assert_eq!( + pieces(r#"["M",0,0],["L",1,0],["Z"],["L",9,9],["L",8,8]"#), + [2, 2] + ); + } + + /// Each curve starts where the one before ended, whatever it was. + #[test] + fn a_curve_starts_where_the_pen_was() { + for before in [ + r#"["M",10,0]"#, + r#"["M",0,0],["L",10,0]"#, + r#"["M",0,0],["Q",5,0,10,0]"#, + ] { + let marks = marks_of(&format!( + r#"{{"type":"Path","path":[{before},["Q",10,100,10,200]]}}"# + )); + let (points, ..) = line(&marks[0]); + let x = points[points.len() - 1].x; + let curve = &points[points.len() - usize::try_from(CURVE_STEPS).unwrap()..]; + assert!( + curve.iter().all(|at| (at.x - x).abs() < 1e-9), + "{before}: {curve:?}" + ); + } + } + + /// The head of an arrow closes; a pen's line that closes is no head. + #[test] + fn a_closed_piece_is_filled_on_an_arrow_alone() { + let closed = marks_of(r#"{"type":"Path","path":[["M",0,0],["L",10,0],["L",5,5],["Z"]]}"#); + + assert!(line(&closed[0]).1); + assert_eq!(line(&closed[0]).2, Fill::None); + } } diff --git a/crates/drawing/src/scene.rs b/crates/drawing/src/scene.rs index 2bc92c20d..f33d6bf35 100644 --- a/crates/drawing/src/scene.rs +++ b/crates/drawing/src/scene.rs @@ -104,14 +104,14 @@ impl Drawing { } } - /// `None` for a body that holds no scene, or one whose objects are not objects: what - /// opens as a new drawing. /// What everything drawn covers; `None` when nothing is. pub fn bounds(&self) -> Option { let boxes: Vec<_> = self.objects.iter().map(Object::bounds).collect(); crate::geometry::scene_box(&boxes, 0.0) } + /// `None` for a body that holds no scene, or one whose objects are not objects: what + /// opens as a new drawing. pub fn read(content: &str) -> Option { let Value::Object(mut body) = serde_json::from_str(content).ok()? else { return None; diff --git a/crates/drawing/src/scene/tests.rs b/crates/drawing/src/scene/tests.rs index f82d8d0a6..5143d5f7e 100644 --- a/crates/drawing/src/scene/tests.rs +++ b/crates/drawing/src/scene/tests.rs @@ -230,3 +230,101 @@ fn the_first_object_put_on_an_empty_scene_is_stored() { assert_eq!(drawing.write(), r#"{"scene":{"objects":[{"id":"a"}]}}"#); } + +/// As Fabric stores one: two decimals, and no `.0`. +#[test] +fn a_number_is_stored_with_two_decimals_at_most() { + for (value, expected) in [ + (1.0, "1"), + (-0.5, "-0.5"), + (1.005_1, "1.01"), + (0.001, "0"), + (1e14, "100000000000000"), + (1e15, "1000000000000000.0"), + ] { + assert_eq!(stored(value).to_string(), expected); + } +} + +#[test] +fn an_angle_is_stored_within_one_turn() { + let mut object = Object::make("Rect", "a".to_owned(), Hue::Ink); + for (degrees, angle) in [(90.0, 90.0), (360.0, 0.0), (-90.0, 270.0), (725.0, 5.0)] { + object.set_angle(degrees); + assert_eq!(object.angle().to_string(), angle.to_string()); + } +} + +/// Its whole box, its stroke counted, turned with it. +#[test] +fn a_point_is_on_an_object_by_its_box() { + let object = |angle: f64| { + let body = format!( + r#"{{"scene":{{"objects":[{{"type":"Ellipse","left":10,"top":20,"width":98,"height":18,"strokeWidth":2,"angle":{angle}}}]}}}}"# + ); + Drawing::read(&body).unwrap().objects.remove(0) + }; + + let level = object(0.0); + for (x, y, on) in [ + (60.0, 20.0, true), + (60.1, 20.0, false), + (10.0, 30.0, true), + (10.0, 30.1, false), + (-40.0, 10.0, true), + ] { + assert_eq!(level.contains(at(x, y)), on, "{x} {y}"); + } + let turned = object(90.0); + assert!(turned.contains(at(10.0, 69.0)) && !turned.contains(at(59.0, 20.0))); +} + +#[test] +fn a_drawing_covers_all_that_is_drawn() { + let body = r#"{"scene":{"objects":[ + {"type":"Rect","left":0,"top":0,"width":10,"height":10,"strokeWidth":0}, + {"type":"Rect","left":50,"top":20,"width":20,"height":10,"strokeWidth":0}]}}"#; + let covered = Drawing::read(body).unwrap().bounds().unwrap(); + + assert_eq!( + [covered.left, covered.top, covered.width, covered.height].map(|side| side.to_string()), + ["-5", "-5", "65", "30"] + ); + assert_eq!(Drawing::empty().bounds(), None); +} + +#[test] +fn a_new_drawing_is_empty_and_read_back() { + let empty = Drawing::empty(); + + assert_eq!( + empty.write(), + r#"{"version":1,"scene":{"version":"7.4.0"}}"# + ); + let read = Drawing::read(&empty.write()).unwrap(); + assert_eq!(read.write(), empty.write()); +} + +#[test] +fn a_shape_let_go_is_null_and_its_point_goes_with_it() { + let mut arrow = Object::make("Path", "a".to_owned(), Hue::Ink); + arrow.set_bound("from", Some("b")); + arrow.set_anchor("from", Some(Side::Left)); + assert_eq!( + (arrow.from(), arrow.anchor("from")), + (Some("b"), Some(Side::Left)) + ); + + arrow.set_bound("from", None); + assert_eq!((arrow.from(), arrow.anchor("from")), (None, None)); + assert_eq!(arrow.fields().get("from"), Some(&Value::Null)); +} + +#[test] +fn each_side_is_read_back_by_its_word() { + let mut arrow = Object::make("Path", "a".to_owned(), Hue::Ink); + for side in Side::ALL { + arrow.set_anchor("to", Some(side)); + assert_eq!(arrow.anchor("to"), Some(side)); + } +} diff --git a/crates/drawing/src/text/tests.rs b/crates/drawing/src/text/tests.rs index 9d944ebb5..ff243444a 100644 --- a/crates/drawing/src/text/tests.rs +++ b/crates/drawing/src/text/tests.rs @@ -64,3 +64,16 @@ fn the_baselines_are_fabrics() { assert!((line_step(18.0, 1.16) - 23.5944).abs() < 1e-9); assert!((first_baseline(18.0) - 15.82452).abs() < 1e-9); } + +/// Spaces that do not fit end a line; a blank line is a line. +#[test] +fn lines_break_at_spaces_and_at_line_ends() { + for (text, width, lines) in [ + ("", 180.0, vec![""]), + ("a\n\nb", 180.0, vec!["a", "", "b"]), + ("a b", 1.0, vec!["a", "b"]), + ("ab cd", 1000.0, vec!["ab cd"]), + ] { + assert_eq!(wrapped(text, width), lines, "{text:?}"); + } +} From 9c94e956d565390d3490a03f047e81dd2d8e64b0 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 08:37:00 +0100 Subject: [PATCH 63/95] Translations: unit tests rewritten for counts, dates and numbers (#1796) Co-authored-by: Claude Opus 5.5 --- crates/i18n/src/format.rs | 110 +++++++++++++++++++++++++++++++++++ crates/i18n/src/lib.rs | 78 +++++++++++++++++++++++++ crates/i18n/src/plural.rs | 74 ++++++++++++++++++++++++ crates/i18n/src/time.rs | 119 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 381 insertions(+) diff --git a/crates/i18n/src/format.rs b/crates/i18n/src/format.rs index 54c2c8eaa..6f0fb0427 100644 --- a/crates/i18n/src/format.rs +++ b/crates/i18n/src/format.rs @@ -556,4 +556,114 @@ mod tests { assert_eq!(signed(-0.001, Language::En), "0"); assert_eq!(number(-0.0, Language::En), "0"); } + + #[test] + fn an_exact_decimal_is_rounded_half_away_from_zero_without_a_float() { + let read = |value, digits| exact(value, digits, false, true, Language::En); + + assert_eq!(read("-1234567.891", (0, 2)), "-1,234,567.89"); + assert_eq!(read("0.005", (0, 2)), "0.01"); + assert_eq!(read("0.0049", (0, 2)), "0"); + assert_eq!(read("-0.005", (0, 2)), "-0.01"); + assert_eq!(read("9007199254740993", (0, 0)), "9,007,199,254,740,993"); + assert_eq!(read("999.995", (0, 2)), "1,000"); + } + + #[test] + fn decimals_are_kept_between_the_fewest_and_the_most() { + let read = |value, digits| exact(value, digits, false, false, Language::Fr); + for (value, digits, text) in [ + ("1", (0, 2), "1"), + ("1", (2, 4), "1,00"), + ("1.5", (2, 4), "1,50"), + ("1.50", (0, 4), "1,5"), + ("1.500", (2, 4), "1,50"), + ("1.12345", (2, 4), "1,1235"), + ("1.10", (1, 2), "1,1"), + ("1.00", (0, 2), "1"), + ] { + assert_eq!(read(value, digits), text, "{value} {digits:?}"); + } + } + + #[test] + fn a_sign_is_written_before_what_is_not_zero() { + let read = |value, signed| exact(value, (0, 2), signed, false, Language::En); + for (value, plain, with_sign) in [ + ("5", "5", "+5"), + ("-5", "-5", "-5"), + ("0", "0", "0"), + ("10", "10", "+10"), + ("0.5", "0.5", "+0.5"), + ("0.001", "0", "0"), + ("-0.001", "-0", "0"), + ] { + assert_eq!( + (read(value, false), read(value, true)), + (plain.to_owned(), with_sign.to_owned()), + "{value}" + ); + } + } + + #[test] + fn thousands_are_grouped_by_three_where_asked() { + for (value, english, french, plain) in [ + ("999", "999", "999", "999"), + ("1000", "1,000", "1\u{202f}000", "1000"), + ("1234567", "1,234,567", "1\u{202f}234\u{202f}567", "1234567"), + ] { + let read = |grouped, language| exact(value, (0, 0), false, grouped, language); + assert_eq!(read(true, Language::En), english); + assert_eq!(read(true, Language::Fr), french); + assert_eq!(read(false, Language::Fr), plain); + } + } + + /// Where a clock of twelve hours says it. + #[test] + fn noon_and_midnight_read_on_both_clocks() { + for (hour, english, french) in [ + (0, "12:05 AM", "00:05"), + (1, "01:05 AM", "01:05"), + (11, "11:05 AM", "11:05"), + (12, "12:05 PM", "12:05"), + (13, "01:05 PM", "13:05"), + (23, "11:05 PM", "23:05"), + ] { + let time = NaiveTime::from_hms_opt(hour, 5, 0).unwrap(); + assert_eq!( + time_minutes(time, Language::En).replace('\u{202f}', " "), + english + ); + assert_eq!(time_minutes(time, Language::Fr), french); + } + } + + #[test] + fn each_month_and_each_day_has_its_name_in_both_languages() { + let day = + |offset: u64| NaiveDate::from_ymd_opt(2026, 1, 5).unwrap() + chrono::Days::new(offset); + let days: Vec = (0..7) + .map(|offset| weekday(day(offset), Language::Fr).to_owned()) + .collect(); + assert_eq!( + days, + [ + "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", "dimanche" + ] + ); + assert_eq!(weekday(day(6), Language::En), "Sunday"); + + for (number, short_fr, short_en, long_en) in [ + (1, "janv.", "Jan", "January"), + (5, "mai", "May", "May"), + (12, "déc.", "Dec", "December"), + ] { + let date = NaiveDate::from_ymd_opt(2026, number, 1).unwrap(); + assert_eq!(month_short(date, Language::Fr), short_fr); + assert_eq!(month_short(date, Language::En), short_en); + assert_eq!(month(date, Language::En), long_en); + } + } } diff --git a/crates/i18n/src/lib.rs b/crates/i18n/src/lib.rs index 6c9d608b0..c71dba427 100644 --- a/crates/i18n/src/lib.rs +++ b/crates/i18n/src/lib.rs @@ -422,4 +422,82 @@ mod tests { assert_eq!(of(&["ja-JP"]), Language::En); assert_eq!(of(&[]), Language::En); } + + #[test] + fn a_number_is_read_from_a_text_that_writes_one() { + for (value, number) in [ + (Value::from(3_u32), Some(3.0)), + (Value::from(1.5), Some(1.5)), + (Value::from(" 12 "), Some(12.0)), + (Value::from("-0.5".to_owned()), Some(-0.5)), + (Value::from("douze"), None), + (Value::from(""), None), + (Value::from("NaN"), None), + (Value::from("inf"), None), + (Value::from(f64::INFINITY), None), + ] { + assert_eq!(value.as_number(), number, "{value:?}"); + } + } + + #[test] + fn a_message_counts_and_fills_with_what_it_carries() { + let message = Message::new(keys::time::MINUTES_AGO).with("count", 5_u32); + + assert_eq!(message.text(Language::En), "5 min ago"); + assert_eq!( + message.text(Language::Fr), + translate( + Language::Fr, + keys::time::MINUTES_AGO, + &[("count", Value::Number(5.0))] + ) + ); + } + + #[test] + fn a_sentence_is_read_as_written_with_its_braces() { + let (key, template) = FRENCH + .iter() + .find(|(_, text)| text.contains("{{app}}")) + .map(|(path, text)| (Key::find(path).unwrap(), text)) + .unwrap(); + + assert_eq!(&as_written(Language::Fr, key), template); + assert!(translate(Language::Fr, key, &[]).contains(APP)); + } + + #[test] + fn the_name_of_the_application_is_the_caller_s_where_it_gives_one() { + let params = [("app", Value::from("autre"))]; + + assert_eq!(interpolate("{{app}} {{ app }}", ¶ms), "autre autre"); + } + + /// A reference's words are keys like the others, under its own name, in both languages. + #[test] + fn each_reference_gives_its_words() { + for (id, french, english) in REFERENCES { + for (json, language) in [(french, Language::Fr), (english, Language::En)] { + let words = flatten(json); + assert!(!words.is_empty(), "{id}"); + for (path, text) in words { + let key = format!("tools.{id}.words.{path}"); + assert_eq!(language.catalogue().get(&key), Some(&text), "{key}"); + } + } + } + } + + #[test] + fn a_catalogue_s_paths_are_its_nested_names() { + let flat = flatten(r#"{"a": {"b": "x", "c": {"d": "y"}}, "e": "z", "f": 3}"#); + let mut paths: Vec<(&str, &str)> = flat + .iter() + .map(|(path, text)| (path.as_str(), text.as_str())) + .collect(); + paths.sort_unstable(); + + assert_eq!(paths, [("a.b", "x"), ("a.c.d", "y"), ("e", "z")]); + } } diff --git a/crates/i18n/src/plural.rs b/crates/i18n/src/plural.rs index 05dc37d9c..6894e5b31 100644 --- a/crates/i18n/src/plural.rs +++ b/crates/i18n/src/plural.rs @@ -212,4 +212,78 @@ mod tests { assert!(broken.is_empty(), "{broken:#?}"); } + + #[test] + fn each_language_has_its_categories() { + for (count, english, french) in [ + (0.0, "other", "one"), + (1.0, "one", "one"), + (-1.0, "one", "one"), + (1.5, "other", "one"), + (1.999, "other", "one"), + (2.0, "other", "other"), + (999_999.0, "other", "other"), + (1_000_000.0, "other", "many"), + (1_000_000.5, "other", "other"), + (1_500_000.0, "other", "other"), + (2_000_000.0, "other", "many"), + ] { + assert_eq!(category(count, Language::En), english, "{count}"); + assert_eq!(category(count, Language::Fr), french, "{count}"); + } + } + + #[test] + fn a_name_may_hold_figures_and_an_underscore_and_nothing_else() { + let read = + |source: &str, name: &str| expand(source, &[(name, Value::Number(3.0))], Language::En); + + for name in ["a", "a_b", "_", "n2"] { + assert_eq!(read(&format!("{{{name}, plural, other {{#}}}}"), name), "3"); + } + for source in [ + "{, plural, other {#}}", + "{a-b, plural, other {#}}", + "{a b, plural, other {#}}", + ] { + assert_eq!(read(source, "a"), source); + } + } + + /// `select`, a block with no branch after its kind, a brace that opens nothing. + #[test] + fn what_is_no_plural_is_left_as_written() { + for source in [ + "{a, select, other {#}}", + "{a, plural}", + "{a}", + "{", + "a } b", + "{a, plurals, other {#}}", + ] { + assert_eq!(of(source, 1.0, Language::En), source); + } + } + + #[test] + fn a_block_is_found_after_braces_that_are_none() { + assert_eq!( + of("{x} {{y}} {count,plural,other{#}} {z}", 4.0, Language::En), + "{x} {{y}} 4 {z}" + ); + } + + /// Braces inside a branch are its text; a branch without a selector is none. + #[test] + fn a_branch_holds_what_its_braces_enclose() { + assert_eq!( + of("{count, plural, other {# of {{total}}}}", 2.0, Language::En), + "2 of {{total}}" + ); + assert_eq!( + of("{count, plural, {lost} other {#}}", 2.0, Language::En), + "2" + ); + assert_eq!(of("{count, plural, one {#}}", 2.0, Language::En), ""); + } } diff --git a/crates/i18n/src/time.rs b/crates/i18n/src/time.rs index be8a6f773..0f51d150a 100644 --- a/crates/i18n/src/time.rs +++ b/crates/i18n/src/time.rs @@ -195,4 +195,123 @@ mod tests { assert_eq!(read(later(2 * 60)), "dans 2 h"); assert_eq!(read(later(3 * 24 * 60)), "dans 3 j"); } + + fn seconds_ago(seconds: i64) -> (DateTime, DateTime) { + let now: DateTime = "2026-11-09T12:00:00Z".parse().unwrap(); + (now - chrono::TimeDelta::seconds(seconds), now) + } + + /// Each unit from its first whole one, the gap rounded. + #[test] + fn a_label_changes_unit_where_it_rounds_to_one() { + const MINUTE: i64 = 60; + const HOUR: i64 = 60 * MINUTE; + for (seconds, text) in [ + (0, "just now"), + (29, "just now"), + (30, "1 min ago"), + (89, "1 min ago"), + (90, "2 min ago"), + (59 * MINUTE, "59 min ago"), + (HOUR, "1h ago"), + (23 * HOUR + 29 * MINUTE, "23h ago"), + (23 * HOUR + 30 * MINUTE, "1d ago"), + (36 * HOUR, "2d ago"), + ] { + let (at, now) = seconds_ago(seconds); + assert_eq!(relative(at, now).text(Language::En), text, "{seconds}"); + } + } + + #[test] + fn a_short_label_changes_unit_at_its_first_whole_one() { + const MINUTE: i64 = 60; + const HOUR: i64 = 60 * MINUTE; + const DAY: i64 = 24 * HOUR; + let read = |seconds| { + let (at, now) = seconds_ago(seconds); + short(at, now).text(Language::En) + }; + for (seconds, text) in [ + (29, "now"), + (30, "1 min"), + (59 * MINUTE, "59 min"), + (HOUR, "1 h"), + (23 * HOUR + 29 * MINUTE, "23 h"), + (23 * HOUR + 30 * MINUTE, "yesterday"), + (2 * DAY, "2 d"), + (6 * DAY, "6 d"), + (7 * DAY, "1 wk"), + (29 * DAY, "4 wk"), + (30 * DAY, "1 mo"), + (364 * DAY, "12 mo"), + (365 * DAY, "1 y"), + ] { + assert_eq!(read(seconds), text, "{seconds}"); + } + } + + /// Past the last day, by the day it falls on and not by how many hours away it is. + #[test] + fn a_short_expiry_changes_unit_at_its_first_whole_one() { + let now: DateTime = "2026-11-09T09:00:00Z".parse().unwrap(); + let read = |minutes: i64| { + let at = now + chrono::TimeDelta::minutes(minutes); + short_expiry(at, now, &Paris).text(Language::En) + }; + for (minutes, text) in [ + (-1, "expired"), + (0, "expired"), + (1, "in 1 min"), + (59, "in 59 min"), + (60, "in 1 h"), + (24 * 60 - 1, "in 24 h"), + (24 * 60, "in 1 d"), + (38 * 60 - 1, "in 1 d"), + (38 * 60, "in 2 d"), + ] { + assert_eq!(read(minutes), text, "{minutes}"); + } + } + + #[test] + fn a_span_counts_whole_units_both_ways_and_none_under_a_minute() { + let read = |seconds: i64| { + let (at, now) = seconds_ago(seconds); + span(at, now).key + }; + for seconds in [-59, 0, 59] { + assert_eq!(read(seconds), keys::time::span::NOW, "{seconds}"); + } + for (seconds, past, future) in [ + ( + 60, + keys::time::span::past::MINUTES, + keys::time::span::future::MINUTES, + ), + ( + 3_600, + keys::time::span::past::HOURS, + keys::time::span::future::HOURS, + ), + ( + 86_400, + keys::time::span::past::DAYS, + keys::time::span::future::DAYS, + ), + ( + 2_629_746, + keys::time::span::past::MONTHS, + keys::time::span::future::MONTHS, + ), + ( + 31_556_952, + keys::time::span::past::YEARS, + keys::time::span::future::YEARS, + ), + ] { + assert_eq!((read(seconds), read(-seconds)), (past, future), "{seconds}"); + assert_ne!(read(seconds - 1), past, "{seconds}"); + } + } } From 791fec71d420d4d894dc13c8f2a1bd19a00990d1 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 08:52:28 +0100 Subject: [PATCH 64/95] Desktop: unit tests completed for the instance, dialogs and updates (#1797) Co-authored-by: Claude Opus 5.5 --- crates/app/src/arguments.rs | 27 +++++++++ crates/platform/src/dialog.rs | 14 +++++ crates/platform/src/instance.rs | 85 +++++++++++++++++++++++++--- crates/platform/src/links.rs | 22 +++++++ crates/platform/src/shortcuts.rs | 33 +++++++++-- crates/platform/src/updater/tests.rs | 57 +++++++++++++++++++ crates/platform/src/window.rs | 36 ++++++++++++ 7 files changed, 260 insertions(+), 14 deletions(-) diff --git a/crates/app/src/arguments.rs b/crates/app/src/arguments.rs index 60017d8f1..3498d80ac 100644 --- a/crates/app/src/arguments.rs +++ b/crates/app/src/arguments.rs @@ -63,4 +63,31 @@ mod tests { Some(PathBuf::from("p")) ); } + + #[test] + fn both_are_read_in_any_order_and_the_last_of_each_wins() { + let read = of(&[ + "--action", + "quit", + "--profile", + "a", + "--profile", + "b", + "--action", + "palette", + ]); + + assert_eq!(read.profile, Some(PathBuf::from("b"))); + assert_eq!(read.action.as_deref(), Some("palette")); + } + + /// The one after a flag is its value, whatever it looks like. + #[test] + fn a_flag_takes_the_argument_after_it() { + let read = of(&["--profile", "--action", "palette"]); + + assert_eq!(read.profile, Some(PathBuf::from("--action"))); + assert_eq!(read.action, None); + assert_eq!(of(&["--action"]), Arguments::default()); + } } diff --git a/crates/platform/src/dialog.rs b/crates/platform/src/dialog.rs index b7588ac06..60ba14ab1 100644 --- a/crates/platform/src/dialog.rs +++ b/crates/platform/src/dialog.rs @@ -85,4 +85,18 @@ mod tests { Some(PathBuf::from("export.devnotes")) ); } + + #[test] + fn a_dialog_that_filters_nothing_opens_as_any() { + let dialog = Fixed(PathBuf::from("a.json")); + + assert_eq!(dialog.open_of(&["json"]), Some(PathBuf::from("a.json"))); + } + + #[test] + fn no_dialog_reads_as_a_cancel() { + assert_eq!(NoDialog.open(), None); + assert_eq!(NoDialog.open_of(&["json"]), None); + assert_eq!(NoDialog.save("a.json"), None); + } } diff --git a/crates/platform/src/instance.rs b/crates/platform/src/instance.rs index 21cc4c18d..527275823 100644 --- a/crates/platform/src/instance.rs +++ b/crates/platform/src/instance.rs @@ -245,13 +245,82 @@ mod tests { } #[test] - fn only_our_two_messages_are_read() { - assert_eq!(Message::read("reveal\n"), Some(Message::Reveal)); - assert_eq!( - Message::read("action new-note\n"), - Some(Message::Action("new-note".to_string())) - ); - assert_eq!(Message::read("action \n"), None); - assert_eq!(Message::read("quit\n"), None); + fn a_message_reads_back_from_its_line() { + for message in [ + Message::Reveal, + Message::Action("new-note".to_owned()), + Message::Action("two words".to_owned()), + ] { + assert_eq!(Message::read(&message.line()), Some(message)); + } + assert_eq!(Message::read("reveal\r\n"), Some(Message::Reveal)); + } + + #[test] + fn anything_else_is_no_message() { + for line in [ + "", + "\n", + "quit\n", + "action\n", + "action \n", + "reveal now\n", + "Reveal\n", + "act palette\n", + ] { + assert_eq!(Message::read(line), None, "{line:?}"); + } + } + + /// Sent as bytes, as any process of the same user could. + #[test] + fn a_launch_that_sends_nothing_readable_leaves_the_next_ones_heard() { + let profile = tempfile::tempdir().unwrap(); + let (heard, hearing) = mpsc::channel(); + first(profile.path()) + .serve(move |message| heard.send(message).unwrap()) + .unwrap(); + let too_long = format!("action {}\n", "a".repeat(300)); + let said: [&[u8]; 4] = [b"", b"quit\n", &[0xff, 0xfe, b'\n'], too_long.as_bytes()]; + for bytes in said { + let name = socket_name(profile.path()).unwrap(); + let mut stream = + Stream::connect(name.to_ns_name::().unwrap()).unwrap(); + // Refused before its end, the pipe may already be closed. + let _ = stream.write_all(bytes); + } + + send(profile.path(), &Message::Reveal).unwrap(); + + let mut last = hearing.recv_timeout(Duration::from_secs(10)).unwrap(); + if let Message::Action(name) = &last { + assert!(name.len() < 256, "cut at the longest line"); + last = hearing.recv_timeout(Duration::from_secs(10)).unwrap(); + } + assert_eq!(last, Message::Reveal); + } + + #[test] + fn a_profile_let_go_is_taken_again() { + let profile = tempfile::tempdir().unwrap(); + + drop(first(profile.path())); + drop(first(profile.path())); + } + + #[test] + fn a_profile_s_folder_is_made_where_there_is_none() { + let parent = tempfile::tempdir().unwrap(); + let profile = parent.path().join("new").join("profile"); + + drop(first(&profile)); + assert!(profile.is_dir()); + } + + #[test] + fn with_nobody_to_hear_it_a_message_is_an_error() { + let profile = tempfile::tempdir().unwrap(); + + assert!(send(profile.path(), &Message::Reveal).is_err()); } } diff --git a/crates/platform/src/links.rs b/crates/platform/src/links.rs index f46b28f3f..e1aad744a 100644 --- a/crates/platform/src/links.rs +++ b/crates/platform/src/links.rs @@ -57,4 +57,26 @@ mod tests { } assert!(opened.0.borrow().is_empty()); } + + #[test] + fn a_desktop_that_opens_nothing_is_told_apart() { + assert!(!open(&crate::desktop::NoOpener, "https://exemple.fr")); + } + + #[test] + fn an_address_is_of_the_web_by_its_scheme_alone() { + for url in ["https://a", "http://a", "HTTPS://A", "https://"] { + assert!(is_web(url), "{url}"); + } + for url in [ + "//a", + "://a", + "httpsx://a", + "file://http://a", + "http:/a", + " https://a", + ] { + assert!(!is_web(url), "{url}"); + } + } } diff --git a/crates/platform/src/shortcuts.rs b/crates/platform/src/shortcuts.rs index cd96ad4c4..d6e0e1d64 100644 --- a/crates/platform/src/shortcuts.rs +++ b/crates/platform/src/shortcuts.rs @@ -199,12 +199,33 @@ mod tests { } #[test] - fn a_path_with_a_space_or_a_quote_stays_one_word() { - assert_eq!(shell_quoted("/usr/bin/devnotes"), "/usr/bin/devnotes"); - assert_eq!( - shell_quoted("/home/a b/Dev'Notes.AppImage"), - r"'/home/a b/Dev'\''Notes.AppImage'" - ); + fn a_path_is_one_word_for_a_shell() { + for (path, word) in [ + ("/usr/bin/devnotes", "/usr/bin/devnotes"), + ("/a-b_c.d+e:f=g@h%i,j", "/a-b_c.d+e:f=g@h%i,j"), + ("/home/a b/DevNotes", "'/home/a b/DevNotes'"), + ("/home/Dev'Notes", r"'/home/Dev'\''Notes'"), + ("/home/$a", "'/home/$a'"), + ("/home/é", "'/home/é'"), + ("", "''"), + ] { + assert_eq!(shell_quoted(path), word, "{path}"); + } + } + + #[test] + fn an_id_nobody_took_is_nothing() { + let (taken, _) = take_each(&wanted(), |_| Ok::<(), String>(())); + let active = Arc::new(Mutex::new(taken)); + + assert_eq!(action_of(&active, 0), None); + assert_eq!(action_of(&Active::default(), 1), None); + } + + #[test] + fn where_no_key_is_taken_nothing_is_said_to_be_missing() { + assert!(NoShortcuts.set(&wanted()).is_empty()); + assert_eq!(NoShortcuts.holder(), Holder::Application); } #[test] diff --git a/crates/platform/src/updater/tests.rs b/crates/platform/src/updater/tests.rs index 28eba6b05..3469bcf28 100644 --- a/crates/platform/src/updater/tests.rs +++ b/crates/platform/src/updater/tests.rs @@ -169,3 +169,60 @@ fn an_installation_that_cannot_update_offers_nothing() { assert_eq!(NoUpdater.check(), Ok(None)); assert!(NoUpdater.download(&|_| {}).is_err()); } + +#[test] +fn an_address_that_does_not_read_builds_no_client() { + let source = Source { + version: "1.0.0", + endpoint: "not an address", + public_key: KEY, + }; + + assert!(built(&source, true).is_none()); + assert!(!super::system(&source).is_available()); +} + +#[test] +fn whether_an_installation_updates_itself_is_what_it_was_built_with() { + for can_install in [true, false] { + let source = Source { + version: "1.0.0", + endpoint: "https://exemple.fr/latest.json", + public_key: KEY, + }; + assert_eq!( + built(&source, can_install).unwrap().is_available(), + can_install + ); + } +} + +#[test] +fn progress_never_goes_back_nor_past_a_hundred() { + let origin = serve("0.26.0", INSTALLER); + let updater = client(&origin, "0.25.0", KEY); + updater.check().unwrap(); + let said = std::cell::RefCell::new(Vec::new()); + + updater + .download(&|percent| said.borrow_mut().push(percent)) + .unwrap(); + + let said = said.into_inner(); + assert!( + said.is_sorted() && said.iter().all(|percent| *percent <= 100), + "{said:?}" + ); +} + +/// Nothing downloaded, the process goes on as it was. +#[test] +fn with_nothing_downloaded_nothing_is_installed() { + let origin = serve("0.26.0", INSTALLER); + let updater = client(&origin, "0.25.0", KEY); + updater.install_and_relaunch(); + updater.check().unwrap(); + + updater.install_and_relaunch(); + NoUpdater.install_and_relaunch(); +} diff --git a/crates/platform/src/window.rs b/crates/platform/src/window.rs index 909ee35c4..74d2d7a4a 100644 --- a/crates/platform/src/window.rs +++ b/crates/platform/src/window.rs @@ -97,4 +97,40 @@ mod tests { std::fs::write(&file, "{ not json").unwrap(); assert_eq!(read(&file), None); } + + /// The file as it was first written, for a window already placed. + #[test] + fn a_geometry_is_stored_under_its_own_names() { + let directory = tempfile::tempdir().unwrap(); + let file = directory.path().join("window.json"); + write(&file, &PLACED).unwrap(); + + let stored: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap(); + let expected = serde_json::json!({"x": 40.0, "y": 30.0, "width": 1200.0, "height": 800.0, "maximized": false}); + assert_eq!(stored, expected); + } + + #[test] + fn a_geometry_written_again_replaces_the_one_before() { + let directory = tempfile::tempdir().unwrap(); + let file = directory.path().join("window.json"); + write(&file, &PLACED).unwrap(); + let moved = Geometry { + x: -8.0, + maximized: true, + ..PLACED + }; + + write(&file, &moved).unwrap(); + assert_eq!(read(&file), Some(moved)); + } + + #[test] + fn a_geometry_is_written_nowhere_a_folder_cannot_be() { + let directory = tempfile::tempdir().unwrap(); + std::fs::write(directory.path().join("file"), "").unwrap(); + + assert!(write(&directory.path().join("file").join("window.json"), &PLACED).is_err()); + } } From 42d3d31185270eff3dc38a029e8e5c8b50a6a906 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 08:52:36 +0100 Subject: [PATCH 65/95] Notes: unit tests rewritten for the rich text and its Markdown (#1798) Co-authored-by: Claude Opus 5.5 --- crates/richtext/src/edit/tests.rs | 995 ++++++++++++++++++++++------- crates/richtext/src/escape.rs | 118 ++++ crates/richtext/src/history.rs | 67 +- crates/richtext/src/html.rs | 133 ++++ crates/richtext/src/inlines.rs | 214 ++++++- crates/richtext/src/picture.rs | 173 +++-- crates/richtext/src/read.rs | 173 +++++ crates/richtext/src/rules/tests.rs | 275 ++++++-- crates/richtext/src/table.rs | 204 +++++- crates/richtext/src/tree.rs | 178 ++++++ crates/richtext/src/write.rs | 8 + 11 files changed, 2159 insertions(+), 379 deletions(-) diff --git a/crates/richtext/src/edit/tests.rs b/crates/richtext/src/edit/tests.rs index d3c60217a..38e334ceb 100644 --- a/crates/richtext/src/edit/tests.rs +++ b/crates/richtext/src/edit/tests.rs @@ -1,344 +1,857 @@ -//! Each operation from Markdown to Markdown, the caret where the reference's editor leaves it. +//! Each operation from Markdown to Markdown, the caret written in it as `¦` and the two ends of a +//! selection as `‹` and `›`: what was read, and where the reference's editor leaves the caret. use super::*; use crate::{read, write}; -fn caret_at(path: &[usize], offset: usize) -> Selection { - caret(path.to_vec(), offset) +fn open(marked: &str) -> (Document, Selection) { + let mut document = read(marked); + if let Some(caret) = take(&mut document, '¦') { + return (document, Selection::caret(caret)); + } + let anchor = take(&mut document, '‹').unwrap(); + let head = take(&mut document, '›').unwrap(); + (document, Selection { anchor, head }) +} + +fn take(document: &mut Document, marker: char) -> Option { + for path in tree::leaves(document) { + let offset = text_of(document, &path) + .chars() + .position(|glyph| glyph == marker); + if let Some(offset) = offset { + cut(document, &path, offset..offset + 1); + return Some(at(path, offset)); + } + } + None +} + +fn text_of(document: &Document, path: &[usize]) -> String { + match tree::leaf(document, path).unwrap() { + Leaf::Inlines(content) => inlines::plain(content), + Leaf::Code(text) => text.clone(), + } +} + +fn shown(document: &Document, selection: &Selection) -> String { + let mut document = document.clone(); + let (start, end) = ordered(selection); + if start == end { + mark_place(&mut document, &start, "¦"); + } else { + mark_place(&mut document, &end, "›"); + mark_place(&mut document, &start, "‹"); + } + write(&document) +} + +fn mark_place(document: &mut Document, place: &Position, marker: &str) { + match tree::leaf_mut(document, &place.path) { + Some(LeafMut::Inlines(content)) => { + let marks = inlines::marks_at(content, place.offset); + let text = marker.to_owned(); + inlines::insert(content, place.offset, Inline::Text { text, marks }); + } + Some(LeafMut::Code(text)) => { + let byte = text + .char_indices() + .nth(place.offset) + .map_or(text.len(), |(at, _)| at); + text.insert_str(byte, marker); + } + None => panic!("the caret is on no text: {place:?}"), + } +} + +type Edit = fn(&mut Document, &Selection) -> Selection; + +#[track_caller] +fn each(edit: Edit, cases: &[(&str, &str)]) { + for (before, after) in cases { + let (mut document, selection) = open(before); + let selection = edit(&mut document, &selection); + assert_eq!(shown(&document, &selection), *after, "from {before:?}"); + } +} + +/// `before` typed in, the caret after it. +fn typed(before: &str, text: &str) -> String { + let (mut document, selection) = open(before); + let selection = insert_text(&mut document, &selection, text, &Marks::default()); + shown(&document, &selection) +} + +fn pasted(before: &str, html: &str) -> String { + let (mut document, selection) = open(before); + let selection = insert_document(&mut document, &selection, crate::from_html(html)); + shown(&document, &selection) +} + +fn marked(before: &str, edit: impl Fn(&mut Document, &Selection)) -> String { + let (mut document, selection) = open(before); + edit(&mut document, &selection); + write(&document) +} + +// What is selected + +#[test] +fn a_selection_reads_the_same_from_either_end() { + let (document, selection) = open("a‹b\n\nc›d"); + let backward = Selection { + anchor: selection.head.clone(), + head: selection.anchor.clone(), + }; + + assert_eq!(ordered(&selection), ordered(&backward)); + assert_eq!(selected_text(&document, &backward), "b\nc"); +} + +#[test] +fn the_text_selected_is_a_line_a_block() { + for (marked, text) in [ + ("‹a **b**› c", "a b"), + ("a‹b\n\n- c\n- d›e", "b\nc\nd"), + ("# ‹a\n\n```\nb\nc\n```\n\n> d›", "a\nb\nc\nd"), + ("x\n\n| ‹a | b› |\n| --- | --- |\n| c | d |\n\ny", "a\nb"), + ("a‹ \n›b", "\n"), + ("‹é›à", "é"), + ] { + let (document, selection) = open(marked); + assert_eq!(selected_text(&document, &selection), text, "{marked}"); + } +} + +#[test] +fn a_copy_keeps_the_markers_of_its_blocks_and_none_of_the_marks() { + for (marked, text) in [ + ("- ‹one\n- two›", "- one\n- two"), + ("3. ‹three\n4. four›", "3. three\n4. four"), + ("- [ ] ‹open\n- [x] done›", "- [ ] open\n- [x] done"), + ("- ‹one\n - nested\n- two›", "- one\n - nested\n- two"), + ("> ‹quoted\n>\n> again›", "> quoted\n> again"), + ("# ‹Title\n\n**bold** and `code`›", "Title\nbold and code"), + ("- ‹one \n broken\n- two›", "- one\n broken\n- two"), + ( + "- ‹one\n ```\n a\n b\n ```\n- two›", + "- one\n a\n b\n- two", + ), + ("- > ‹one\n >\n > two›", "- > one\n > two"), + ("> - ‹one\n> - two›", "> - one\n> - two"), + ("- ‹a\n- - b\n - c\n- d›", "- a\n- - b\n - c\n- d"), + ( + "- ‹a\n- | b | c |\n | --- | --- |\n- d›", + "- a\n- b\n c\n- d", + ), + ("‹a\n\n---\n\n![b](c)\n\nd›", "a\nd"), + ("‹a\n\n| b | c |\n| --- | --- |\n\nd›", "a\nb\nc\nd"), + ] { + let (document, selection) = open(marked); + assert_eq!(copied(&document, &selection), text, "{marked}"); + } +} + +#[test] +fn a_copy_cut_inside_items_keeps_their_numbers() { + let (document, selection) = open("1. first\n2. sec‹ond\n3. th›ird"); + + assert_eq!(copied(&document, &selection), "2. ond\n3. th"); +} + +#[test] +fn a_copy_within_one_item_is_its_text_alone() { + let (document, selection) = open("1. first\n2. ‹second›\n3. third"); + + assert_eq!(copied(&document, &selection), "second"); +} + +#[test] +fn copied_as_markdown_reads_back_to_the_same_blocks() { + for markdown in [ + "- ‹one **bold**\n- two›", + "3. ‹three\n4. four›", + "- [ ] ‹open\n- [x] done›", + "- ‹one\n - nested\n- two›", + "> ‹quoted›", + "# ‹Title\n\n**bold** and `code`›", + "‹a\n\n---\n\n```rust\nb\n```›", + ] { + let (document, selection) = open(markdown); + let copied = copied_markdown(&document, &selection); + assert_eq!(read(&copied), document, "{markdown} gave {copied}"); + } } -fn range(from: (&[usize], usize), to: (&[usize], usize)) -> Selection { - Selection { - anchor: at(from.0.to_vec(), from.1), - head: at(to.0.to_vec(), to.1), +#[test] +fn copied_as_markdown_the_first_and_the_last_block_are_cut() { + for (marked, markdown) in [ + ("1. first\n2. ‹second\n3. third›", "2. second\n3. third"), + ("a‹b\n\n# c›d", "b\n\n# c"), + ("```js\na‹b\nc›d\n```", "```js\nb\nc\n```"), + ("- a\n - b‹c\n- d›e", "- - c\n- d"), + ("> a‹b\n\nc›", "> b\n\nc"), + ("a **b‹c** d› e", "**c** d"), + ] { + let (document, selection) = open(marked); + assert_eq!(copied_markdown(&document, &selection), markdown, "{marked}"); } } +// Typing + +#[test] +fn text_is_typed_at_the_caret() { + assert_eq!(typed("a¦b", "xé"), "axé¦b"); + assert_eq!(typed("é¦b", "x"), "éx¦b"); + assert_eq!(typed("# a¦", "x"), "# ax¦"); + assert_eq!(typed("- a\n- b¦", "x"), "- a\n- bx¦"); + assert_eq!(typed("a¦", ""), "a¦"); +} + +#[test] +fn text_is_typed_over_what_is_selected() { + assert_eq!(typed("a‹bc›d", "x"), "ax¦d"); + assert_eq!(typed("a‹b\n\nc›d", "x"), "ax¦d"); + assert_eq!(typed("a‹bc›d", ""), "a¦d"); +} + #[test] -fn typing_writes_at_the_caret_with_its_marks_and_a_line_splits() { - let mut document = read("ab"); +fn text_is_typed_with_the_marks_given() { + let (mut document, selection) = open("ab¦"); let bold = Marks { bold: true, ..Marks::default() }; - let after = insert_text(&mut document, &caret_at(&[0], 2), "c", &bold); - assert_eq!(write(&document), "ab**c**"); - assert_eq!(after, caret_at(&[0], 3)); - let after = insert_text(&mut document, &after, "\nd", &Marks::default()); - assert_eq!(write(&document), "ab**c**\n\nd"); - assert_eq!(after, caret_at(&[1], 1)); -} - -#[test] -fn enter_splits_a_paragraph_and_a_heading_ends_into_a_paragraph() { - let mut document = read("# Titre\n\nabcd"); - let after = split(&mut document, &caret_at(&[1], 2)); - assert_eq!(write(&document), "# Titre\n\nab\n\ncd"); - assert_eq!(after, caret_at(&[2], 0)); - let after = split(&mut document, &caret_at(&[0], 5)); - assert_eq!(after, caret_at(&[1], 0)); - assert_eq!( - write(&document), - "# Titre\n\n\n\nab\n\ncd", - "an empty paragraph under it" + + let after = insert_text(&mut document, &selection, "c", &bold); + assert_eq!(shown(&document, &after), "ab**c¦**"); +} + +#[test] +fn each_line_typed_is_a_block_or_an_item() { + assert_eq!(typed("a¦b", "x\ny"), "ax\n\ny¦b"); + assert_eq!(typed("- a¦", "\nb"), "- a\n- b¦"); + assert_eq!(typed("a¦", "\n\nb"), "a\n\n\n\nb¦"); +} + +#[test] +fn lines_typed_in_a_code_block_stay_in_it() { + assert_eq!(typed("```\né¦b\n```", "x\ny"), "```\néx\ny¦b\n```"); + assert_eq!(typed("```\na¦\n```", "\n\n\nb"), "```\na\n\n\nb¦\n```"); +} + +#[test] +fn a_line_typed_in_a_cell_is_a_break() { + assert_eq!(typed("| a¦ |\n| --- |", "\nb"), "| a
    b¦ |\n| ------- |"); +} + +#[test] +fn shift_enter_is_a_break_inside_the_block() { + each( + hard_break, + &[ + ("a¦b", "a \n¦b"), + ("a‹b›c", "a \n¦c"), + ("- a¦b", "- a \n ¦b"), + ("```\na¦b\n```", "```\na\n¦b\n```"), + ], ); } +// Pasting a page + #[test] -fn enter_in_an_item_adds_one_and_in_an_empty_one_leaves_the_list() { - let mut document = read("- un\n- deux"); - let after = split(&mut document, &caret_at(&[0, 1, 0], 4)); - assert_eq!(after, caret_at(&[0, 2, 0], 0)); - let after = split(&mut document, &after); - assert_eq!(after, caret_at(&[1], 0)); - assert!(matches!(&document.blocks[1], Block::Paragraph(content) if content.is_empty())); - assert_eq!(write(&document), "- un\n- deux"); +fn one_paragraph_pasted_goes_into_the_text_with_its_marks() { + assert_eq!(pasted("a¦b", "x"), "a**x¦**b"); + assert_eq!(pasted("a‹b›c", "

    xy

    "), "axy¦c"); + assert_eq!(pasted("# a¦", "x"), "# a*x¦*"); + assert_eq!(pasted("- a¦", "x"), "- ax¦"); } #[test] -fn backspace_lifts_an_item_and_joins_two_paragraphs() { - let mut document = read("- un\n- deux\n- trois"); - let after = delete_backward(&mut document, &caret_at(&[0, 1, 0], 0)); - assert_eq!(write(&document), "- un\n\ndeux\n\n- trois"); - assert_eq!(after, caret_at(&[1], 0)); - let after = delete_backward(&mut document, &after); - assert_eq!(write(&document), "- undeux\n\n- trois"); - assert_eq!(after, caret_at(&[0, 0, 0], 2)); +fn blocks_pasted_go_between_the_two_halves() { + let page = "

    T

    • u
    "; + assert_eq!(pasted("a¦b", page), "a\n\n## T\n\n- u\n\n¦b"); + assert_eq!(pasted("a‹x›b", page), "a\n\n## T\n\n- u\n\n¦b"); + assert_eq!(pasted("a¦\n\nb", page), "a\n\n## T\n\n- u\n\n¦b"); + assert_eq!(pasted("x\n\n¦b", page), "x\n\n## T\n\n- u\n\n¦b"); } +/// An empty half is not kept, except the one to type in at the end. #[test] -fn tab_nests_an_item_under_the_one_above_and_shift_tab_takes_it_back() { - let mut document = read("- un\n- deux\n- trois"); - let after = sink_item(&mut document, &caret_at(&[0, 1, 0], 1)); - assert_eq!(write(&document), "- un\n - deux\n- trois"); - assert_eq!(after, caret_at(&[0, 0, 1, 0, 0], 1)); - let after = lift_item(&mut document, &after); - assert_eq!(write(&document), "- un\n- deux\n- trois"); - assert_eq!(after, caret_at(&[0, 1, 0], 1)); +fn blocks_pasted_leave_no_empty_paragraph_behind() { + let (mut document, _) = open("a¦"); + document.blocks = vec![Block::Paragraph(Vec::new())]; + let page = crate::from_html("

    T

    x

    "); + + let after = insert_document(&mut document, &caret(vec![0], 0), page); + assert_eq!(shown(&document, &after), "## T\n\nx\n\n¦"); } #[test] -fn a_selection_across_blocks_is_taken_out_and_its_ends_joined() { - let mut document = read("abc\n\n- un\n- deux\n\n---\n\nfin"); - let after = delete_selection(&mut document, &range((&[0], 1), (&[3], 1))); - assert_eq!(write(&document), "ain"); - assert_eq!(after, caret_at(&[0], 1)); +fn blocks_pasted_in_an_item_stay_in_the_list() { + assert_eq!( + pasted("- a¦b", "

    T

    x

    "), + "- a\n- ## T\n x\n\n ¦b", + ); } #[test] -fn a_mark_toggles_over_a_selection_across_two_paragraphs() { - let mut document = read("ab\n\ncd"); - let selection = range((&[0], 1), (&[1], 1)); - toggle_mark(&mut document, &selection, &Mark::Bold); - assert_eq!(write(&document), "a**b**\n\n**c**d"); - toggle_mark(&mut document, &selection, &Mark::Bold); - assert_eq!(write(&document), "ab\n\ncd"); +fn a_page_pasted_in_code_or_in_a_cell_is_its_markdown() { + assert_eq!(pasted("```\na¦\n```", "x"), "```\na**x**¦\n```"); + assert_eq!(pasted("| a¦ |\n| --- |", "

    x

    "), "| ax¦ |\n| --- |",); } +// Deleting what is selected + #[test] -fn headings_lists_and_quotes_come_and_go() { - let mut document = read("un"); - set_heading(&mut document, &caret_at(&[0], 0), Some(2)); - assert_eq!(write(&document), "## un"); - set_heading(&mut document, &caret_at(&[0], 0), None); - let after = toggle_list(&mut document, &caret_at(&[0], 1), ListKind::Bullet); - assert_eq!(write(&document), "- un"); - let after = toggle_list(&mut document, &after, ListKind::Ordered { start: 1 }); - assert_eq!(write(&document), "1. un"); - let after = toggle_list(&mut document, &after, ListKind::Ordered { start: 1 }); - assert_eq!(write(&document), "un"); - let after = toggle_quote(&mut document, &after); - assert_eq!(write(&document), "> un"); - toggle_quote(&mut document, &after); - assert_eq!(write(&document), "un"); +fn a_selection_inside_a_block_is_taken_out() { + each( + delete_selection, + &[ + ("a‹bc›d", "a¦d"), + ("‹abc›", "¦"), + ("```\na‹b\nc›d\n```", "```\na¦d\n```"), + ("a¦b", "a¦b"), + ], + ); } #[test] -fn a_task_is_ticked_and_the_selection_read_as_text() { - let mut document = read("- [ ] fait\n\nfin"); - toggle_task(&mut document, &[0], 0); - assert_eq!(write(&document), "- [x] fait\n\nfin"); - let text = selected_text(&document, &range((&[0, 0, 0], 2), (&[1], 2))); - assert_eq!(text, "it\nfi"); +fn a_selection_across_blocks_is_taken_out_and_its_ends_joined() { + each( + delete_selection, + &[ + ("a‹b\n\nc›d", "a¦d"), + ("a‹bc\n\n- un\n- deux\n\n---\n\nf›in", "a¦in"), + ("a‹b\n\n![x](y)\n\nc›d", "a¦d"), + ("# a‹b\n\nc›d", "# a¦d"), + ("a‹b\n\n```\nc›d\n```", "a¦d"), + ("```\na‹b\n```\n\nc›d", "```\na¦d\n```"), + ("- a‹b\n- c›d\n- e", "- a¦d\n- e"), + ("- a\n- b‹c\n\nd›e", "- a\n- b¦e"), + ("a‹b\n\n> c›d\n>\n> e", "a¦d\n\n> e"), + ("‹a\n\nb›", "¦"), + ], + ); } +/// A cell is emptied, never taken out of its row. #[test] -fn delete_joins_the_next_block_and_backspace_takes_a_rule_out() { - let mut document = read("ab\n\ncd"); - let after = delete_forward(&mut document, &caret_at(&[0], 2)); - assert_eq!(write(&document), "abcd"); - assert_eq!(after, caret_at(&[0], 2)); - let after = delete_forward(&mut document, &caret_at(&[0], 1)); - assert_eq!(write(&document), "acd"); - assert_eq!(after, caret_at(&[0], 1)); +fn a_selection_that_covers_cells_empties_them() { + each( + delete_selection, + &[ + ( + "| a‹b | c |\n| --- | --- |\n| d | e›f |", + "| a¦f | |\n| --- | --- |\n| | |", + ), + ( + "| a | b‹c |\n| --- | --- |\n| d | e |\n\nf›g", + "| a | b¦g |\n| --- | --- |\n| | |", + ), + ], + ); +} - let mut document = read("un\n\n---\n\ndeux"); - let after = delete_backward(&mut document, &caret_at(&[2], 0)); - assert_eq!(write(&document), "un\n\ndeux"); - assert_eq!(after, caret_at(&[1], 0)); +// Enter + +#[test] +fn enter_splits_a_paragraph() { + each( + split, + &[ + ("a¦b", "a\n\n¦b"), + ("a¦", "a\n\n¦"), + ("a‹b›c", "a\n\n¦c"), + ("**a¦b**", "**a**\n\n**¦b**"), + ], + ); } #[test] -fn a_heading_at_its_start_becomes_a_paragraph_and_a_break_is_typed() { - let mut document = read("## Titre"); - delete_backward(&mut document, &caret_at(&[0], 0)); - assert_eq!(write(&document), "Titre"); - let after = hard_break(&mut document, &caret_at(&[0], 2)); - assert_eq!(write(&document), "Ti \ntre"); - assert_eq!(after, caret_at(&[0], 3)); +fn enter_in_a_heading_keeps_its_level_and_at_its_end_opens_a_paragraph() { + each( + split, + &[ + ("## a¦b", "## a\n\n## ¦b"), + ("## a¦\n\nb", "## a\n\n¦\n\nb"), + ], + ); } #[test] -fn a_nested_item_lifted_takes_the_ones_after_it_along() { - let mut document = read("- un\n - a\n - b\n- deux"); - let after = lift_item(&mut document, &caret_at(&[0, 0, 1, 0, 0], 0)); - assert_eq!(write(&document), "- un\n- a\n - b\n- deux"); - assert_eq!(after, caret_at(&[0, 1, 0], 0)); +fn enter_in_an_item_adds_one_under_it() { + each( + split, + &[ + ("- a¦b\n- c", "- a\n- ¦b\n- c"), + ("1. a¦", "1. a\n2. ¦"), + ("- [x] a¦b", "- [x] a\n- [ ] ¦b"), + ("- a\n - b¦", "- a\n - b\n - ¦"), + ], + ); } #[test] -fn an_empty_line_at_a_quote_s_end_leaves_it_and_a_rule_is_inserted() { - let mut document = read("> cité"); - let after = split(&mut document, &caret_at(&[0, 0], 4)); - let after = split(&mut document, &after); - assert_eq!(after, caret_at(&[1], 0)); - assert_eq!(write(&document), "> cité"); - let after = insert_rule(&mut document, &after); - assert_eq!(after, caret_at(&[3], 0)); - assert!(matches!(document.blocks[2], Block::Rule)); +fn enter_in_a_second_paragraph_of_an_item_stays_in_it() { + each(split, &[("- a\n\n b¦c", "- a\n\n b\n\n ¦c")]); } #[test] -fn a_selection_inside_one_block_and_text_typed_over_it() { - let mut document = read("abcdef"); - let after = insert_text( - &mut document, - &range((&[0], 1), (&[0], 4)), - "X", - &Marks::default(), +fn enter_in_an_empty_item_leaves_the_list() { + each( + split, + &[ + ("- a\n- ¦", "- a\n\n¦"), + ("- a\n- ¦\n- b", "- a\n\n¦\n\n- b"), + ("- a\n - ¦", "- a\n- ¦"), + ("- ¦", "¦"), + ], ); - assert_eq!(write(&document), "aXef"); - assert_eq!(after, caret_at(&[0], 2)); } #[test] -fn a_page_pasted_keeps_its_marks_in_a_line_and_its_blocks_between_two_halves() { - let mut document = read("ab"); - let after = insert_document( - &mut document, - &caret_at(&[0], 1), - crate::from_html("gras"), +fn enter_in_an_empty_paragraph_of_a_quote_leaves_it() { + each( + split, + &[ + ("> a\n>\n> ¦", "> a\n\n¦"), + ("> ¦", "¦"), + ("> a¦", "> a\n>\n> ¦"), + ], ); - assert_eq!(write(&document), "a**gras**b"); - assert_eq!(after, caret_at(&[0], 5)); +} - let mut document = read("ab"); - let pasted = crate::from_html("

    Titre

    • un
    "); - insert_document(&mut document, &caret_at(&[0], 1), pasted); - assert_eq!(write(&document), "a\n\n## Titre\n\n- un\n\nb"); +#[test] +fn enter_in_a_cell_is_a_break() { + each(split, &[("| a¦b |\n| --- |", "| a
    ¦b |\n| ------- |")]); } #[test] -fn a_third_enter_at_the_end_of_a_code_block_leaves_it_for_a_paragraph() { - let mut document = read("```rust\nlet x = 1;\n```"); - let mut selection = caret_at(&[0], 10); +fn enter_in_a_code_block_is_a_line_of_it() { + each( + split, + &[ + ("```\na¦b\n```", "```\na\n¦b\n```"), + ("```\na\n¦\n\nb\n```", "```\na\n\n¦\n\nb\n```"), + ("```\na¦\n\n\n```", "```\na\n¦\n\n\n```"), + ], + ); +} + +#[test] +fn a_third_enter_at_the_end_of_a_code_block_leaves_it() { + let (mut document, mut selection) = open("```rust\na¦\n```"); for _ in 0..2 { selection = split(&mut document, &selection); - assert_eq!(selection.head.path, [0], "a blank line is code's"); + assert_eq!(selection.head.path, [0]); } selection = split(&mut document, &selection); - assert_eq!(selection, caret_at(&[1], 0)); - - insert_text(&mut document, &selection, "Après", &Marks::default()); - assert_eq!(write(&document), "```rust\nlet x = 1;\n```\n\nAprès"); -} -#[test] -fn blank_lines_inside_a_code_block_stay_in_it() { - let mut document = read("```\na\n\n\nb\n```"); - let after = split(&mut document, &caret_at(&[0], 4)); - assert_eq!(after.head.path, [0]); - assert_eq!(write(&document), "```\na\n\n\n\nb\n```"); + assert_eq!(shown(&document, &selection), "```rust\na\n```\n\n¦"); } #[test] -fn a_code_block_left_opens_a_paragraph_beside_it_in_its_item_or_its_quote() { - for (markdown, path, left) in [ - ("```\na\n```", vec![0], vec![1]), - ("- un\n\n ```\n a\n ```", vec![0, 0, 1], vec![0, 0, 2]), - ("> ```\n> a\n> ```", vec![0, 0], vec![0, 1]), +fn a_code_block_is_left_for_a_paragraph_beside_it() { + for (before, after) in [ + ("```\na¦\n```\n\nb", "```\na\n```\n\n¦\n\nb"), + ("- a\n ```\n b¦\n ```", "- a\n ```\n b\n ```\n ¦"), + ("> ```\n> a¦\n> ```", "> ```\n> a\n> ```\n>\n> ¦"), ] { - let mut document = read(markdown); - let after = leave_code(&mut document, &caret_at(&path, 1)).unwrap(); - assert_eq!(after, caret_at(&left, 0), "{markdown}"); + let (mut document, selection) = open(before); + let left = leave_code(&mut document, &selection).unwrap(); + assert_eq!(shown(&document, &left), after); } - assert_eq!(leave_code(&mut read("text"), &caret_at(&[0], 1)), None); + let (mut document, selection) = open("a¦"); + assert_eq!(leave_code(&mut document, &selection), None); } #[test] fn a_paragraph_left_empty_after_a_code_block_is_not_written() { - let mut document = read("```\na\n```"); - leave_code(&mut document, &caret_at(&[0], 1)); - assert_eq!(read(&write(&document)), read("```\na\n```")); + let (mut document, selection) = open("```\na¦\n```"); + leave_code(&mut document, &selection); + + assert_eq!(write(&document), "```\na\n```"); } -fn whole(document: &Document) -> Selection { - let leaves = tree::leaves(document); - let last = leaves.last().unwrap(); - let length = tree::leaf(document, last).unwrap().len(); - range((&leaves[0], 0), (last, length)) +// Items + +#[test] +fn an_item_lifted_at_the_top_leaves_the_list_cut_in_two() { + each( + lift_item, + &[ + ("- a\n- b¦b\n- c", "- a\n\nb¦b\n\n- c"), + ("- ¦a\n- b", "¦a\n\n- b"), + ("- a\n- ¦b", "- a\n\n¦b"), + ("- ¦a", "¦a"), + ("1. a\n2. ¦b\n - c", "1. a\n\n¦b\n\n- c"), + ("> - ¦a", "> ¦a"), + ("- a\n\n b¦\n- c", "a\n\nb¦\n\n- c"), + ("- a\n > b¦", "a\n\n> b¦"), + ("a¦", "a¦"), + ], + ); } #[test] -fn a_copy_keeps_the_markers_of_its_blocks_and_none_of_the_marks() { - let cases = [ - ("- one\n- two", "- one\n- two"), - ("3. three\n4. four", "3. three\n4. four"), - ("- [ ] open\n- [x] done", "- [ ] open\n- [x] done"), - ("- one\n - nested\n- two", "- one\n - nested\n- two"), - ("> quoted\n>\n> again", "> quoted\n> again"), - ("# Title\n\n**bold** and `code`", "Title\nbold and code"), - ]; - for (markdown, expected) in cases { - let document = read(markdown); - assert_eq!(copied(&document, &whole(&document)), expected, "{markdown}"); +fn a_nested_item_lifted_is_one_of_the_list_above_and_takes_the_ones_after_it() { + each( + lift_item, + &[ + ("- a\n - b¦b\n- c", "- a\n- b¦b\n- c"), + ("- a\n - b\n\n c¦", "- a\n- b\n\n c¦"), + ("- a\n - ¦b\n - c\n- d", "- a\n- ¦b\n - c\n- d"), + ("- a\n - b\n - ¦c", "- a\n - b\n- ¦c"), + ], + ); +} + +#[test] +fn an_item_sunk_goes_under_the_one_above() { + each( + sink_item, + &[ + ("- a\n- b¦\n- c", "- a\n - b¦\n- c"), + ("- a\n - b\n- c¦", "- a\n - b\n - c¦"), + ("- a\n 1. b\n- c¦", "- a\n 1. b\n - c¦"), + ("- a\n- b\n - c¦\n- d", "- a\n- b\n - c¦\n- d"), + ("- a\n- b\n\n c¦", "- a\n - b\n\n c¦"), + ], + ); +} + +#[test] +fn a_first_item_and_what_is_no_item_are_not_sunk() { + each(sink_item, &[("- a¦\n- b", "- a¦\n- b"), ("a¦", "a¦")]); +} + +// Backspace + +#[test] +fn backspace_takes_the_glyph_before_or_what_is_selected() { + each( + delete_backward, + &[ + ("aé¦b", "a¦b"), + ("a‹bc›d", "a¦d"), + ("```\na\n¦b\n```", "```\na¦b\n```"), + ("- a¦b", "- ¦b"), + ], + ); +} + +#[test] +fn backspace_at_a_block_s_start_joins_it_to_the_one_before() { + each( + delete_backward, + &[ + ("a\n\n¦b", "a¦b"), + ("# a\n\n¦b", "# a¦b"), + ("- a\n- b\n\n¦c", "- a\n- b¦c"), + ("> a\n\n¦b", "> a¦b"), + ("- a\n\n ¦b", "- a¦b"), + ("¦a", "¦a"), + ], + ); +} + +#[test] +fn backspace_at_an_item_s_start_lifts_it() { + each( + delete_backward, + &[("- a\n- ¦b", "- a\n\n¦b"), ("- a\n - ¦b", "- a\n- ¦b")], + ); +} + +#[test] +fn backspace_at_a_heading_s_start_makes_it_a_paragraph() { + each(delete_backward, &[("a\n\n## ¦b", "a\n\n¦b")]); +} + +#[test] +fn backspace_after_an_image_or_a_rule_takes_it_out() { + each( + delete_backward, + &[ + ("a\n\n---\n\n¦b", "a\n\n¦b"), + ("![x](y)\n\n¦b", "¦b"), + ("> ![x](y)\n\n¦b", "¦b"), + ("- a\n\n ---\n\n¦b", "- a\n\n¦b"), + ("a\n\n> ![x](y)\n\n¦b", "a\n\n¦b"), + ], + ); +} + +#[test] +fn backspace_at_the_start_of_a_cell_or_of_code_or_after_one_does_nothing() { + for before in [ + "a\n\n| ¦b |\n| --- |", + "a\n\n```\n¦b\n```", + "| a |\n| --- |\n\n¦b", + "```\na\n```\n\n¦b", + ] { + let (mut document, selection) = open(before); + let after = delete_backward(&mut document, &selection); + assert_eq!((document, after), open(before), "{before}"); } } +// Delete + #[test] -fn a_copy_cut_inside_items_keeps_their_numbers_and_within_one_item_its_text_alone() { - let document = read("1. first\n2. second\n3. third"); - let from_second = range((&[0, 1, 0], 3), (&[0, 2, 0], 2)); - assert_eq!(copied(&document, &from_second), "2. ond\n3. th"); - let within = range((&[0, 1, 0], 0), (&[0, 1, 0], 6)); - assert_eq!(copied(&document, &within), "second"); +fn delete_takes_the_glyph_after_or_what_is_selected() { + each( + delete_forward, + &[ + ("a¦éb", "a¦b"), + ("a‹bc›d", "a¦d"), + ("```\na¦\nb\n```", "```\na¦b\n```"), + ], + ); } #[test] -fn copied_as_markdown_reads_back_to_the_same_blocks() { - for markdown in [ - "- one **bold**\n- two", - "3. three\n4. four", - "- [ ] open\n- [x] done", - "- one\n - nested\n- two", - "> quoted", - "# Title\n\n**bold** and `code`", +fn delete_at_a_block_s_end_joins_the_next_onto_it() { + each( + delete_forward, + &[ + ("a¦\n\nb", "a¦b"), + ("a¦\n\n- b\n- c", "a¦b\n\n- c"), + ("a¦\n\n---\n\nb", "a¦\n\nb"), + ("```\na¦\n```\n\nb", "```\na¦\n```\n\nb"), + ("a¦\n\n![x](y)", "a¦\n\n![x](y)"), + ("a¦", "a¦"), + ], + ); +} + +#[test] +fn delete_never_joins_a_cell() { + for before in [ + "a¦\n\n| b |\n| --- |", + "| a¦ | b |\n| --- | --- |", + "| a¦ |\n| --- |\n\nb", ] { - let document = read(markdown); - let copied = copied_markdown(&document, &whole(&document)); - assert_eq!(read(&copied), document, "{markdown} gave {copied}"); + let (mut document, selection) = open(before); + let after = delete_forward(&mut document, &selection); + assert_eq!((document, after), open(before), "{before}"); } - let document = read("1. first\n2. second\n3. third"); - let from_second = range((&[0, 1, 0], 0), (&[0, 2, 0], 5)); +} + +// Marks + +#[test] +fn a_mark_is_put_over_a_selection_and_taken_off_it() { + let bold = |marked_text: &str| { + marked(marked_text, |document, selection| { + toggle_mark(document, selection, &Mark::Bold); + }) + }; + + assert_eq!(bold("a‹b\n\nc›d"), "a**b**\n\n**c**d"); + assert_eq!(bold("a‹**b**\n\n**c**›d"), "ab\n\ncd"); + assert_eq!(bold("a‹**b**c›"), "a**bc**"); + assert_eq!(bold("‹**a** \n**b**›"), "a \nb"); assert_eq!( - copied_markdown(&document, &from_second), - "2. second\n3. third" + bold("‹**a**\n\n```\nb\n```\n\n**c**›"), + "a\n\n```\nb\n```\n\nc" ); } -/// Shift+Tab from the middle of a line: the caret is still there. #[test] -fn a_lifted_item_keeps_the_caret_where_it_was_in_it() { - for (markdown, path, landed) in [ - ("- un\n- deux", vec![0, 1, 0], vec![1]), - ("- un\n\n deux\n- trois", vec![0, 0, 1], vec![1]), - ( - "- un\n - deux\n\n trois", - vec![0, 0, 1, 0, 1], - vec![0, 1, 1], - ), - ("- un\n > deux", vec![0, 0, 1, 0], vec![1, 0]), - ] { - let mut document = read(markdown); - let after = lift_item(&mut document, &caret_at(&path, 3)); - assert_eq!(after, caret_at(&landed, 3), "{markdown}"); - assert!(tree::leaf(&document, &landed).is_some(), "{markdown}"); +fn a_link_is_put_over_a_selection_and_taken_off_it() { + let link = |marked_text: &str, href: Option<&str>| { + marked(marked_text, |document, selection| { + set_mark( + document, + selection, + &Mark::Link(href.map(str::to_owned)), + true, + ); + }) + }; + + assert_eq!( + link("a ‹b› c", Some("https://a.fr")), + "a [b](https://a.fr) c" + ); + assert_eq!(link("a [‹b›](https://a.fr) c", None), "a b c"); +} + +// Blocks + +#[test] +fn each_paragraph_and_heading_selected_becomes_a_heading_or_a_paragraph() { + let heading = |marked_text: &str, level| { + marked(marked_text, |document, selection| { + set_heading(document, selection, level); + }) + }; + + assert_eq!(heading("a¦", Some(2)), "## a"); + assert_eq!(heading("## a¦", None), "a"); + assert_eq!(heading("‹a\n\n# b›\n\nc", Some(3)), "### a\n\n### b\n\nc"); + assert_eq!(heading("```\na¦\n```", Some(1)), "```\na\n```"); + assert_eq!(heading("| a¦ |\n| --- |", Some(1)), "| a |\n| --- |"); +} + +#[test] +fn a_paragraph_or_a_heading_becomes_a_list_of_one() { + each( + to_bullets, + &[("a¦b", "- a¦b"), ("# a¦", "- # a¦"), ("> a¦", "> - a¦")], + ); +} + +#[test] +fn a_list_of_another_kind_changes_kind_whole() { + each( + to_bullets, + &[("1. a\n2. b¦", "- a\n- b¦"), ("- [x] a¦", "- a¦")], + ); + each( + |document, selection| toggle_list(document, selection, ListKind::Task), + &[("- a¦\n- b", "- [ ] a¦\n- [ ] b")], + ); +} + +/// A numbered list is one from whatever number. +#[test] +fn a_list_of_the_kind_asked_is_undone_whole() { + each( + to_bullets, + &[ + ("- a\n- b¦\n- c", "a\n\nb¦\n\nc"), + ("- a\n\n b\n- c\n\n d¦", "a\n\nb\n\nc\n\nd¦"), + ("- a\n - b¦", "- a\n\n b¦"), + ("- a\n - b\n- c¦", "a\n\n- b\n\nc¦"), + ], + ); + each( + |document, selection| toggle_list(document, selection, ListKind::Ordered { start: 1 }), + &[("3. a¦", "a¦")], + ); +} + +#[test] +fn code_and_cells_become_no_list() { + for before in ["```\na¦\n```", "| a¦ |\n| --- |"] { + let (mut document, selection) = open(before); + let after = to_bullets(&mut document, &selection); + assert_eq!((document, after), open(before), "{before}"); } - let mut document = read("un"); - let before = caret_at(&[0], 1); - assert_eq!(lift_item(&mut document, &before), before); +} + +fn to_bullets(document: &mut Document, selection: &Selection) -> Selection { + toggle_list(document, selection, ListKind::Bullet) } #[test] -fn an_image_taken_out_with_its_quote_leaves_the_caret_at_its_line() { - let mut document = read("un\n\n> ![x](y)\n\ndeux"); - let after = delete_backward(&mut document, &caret_at(&[2], 0)); - assert_eq!(write(&document), "un\n\ndeux"); - assert_eq!(after, caret_at(&[1], 0)); +fn a_block_goes_into_a_quote_and_a_quote_is_undone() { + each( + toggle_quote, + &[ + ("a¦\n\nb", "> a¦\n\nb"), + ("- a\n- b¦", "> - a\n> - b¦"), + ("x\n\n> a\n>\n> - b¦", "x\n\na\n\n- b¦"), + ], + ); } #[test] -fn delete_leaves_the_caret_where_it_is() { - for (markdown, left) in [ - ("un\n\n---\n\ndeux", "un\n\ndeux"), - ("un\n\ndeux", "undeux"), - ] { - let mut document = read(markdown); - let after = delete_forward(&mut document, &caret_at(&[0], 2)); - assert_eq!(write(&document), left); - assert_eq!(after, caret_at(&[0], 2)); +fn a_task_is_ticked_and_unticked() { + let tick = |list: &[usize], item: usize| { + let mut document = read("a\n\n- [ ] b\n- [x] c"); + toggle_task(&mut document, list, item); + write(&document) + }; + + assert_eq!(tick(&[1], 0), "a\n\n- [x] b\n- [x] c"); + assert_eq!(tick(&[1], 1), "a\n\n- [ ] b\n- [ ] c"); + for (list, item) in [(&[0][..], 0), (&[1], 2), (&[2], 0), (&[], 0)] { + assert_eq!(tick(list, item), "a\n\n- [ ] b\n- [x] c"); } - let mut document = read("```\nun\n```\n\ndeux"); - let end = caret_at(&[0], 2); - assert_eq!(delete_forward(&mut document, &end), end); +} + +#[test] +fn a_paragraph_becomes_code_and_code_a_paragraph_its_lines_kept() { + each( + toggle_code_block, + &[ + ("a \nb¦", "```\na\nb¦\n```"), + ("```\n¦\n```", "¦"), + ("```js\na\n\nb¦\n```", "a \n \nb¦"), + ("# a¦", "# a¦"), + ], + ); + each( + |document, selection| set_code_block(document, selection, "js".to_owned()), + &[("**a**¦", "```js\na¦\n```"), ("# a¦", "# a¦")], + ); +} + +#[test] +fn a_fence_takes_a_language() { + let in_rust = |marked_text: &str| { + marked(marked_text, |document, selection| { + set_language(document, selection, "rust".to_owned()); + }) + }; + + assert_eq!(in_rust("```js\na¦\n```"), "```rust\na\n```"); + assert_eq!(in_rust("a¦"), "a"); +} + +#[test] +fn shift_tab_in_code_takes_a_level_off_the_caret_s_line() { + let outdent: Edit = |document, selection| outdent_code(document, selection, " "); + each( + outdent, + &[ + ("```\n a¦\n```", "```\na¦\n```"), + ("```\n a¦\n```", "```\n a¦\n```"), + ("```\n a¦\n```", "```\na¦\n```"), + ("```\n ¦ a\n```", "```\n¦a\n```"), + ( + "```\n a\n b¦\n c\n```", + "```\n a\nb¦\n c\n```", + ), + ("```\n a\n¦ b\n```", "```\n a\n¦b\n```"), + ("```\na¦\n b\n```", "```\na¦\n b\n```"), + ("a¦", "a¦"), + ], + ); + each( + |document, selection| outdent_code(document, selection, "\t"), + &[ + ("```\n\t\ta¦\n```", "```\n\ta¦\n```"), + ("```\n a¦\n```", "```\n a¦\n```"), + ], + ); +} + +#[test] +fn a_rule_takes_the_paragraph_s_place_what_follows_under_it() { + each( + replace_with_rule, + &[ + ("a\n\n¦b\n\nc", "a\n\n---\n\n¦b\n\nc"), + ("a¦", "---\n\n¦"), + ("- ¦a", "- \n ---\n ¦a"), + ], + ); +} + +#[test] +fn a_rule_goes_after_the_top_block() { + each( + insert_rule, + &[ + ("a¦\n\nb", "a\n\n---\n\n¦\n\nb"), + ("- a¦\n- b\n\nc", "- a\n- b\n\n---\n\n¦\n\nc"), + ], + ); } diff --git a/crates/richtext/src/escape.rs b/crates/richtext/src/escape.rs index 6d962d4c1..32421cbe6 100644 --- a/crates/richtext/src/escape.rs +++ b/crates/richtext/src/escape.rs @@ -92,3 +92,121 @@ fn is_entity(rest: &[char]) -> bool { lower.starts_with(|glyph: char| glyph.is_ascii_alphabetic()) && lower.chars().all(|glyph| glyph.is_ascii_alphanumeric()) } + +#[cfg(test)] +mod tests { + use super::*; + + fn escaped(text: &str) -> String { + escape(text, false) + } + + #[test] + fn a_star_is_escaped_where_it_could_open_or_close() { + for (text, expected) in [ + ("2 * 3", "2 * 3"), + ("a*b", r"a\*b"), + ("*a", r"\*a"), + ("a* b", r"a\* b"), + ("a *b", r"a \*b"), + ("* a", "* a"), + ] { + assert_eq!(escaped(text), expected, "{text}"); + } + } + + #[test] + fn an_underscore_inside_a_word_is_left() { + for (text, expected) in [ + ("a_b", "a_b"), + ("é_1", "é_1"), + ("a _ b", "a _ b"), + ("_a", r"\_a"), + ("a_", r"a\_"), + ("a_-", r"a\_-"), + ("-_a", r"-\_a"), + ] { + assert_eq!(escaped(text), expected, "{text}"); + } + } + + #[test] + fn a_tilde_is_escaped_where_it_could_strike() { + for (text, expected) in [ + ("~/.ssh", "~/.ssh"), + ("~ a", "~ a"), + ("a~", "a~"), + ("~a", r"\~a"), + ("~~", r"\~~"), + ] { + assert_eq!(escaped(text), expected, "{text}"); + } + } + + #[test] + fn a_tag_and_a_backslash_are_escaped_where_they_would_be_read() { + for (text, expected) in [ + ("a < b", "a < b"), + ("a b", "a -> b"), + (r"\*", r"\\\*"), + (r"\a", r"\a"), + (r"a\", r"a\"), + ("`", r"\`"), + ("[a]", r"\[a]"), + ] { + assert_eq!(escaped(text), expected, "{text}"); + } + } + + #[test] + fn an_ampersand_is_escaped_where_it_starts_an_entity() { + for text in ["&", "©", " ", "", "", "½"] { + assert_eq!(escaped(text), format!(r"\{text}")); + } + for text in [ + "a & b", "&", "&;", "&#;", "&#x;", "&#xg;", "a;", "&12;", "&a b;", "&a-b;", + ] { + assert_eq!(escaped(text), text); + } + } + + /// Braces that enclose no name on one line are text like another. + #[test] + fn a_field_is_left_as_typed_and_the_text_around_it_escaped() { + for (text, expected) in [ + ("{{a_}}", "{{a_}}"), + ("*{{*a*}}*", r"\*{{*a*}}\*"), + ("{{a}}{{_b}}", "{{a}}{{_b}}"), + ("{{*a*", r"{{\*a\*"), + ("{{*a*}", r"{{\*a\*}"), + ("{{*a*{b}}", r"{{\*a\*{b}}"), + ("{{*a\n*}}", "{{\\*a\n\\*}}"), + ("{{{*a*}}", "{{{*a*}}"), + ("{{*a{{*b*}}", r"{{\*a{{*b*}}"), + ] { + assert_eq!(escaped(text), expected, "{text}"); + } + } + + /// Of the line it starts alone. + #[test] + fn the_spaces_that_start_a_line_are_kept() { + for (text, starting, inside) in [ + ("\ta", " a", "\ta"), + ("\t\ta", " a", "\t\ta"), + ("a\tb", "a\tb", "a\tb"), + (" a", " a", " a"), + (" a", " a", " a"), + (" \ta", " a", " \ta"), + ("\t", " ", "\t"), + ] { + assert_eq!(escape(text, true), starting, "{text:?}"); + assert_eq!(escape(text, false), inside, "{text:?}"); + } + } +} diff --git a/crates/richtext/src/history.rs b/crates/richtext/src/history.rs index d94e594eb..7ba6aad54 100644 --- a/crates/richtext/src/history.rs +++ b/crates/richtext/src/history.rs @@ -47,20 +47,61 @@ mod tests { } } + fn at(offset: usize) -> Selection { + Selection::caret(Position { + path: vec![0], + offset, + }) + } + #[test] - fn a_transaction_undone_comes_back_with_its_selection_and_is_redone() { + fn a_transaction_is_undone_to_the_text_and_the_selection_before_it() { let mut history = History::default(); - let at = Selection::caret(Position { - path: vec![0], - offset: 2, - }); - history.record(¬e("ab"), &at); - let now = note("abc"); - let (before, selection) = history.undo((&now, &Selection::default())).unwrap(); - assert_eq!(before, note("ab")); - assert_eq!(selection, at); - let (after, _) = history.redo((&before, &selection)).unwrap(); - assert_eq!(after, now); - assert!(history.redo((&after, &selection)).is_none()); + history.record(¬e("ab"), &at(2)); + + let before = history.undo((¬e("abc"), &at(3))); + assert_eq!(before, Some((note("ab"), at(2)))); + assert_eq!(history.undo((¬e("ab"), &at(2))), None); + } + + #[test] + fn what_was_undone_is_redone_then_undone_again() { + let mut history = History::default(); + history.record(¬e("a"), &at(1)); + history.undo((¬e("ab"), &at(2))); + + assert_eq!( + history.redo((¬e("a"), &at(1))), + Some((note("ab"), at(2))) + ); + assert_eq!(history.redo((¬e("ab"), &at(2))), None); + assert_eq!( + history.undo((¬e("ab"), &at(2))), + Some((note("a"), at(1))) + ); + } + + #[test] + fn a_transaction_after_an_undo_lets_go_of_what_was_undone() { + let mut history = History::default(); + history.record(¬e("a"), &at(1)); + history.undo((¬e("ab"), &at(2))); + history.record(¬e("a"), &at(1)); + + assert_eq!(history.redo((¬e("ax"), &at(2))), None); + } + + #[test] + fn the_oldest_steps_are_let_go() { + let mut history = History::default(); + for step in 0..=STEPS { + history.record(¬e(&step.to_string()), &at(0)); + } + + let undone: Vec = std::iter::from_fn(|| history.undo((¬e("now"), &at(0)))) + .map(|(document, _)| document) + .collect(); + assert_eq!(undone.len(), STEPS); + assert_eq!(undone[STEPS - 1], note("1")); } } diff --git a/crates/richtext/src/html.rs b/crates/richtext/src/html.rs index cf9bef431..cf9a48883 100644 --- a/crates/richtext/src/html.rs +++ b/crates/richtext/src/html.rs @@ -577,4 +577,137 @@ mod tests { let html = "Version:0.9\r\nStartHTML:0000000105\r\ngras"; assert_eq!(crate::write(&from_html(html)), "**gras**"); } + + fn markdown(html: &str) -> String { + crate::write(&from_html(html)) + } + + #[test] + fn each_tag_that_is_formatting_is_kept_and_no_other() { + for tag in [ + "b", + "strong", + "i", + "em", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "ul", + "ol", + "blockquote", + "table", + ] { + assert!(formatted(&format!("<{tag}>a")), "{tag}"); + } + for tag in ["p", "span", "div", "s", "code", "pre", "li", "a"] { + assert!(!formatted(&format!("<{tag}>a")), "{tag}"); + } + assert!(!formatted("ac"), "code pastes as text"); + assert!(!formatted("
    ")); + } + + #[test] + fn each_inline_tag_is_its_mark_until_it_closes() { + for (html, expected) in [ + ("ab", "**a**b"), + ("ab", "**a**b"), + ("ab", "*a*b"), + ("ab", "*a*b"), + ("ab", "~~a~~b"), + ("ab", "~~a~~b"), + ("ab", "~~a~~b"), + ("ab", "`a`b"), + ("ab", "[a](u)b"), + ("ab", "ab"), + ("ab", "ab"), + ("abcd", "**a*b*c**d"), + ("abc", "**ab**c"), + ("abc", "**a*b***c"), + ("a
    b", "ab"), + ("abc", "**ab**c"), + ] { + assert_eq!(markdown(html), expected, "{html}"); + } + } + + #[test] + fn a_span_is_bold_by_its_weight_and_italic_by_its_slant() { + for (style, expected) in [ + ("font-weight:bold", "**a**"), + ("font-weight: 600", "**a**"), + ("font-weight:599", "a"), + ("font-weight:normal", "a"), + ("color:red; FONT-WEIGHT: 700;", "**a**"), + ("font-style: italic", "*a*"), + ("font-style:normal", "a"), + ("font-weight:bold;font-style:italic", "***a***"), + ("", "a"), + ] { + assert_eq!( + markdown(&format!("a")), + expected, + "{style}" + ); + } + assert_eq!(markdown("a"), "**a**"); + } + + #[test] + fn each_block_tag_is_its_block() { + for (html, expected) in [ + ("

    a

    ", "### a"), + ("
    a
    b", "###### a\n\nb"), + ("
    a
    b
    ", "a\n\nb"), + ("a

    b

    c", "a\n\nb\n\nc"), + ("
    • a

    b

    ", "- a\n\nb"), + ("
    1. a
    2. b
    c", "1. a\n2. b\n\nc"), + ("
    a
    b", "> a\n\nb"), + ("
    a\nb\n
    c", "```\na\nb\n```\n\nc"), + ("
    a
    b
    ", "```\na\nb\n```"), + ("

    a", "a"), + ] { + assert_eq!(markdown(html), expected, "{html}"); + } + } + + #[test] + fn spaces_collapse_as_a_page_shows_them_but_for_those_meant_to_stay() { + for (html, expected) in [ + ("

    a \n\t b

    ", "a b"), + ("

    a

    ", "a"), + ("

    a  b

    ", "a\u{a0}\u{a0}b"), + ("

    a
    b

    ", "a \nb"), + ("

    a

    b", "a\n\nb"), + ("
    a  b
    ", "```\na b\n```"), + ("

    a b

    ", "a **b**"), + ] { + assert_eq!(markdown(html), expected, "{html}"); + } + } + + #[test] + fn what_follows_a_block_is_out_of_it() { + for (html, expected) in [ + ( + "
    a
    b", + "| a |\n| --- |\n\n\nb", + ), + ("
    • a
    b", "- a\n\nb"), + ("
    a
    b", "> a\n\nb"), + ("

    a

    b", "a\n\nb"), + ] { + assert_eq!(markdown(html), expected, "{html}"); + } + } + + #[test] + fn what_is_never_shown_is_not_pasted() { + assert_eq!( + markdown("ta"), + "a" + ); + } } diff --git a/crates/richtext/src/inlines.rs b/crates/richtext/src/inlines.rs index 7cdd80e6d..38e80d945 100644 --- a/crates/richtext/src/inlines.rs +++ b/crates/richtext/src/inlines.rs @@ -179,51 +179,205 @@ mod tests { use super::*; fn bold(text: &str) -> Inline { - Inline::Text { - text: text.to_owned(), - marks: Marks { - bold: true, - ..Marks::default() - }, + let marks = Marks { + bold: true, + ..Marks::default() + }; + let text = text.to_owned(); + Inline::Text { text, marks } + } + + fn linked(text: &str, href: &str) -> Inline { + let marks = Marks { + link: Some(href.to_owned()), + ..Marks::default() + }; + let text = text.to_owned(); + Inline::Text { text, marks } + } + + #[test] + fn a_break_counts_one_and_reads_as_a_line_end() { + let content = [Inline::text("é"), Inline::HardBreak, bold("cd")]; + + assert_eq!(len(&content), 4); + assert_eq!(plain(&content), "é\ncd"); + assert!(Inline::text("").is_empty() && !Inline::HardBreak.is_empty()); + } + + #[test] + fn runs_are_split_at_a_char_each_half_with_its_marks() { + let content = [Inline::text("ab"), bold("cdé"), Inline::HardBreak]; + let whole = content.to_vec(); + + for (at, left) in [ + (0, vec![]), + (1, vec![Inline::text("a")]), + (2, vec![Inline::text("ab")]), + (4, vec![Inline::text("ab"), bold("cd")]), + (5, vec![Inline::text("ab"), bold("cdé")]), + (6, whole.clone()), + (9, whole.clone()), + ] { + let (before, after) = split(&content, at); + assert_eq!(before, left, "at {at}"); + let mut joined = [before, after].concat(); + normalize(&mut joined); + assert_eq!(joined, whole, "at {at}"); } } #[test] - fn a_run_splits_inside_and_joins_back() { - let mut content = vec![Inline::text("ab"), bold("cdé"), Inline::HardBreak]; - let (left, right) = split(&content, 3); - assert_eq!(left, vec![Inline::text("ab"), bold("c")]); - assert_eq!(right, vec![bold("dé"), Inline::HardBreak]); - insert(&mut content, 5, bold("!")); + fn a_run_goes_in_at_a_char_and_joins_one_of_its_marks() { + let mut content = vec![Inline::text("ab"), bold("c")]; + + insert(&mut content, 1, Inline::text("é")); + assert_eq!(content, [Inline::text("aéb"), bold("c")]); + insert(&mut content, 3, bold("x")); + assert_eq!(content, [Inline::text("aéb"), bold("xc")]); + insert(&mut content, 1, Inline::HardBreak); assert_eq!( content, - vec![Inline::text("ab"), bold("cdé!"), Inline::HardBreak] + [ + Inline::text("a"), + Inline::HardBreak, + Inline::text("éb"), + bold("xc") + ] ); - delete(&mut content, 1..4); + } + + #[test] + fn what_is_deleted_goes_and_the_runs_around_it_join() { + for (range, left) in [ + (1..4, vec![Inline::text("a"), bold("é"), Inline::HardBreak]), + ( + 0..0, + vec![Inline::text("ab"), bold("cdé"), Inline::HardBreak], + ), + (2..5, vec![Inline::text("ab"), Inline::HardBreak]), + (5..6, vec![Inline::text("ab"), bold("cdé")]), + (0..6, vec![]), + ] { + let mut content = vec![Inline::text("ab"), bold("cdé"), Inline::HardBreak]; + delete(&mut content, range.clone()); + assert_eq!(content, left, "{range:?}"); + } + let mut content = vec![Inline::text("a"), bold("b"), Inline::text("c")]; + delete(&mut content, 1..2); + assert_eq!(content, [Inline::text("ac")]); + } + + #[test] + fn runs_of_equal_marks_are_one_and_empty_ones_none() { + let mut content = vec![ + Inline::text(""), + bold("a"), + bold("b"), + Inline::text("c"), + bold(""), + Inline::text("d"), + Inline::HardBreak, + Inline::HardBreak, + ]; + normalize(&mut content); + assert_eq!( content, - vec![Inline::text("a"), bold("é!"), Inline::HardBreak] + [ + bold("ab"), + Inline::text("cd"), + Inline::HardBreak, + Inline::HardBreak + ] ); } #[test] - fn a_mark_toggles_over_a_range_and_typing_takes_the_one_before() { - let mut content = vec![Inline::text("hello")]; - set(&mut content, 1..3, &Mark::Bold, true); - assert!(has(&content, 1..3, &Mark::Bold)); - assert!(!has(&content, 0..3, &Mark::Bold)); - assert!(marks_at(&content, 3).bold); - assert!(!marks_at(&content, 1).bold); - set( - &mut content, - 0..5, - &Mark::Link(Some("https://a.fr".into())), - true, + fn typing_writes_with_the_marks_before_the_caret() { + let content = [Inline::text("ab"), bold("cd"), Inline::text("e")]; + let typed_bold = |at| marks_at(&content, at).bold; + + assert_eq!( + [0, 1, 2, 3, 4, 5].map(typed_bold), + [false, false, false, true, true, false] ); - assert!(marks_at(&content, 2).link.is_some()); assert!( - marks_at(&content, 5).link.is_none(), - "a link does not grow at its end" + marks_at(&[bold("a")], 0).bold, + "with nothing before, those after" ); + assert!(!marks_at(&[Inline::text("a"), Inline::HardBreak, bold("b")], 2).bold); + assert_eq!(marks_at(&[], 0), Marks::default()); + assert_eq!(marks_at(&[bold("a")], 4), Marks::default()); + } + + /// Text typed at a link's end is after it. + #[test] + fn a_link_grows_from_inside_alone() { + let content = [Inline::text("a"), linked("bc", "u"), linked("d", "v")]; + let link_at = |at| marks_at(&content, at).link; + + assert_eq!( + [0, 1, 2, 3, 4].map(link_at), + [None, None, Some("u".to_owned()), None, None] + ); + assert_eq!(marks_at(&content[1..], 0).link, Some("u".to_owned())); + } + + #[test] + fn a_range_wears_a_mark_where_every_char_of_it_does() { + let content = [Inline::text("a"), bold("b"), Inline::HardBreak, bold("c")]; + let has_bold = |range| has(&content, range, &Mark::Bold); + + assert!(has_bold(1..4), "a break wears any"); + assert!(has_bold(1..2) && has_bold(3..4) && has_bold(2..2)); + assert!(!has_bold(0..2) && !has_bold(0..4)); + assert!(!has(&content, 1..2, &Mark::Italic)); + } + + #[test] + fn each_mark_is_put_over_a_range_and_taken_off_it() { + let link = Mark::Link(Some("u".to_owned())); + for mark in [Mark::Bold, Mark::Italic, Mark::Strike, Mark::Code, link] { + let mut content = vec![Inline::text("abcd")]; + + set(&mut content, 1..3, &mark, true); + assert!(has(&content, 1..3, &mark), "{mark:?}"); + assert!(!has(&content, 0..2, &mark) && !has(&content, 2..4, &mark)); + assert_eq!(content.len(), 3); + + set(&mut content, 0..4, &mark, false); + assert_eq!(content, [Inline::text("abcd")], "{mark:?}"); + } + } + + #[test] + fn a_link_is_worn_by_its_own_address_and_none_by_no_link() { + let content = [linked("a", "u")]; + let to = |href: Option<&str>| Mark::Link(href.map(str::to_owned)); + + assert!(has(&content, 0..1, &to(Some("u")))); + assert!(!has(&content, 0..1, &to(Some("v"))) && !has(&content, 0..1, &to(None))); + assert!(has(&[Inline::text("a")], 0..1, &to(None))); + } + + #[test] + fn a_mark_is_put_on_text_alone() { + let mut content = vec![Inline::text("a"), Inline::HardBreak, Inline::text("b")]; + set(&mut content, 0..3, &Mark::Bold, true); + + assert_eq!(content, [bold("a"), Inline::HardBreak, bold("b")]); + } + + /// The first run after the caret says whether it is inside the link. + #[test] + fn a_caret_between_two_runs_of_one_link_is_inside_it() { + let mut second = linked("b", "u"); + if let Inline::Text { marks, .. } = &mut second { + marks.bold = true; + } + + let marks = marks_at(&[linked("a", "u"), second, Inline::text("c")], 1); + assert_eq!((marks.link.as_deref(), marks.bold), (Some("u"), false)); } } diff --git a/crates/richtext/src/picture.rs b/crates/richtext/src/picture.rs index e26a71cdc..41348666a 100644 --- a/crates/richtext/src/picture.rs +++ b/crates/richtext/src/picture.rs @@ -142,78 +142,179 @@ mod tests { #[test] fn the_width_is_read_and_written_back() { - let mut document = read_note(SIZED); + let document = read_note(SIZED); + assert_eq!(width(&document, &[1]), Some(50)); assert!(matches!( &document.blocks[1], Block::Image { src, .. } if src == "devnotes:drawing/a1" )); assert_eq!(write(&document), SIZED); + } + + #[test] + fn every_width_from_the_narrowest_to_the_widest_is_read() { + for (written, width_read) in [(9, None), (10, Some(10)), (100, Some(100)), (101, None)] { + let document = read_note(&format!("![a](devnotes:drawing/a1?w={written})")); + assert_eq!(width(&document, &[0]), width_read, "{written}"); + } + } + + #[test] + fn a_drawing_takes_a_width_and_gives_it_back() { + let mut document = read_note(SIZED); assert!(set_width(&mut document, &[1], Some(75))); assert!(!set_width(&mut document, &[1], Some(75)), "as it was"); assert!(write(&document).contains("devnotes:drawing/a1?w=75)")); - set_width(&mut document, &[1], None); + assert!(set_width(&mut document, &[1], None)); assert!(write(&document).contains("devnotes:drawing/a1)")); - assert!(!set_width(&mut document, &[0], Some(50)), "a paragraph"); } #[test] - fn what_is_not_a_width_is_left_as_written_and_the_drawing_still_found() { + fn what_is_no_drawing_takes_no_width() { + let mut document = read_note("text\n\n![a](https://a.fr/a.png?w=50)"); + + for path in [&[0][..], &[1], &[7], &[]] { + assert!(!set_width(&mut document, path, Some(50)), "{path:?}"); + assert_eq!(width(&document, path), None, "{path:?}"); + } + assert!(write(&document).contains("(https://a.fr/a.png?w=50)")); + } + + #[test] + fn what_is_not_a_width_is_left_as_written() { for query in ["w=5", "w=101", "w=large", "x=50", "w=50&x=1", "w="] { let written = format!("![a](devnotes:drawing/a1?{query})"); let document = read_note(&written); assert_eq!(width(&document, &[0]), None, "{query}"); assert_eq!(write(&document), written); } - assert_eq!(drawing_id("devnotes:drawing/a1?w=large"), Some("a1")); - assert_eq!(drawing_id("https://a.fr/a.png"), None); - let remote = "![a](https://a.fr/a.png?w=50)"; - let mut document = read_note(remote); - assert_eq!(width(&document, &[0]), None, "a query of its own"); - assert!(!set_width(&mut document, &[0], Some(50))); - assert_eq!(write(&document), remote); } #[test] - fn a_drag_stops_on_the_quarters_and_a_step_on_fives() { - let stopped = [23.0, 28.0, 51.4, 98.0, 140.0, 2.0, 61.0].map(width_near); - assert_eq!(stopped, [25, 25, 50, 100, 100, 10, 61]); - assert_eq!(width_beside(50, true), 55); - assert_eq!(width_beside(50, false), 45); - assert_eq!(width_beside(52, true), 55); - assert_eq!(width_beside(52, false), 50); - assert_eq!(width_beside(100, true), 100); - assert_eq!(width_beside(10, false), 10); + fn a_drawing_is_found_whatever_its_query() { + for (src, id) in [ + ("devnotes:drawing/a1", Some("a1")), + ("devnotes:drawing/a1?w=large", Some("a1")), + ("devnotes:drawing/a1?x=1?w=2", Some("a1")), + ("https://a.fr/a.png", None), + ("", None), + ] { + assert_eq!(drawing_id(src), id, "{src}"); + } + } + + #[test] + fn a_drag_stops_near_the_quarters() { + for (percent, stopped) in [ + (22.0, 25), + (21.9, 22), + (28.0, 25), + (28.1, 28), + (51.4, 50), + (72.0, 75), + (61.4, 61), + (61.5, 62), + (98.0, 100), + (140.0, 100), + (2.0, 10), + ] { + assert_eq!(width_near(percent), stopped, "{percent}"); + } + } + + #[test] + fn a_step_goes_to_the_next_multiple_of_five() { + for (width, narrower, wider) in [ + (50, 45, 55), + (52, 50, 55), + (49, 45, 50), + (100, 95, 100), + (10, 10, 15), + (12, 10, 15), + ] { + assert_eq!( + (width_beside(width, false), width_beside(width, true)), + (narrower, wider), + "{width}" + ); + } + } + + fn leaf(path: &[usize], offset: usize) -> Beside { + let path = path.to_vec(); + Beside::Leaf(Position { path, offset }) } #[test] fn the_caret_meets_the_image_then_the_text_past_it() { let document = read_note(SIZED); + assert_eq!(beside(&document, &[0], true), Some(Beside::Image(vec![1]))); - let leaf = |path: usize, offset| { - Some(Beside::Leaf(Position { - path: vec![path], - offset, - })) - }; - assert_eq!(beside(&document, &[1], true), leaf(2, 0)); - assert_eq!(beside(&document, &[1], false), leaf(0, 5)); + assert_eq!(beside(&document, &[2], false), Some(Beside::Image(vec![1]))); + assert_eq!(beside(&document, &[1], true), Some(leaf(&[2], 0))); + assert_eq!(beside(&document, &[1], false), Some(leaf(&[0], 5))); + } + + #[test] + fn past_the_ends_there_is_nothing_to_meet() { + let document = read_note(SIZED); + + assert_eq!(beside(&document, &[0], false), None); assert_eq!(beside(&document, &[2], true), None); - let ruled = read_note("a\n\n---\n\nb"); - assert_eq!(beside(&ruled, &[0], true), leaf(2, 0)); + assert_eq!(beside(&document, &[9], true), None); } #[test] - fn removed_it_leaves_the_text_and_never_an_empty_note() { + fn a_rule_is_stepped_over_and_an_item_gone_into() { + let ruled = read_note("ab\n\n---\n\n---\n\n- c"); + assert_eq!(beside(&ruled, &[0], true), Some(leaf(&[3, 0, 0], 0))); + assert_eq!(beside(&ruled, &[3, 0, 0], false), Some(leaf(&[0], 2))); + } + + #[test] + fn an_image_removed_leaves_the_caret_in_the_text_before_it() { let mut document = read_note(SIZED); let selection = remove(&mut document, &[1]); + assert_eq!(write(&document), "avant\n\naprès"); - assert_eq!(selection.head.path, [0]); - assert_eq!(selection.head.offset, 5); + assert_eq!( + selection, + Selection::caret(Position { + path: vec![0], + offset: 5 + }) + ); + } + + #[test] + fn an_image_removed_first_leaves_the_caret_in_the_text_after_it() { + for markdown in [ + "![a](b)\n\naprès", + "> ![a](b)\n\naprès", + "![a](b)\n\n![c](d)\n\naprès", + ] { + let mut document = read_note(markdown); + let path = if markdown.starts_with('>') { + vec![0, 0] + } else { + vec![0] + }; + let selection = remove(&mut document, &path); + assert_eq!( + tree::leaf(&document, &selection.head.path).map(|leaf| leaf.len()), + Some(5), + "{markdown}" + ); + } + } + + #[test] + fn an_image_removed_alone_leaves_a_paragraph_to_type_in() { + let mut document = read_note("![a](devnotes:drawing/a1)"); + remove(&mut document, &[0]); - let mut alone = read_note("![a](devnotes:drawing/a1)"); - remove(&mut alone, &[0]); - assert_eq!(alone.blocks, [Block::Paragraph(Vec::new())]); + assert_eq!(document.blocks, [Block::Paragraph(Vec::new())]); } } diff --git a/crates/richtext/src/read.rs b/crates/richtext/src/read.rs index e51a5f624..372efd49a 100644 --- a/crates/richtext/src/read.rs +++ b/crates/richtext/src/read.rs @@ -444,4 +444,177 @@ mod tests { [Block::Paragraph(vec![Inline::text("ab")])] ); } + + fn only(markdown: &str) -> Block { + let mut blocks = read(markdown).blocks; + assert_eq!(blocks.len(), 1, "{markdown}"); + blocks.remove(0) + } + + fn run(text: &str, marks: Marks) -> Inline { + let text = text.to_owned(); + Inline::Text { text, marks } + } + + #[test] + fn marks_nest_and_end_where_they_end() { + let italic = Marks { + italic: true, + ..Marks::default() + }; + let both = Marks { + bold: true, + ..italic.clone() + }; + assert_eq!( + only("*a **b** c* d"), + Block::Paragraph(vec![ + run("a ", italic.clone()), + run("b", both), + run(" c", italic.clone()), + Inline::text(" d") + ]) + ); + assert_eq!( + only("*a *b* c* d"), + Block::Paragraph(vec![run("a b c", italic), Inline::text(" d")]) + ); + } + + #[test] + fn a_bare_address_is_a_link_to_itself_without_the_mark_that_ends_its_sentence() { + let links = |text: &str| -> Vec { + autolinks(text) + .into_iter() + .filter_map(|(_, link)| link) + .collect() + }; + + assert_eq!(links("voir https://a.fr."), ["https://a.fr"]); + assert_eq!( + links("(http://a.fr/b?c=d), puis https://e.fr!"), + ["http://a.fr/b?c=d", "https://e.fr"] + ); + assert_eq!(links("https://a.fr\nb"), ["https://a.fr"]); + assert!(links("a.fr, ftp://b.fr").is_empty()); + assert_eq!( + autolinks("a https://b c"), + [ + ("a ", None), + ("https://b", Some("https://b".to_owned())), + (" c", None) + ] + ); + } + + #[test] + fn an_address_inside_a_link_is_that_link_s() { + let link = Marks { + link: Some("https://b".to_owned()), + ..Marks::default() + }; + assert_eq!( + only("[https://a](https://b)"), + Block::Paragraph(vec![run("https://a", link)]) + ); + } + + #[test] + fn html_is_the_text_it_shows() { + for (html, text) in [ + ("a b > c", "a b > c"), + ("
    \na\n
    ", "a"), + ("a c", "a c"), + ] { + let shown = match only(html) { + Block::Paragraph(content) => crate::inlines::plain(&content), + other => panic!("{other:?}"), + }; + assert_eq!(shown, text, "{html}"); + } + } + + #[test] + fn an_image_among_words_stands_between_two_paragraphs() { + let blocks = read("a ![b *c*](d) e").blocks; + + assert_eq!(blocks.len(), 3); + assert!(matches!(&blocks[1], Block::Image { alt, src, .. } if alt == "b c" && src == "d")); + assert_eq!(read("![b](d)").blocks.len(), 1); + } + + #[test] + fn an_image_in_a_heading_or_a_cell_is_left_out() { + for markdown in ["# a ![b](c)", "| a ![b](c) |\n| --- |"] { + assert_eq!(read(markdown).blocks.len(), 1, "{markdown}"); + } + } + + #[test] + fn a_tight_item_s_text_comes_before_the_blocks_under_it() { + let Block::List { items, .. } = only("- a\n > b\n- c\n - d\n\n e") else { + panic!("a list"); + }; + + let kinds = |item: &Item| { + item.blocks + .iter() + .map(std::mem::discriminant) + .collect::>() + }; + let paragraph = std::mem::discriminant(&Block::Paragraph(Vec::new())); + assert_eq!(items.len(), 2); + assert!( + items + .iter() + .all(|item| item.blocks.len() == 2 && kinds(item)[0] == paragraph) + ); + } + + #[test] + fn a_box_makes_its_list_a_task_list() { + let Block::List { kind, items } = only("1. [x] a\n2. [ ] b") else { + panic!("a list"); + }; + + assert_eq!(kind, ListKind::Task); + assert_eq!( + items.iter().map(|item| item.checked).collect::>(), + [true, false] + ); + } + + #[test] + fn a_fence_gives_its_language_and_an_indented_block_none() { + let code = |markdown: &str| match only(markdown) { + Block::CodeBlock { language, text } => (language, text), + other => panic!("{other:?}"), + }; + + assert_eq!(code("```rust\na\n\n```"), ("rust".into(), "a\n".into())); + assert_eq!(code(" a\n b"), (String::new(), "a\nb".into())); + assert_eq!(code("```\n```"), (String::new(), String::new())); + } + + /// The quotes past the depth kept are read as the one around them. + #[test] + fn quotes_nested_too_deep_are_flattened_and_their_text_kept_in_order() { + let deep = "> ".repeat(MAX_QUOTES + 5); + let mut block = only(&format!("{deep}a\n>\n> b")); + + let mut depth = 0; + let mut texts = Vec::new(); + while let Block::Quote(inner) = block { + depth += 1; + for other in &inner[1..] { + if let Block::Paragraph(content) = other { + texts.push(crate::inlines::plain(content)); + } + } + block = inner.into_iter().next().unwrap(); + } + assert_eq!(depth, MAX_QUOTES); + assert_eq!(block, Block::Paragraph(vec![Inline::text("a")])); + assert_eq!(texts, ["b"]); + } } diff --git a/crates/richtext/src/rules/tests.rs b/crates/richtext/src/rules/tests.rs index d39627a70..59d9a0e15 100644 --- a/crates/richtext/src/rules/tests.rs +++ b/crates/richtext/src/rules/tests.rs @@ -4,55 +4,254 @@ use super::*; use crate::model::{Marks, Position}; use crate::{read, write}; -/// What a fresh Note holds after `typed`, each rule applied as it closes. -fn typed(typed: &str) -> String { - let mut document = read(""); - document.blocks.push(Block::Paragraph(Vec::new())); - let mut selection = Selection::caret(Position { - path: vec![0], - offset: 0, - }); - for glyph in typed.chars() { - selection = edit::insert_text( - &mut document, - &selection, - &glyph.to_string(), - &Marks::default(), - ); +/// What `markdown` holds once `text` is typed at the end of its last text, each rule applied as +/// it closes. +fn typed_in(markdown: &str, text: &str) -> Document { + let mut document = read(markdown); + if document.blocks.is_empty() { + document.blocks.push(Block::Paragraph(Vec::new())); + } + let path = tree::leaves(&document).pop().unwrap(); + let offset = tree::leaf(&document, &path).unwrap().len(); + let mut selection = Selection::caret(Position { path, offset }); + for glyph in text.chars() { + let glyph = glyph.to_string(); + selection = edit::insert_text(&mut document, &selection, &glyph, &Marks::default()); if let Some(applied) = after_typing(&mut document, &selection) { selection = applied.selection; } } - write(&document) + document +} + +fn typed(text: &str) -> String { + write(&typed_in("", text)) +} + +/// Read back, what was typed is one paragraph of that text. +fn stays(text: &str) -> bool { + let expected = Block::Paragraph(vec![Inline::text(text)]); + typed_in("", text).blocks == [expected] +} + +#[test] +fn a_paragraph_s_start_becomes_the_block_it_writes() { + for (text, markdown) in [ + ("# a", "# a"), + ("###### a", "###### a"), + ("> a", "> a"), + (" > a", "> a"), + ("- a", "- a"), + ("+ a", "- a"), + ("* a", "- a"), + ("1. a", "1. a"), + ("12. a", "12. a"), + ("[] a", "- [ ] a"), + ("[ ] a", "- [ ] a"), + ("[(] a", "- [ ] a"), + ("[x] a", "- [x] a"), + ("``` a", "```\na\n```"), + ("~~~ a", "```\na\n```"), + ("```sql a", "```sql\na\n```"), + ("---", "---"), + ("—-", "---"), + ("___ ", "---"), + ("*** ", "---"), + ] { + assert_eq!(typed(text), markdown, "{text}"); + } +} + +#[test] +fn a_start_that_writes_no_block_stays_text() { + for text in [ + "####### a", + "#a", + "a # b", + "a - b", + "1 . a", + "1) a", + ". a", + "a1. b", + "-a", + "--", + "__ ", + "** ", + "[y] a", + "[xx] a", + "```C a", + ">a", + "a > b", + "a ---", + "—— ", + ] { + let document = typed_in("", text); + assert!( + matches!(document.blocks.as_slice(), [Block::Paragraph(_)]), + "{text}: {document:?}" + ); + } +} + +/// The rule reads what is before the caret; what is after it stays in the block. +#[test] +fn a_rule_typed_before_a_text_keeps_it() { + let mut document = read("a"); + let start = Selection::caret(Position { + path: vec![0], + offset: 0, + }); + let hash = edit::insert_text(&mut document, &start, "# ", &Marks::default()); + + let applied = after_typing(&mut document, &hash).unwrap(); + assert_eq!(write(&document), "# a"); + assert_eq!(applied.selection, start); + assert_eq!(applied.mark, None); +} + +#[test] +fn a_block_rule_is_for_a_paragraph_alone() { + for markdown in ["# ", "| a |\n| --- |", "```\n```"] { + let after = typed_in(markdown, "# "); + let path = tree::leaves(&after).pop().unwrap(); + let text = match tree::leaf(&after, &path) { + Some(Leaf::Inlines(content)) => inlines::plain(content), + Some(Leaf::Code(text)) => text.clone(), + None => String::new(), + }; + assert!(text.ends_with("# "), "{markdown}: {text:?}"); + } +} + +#[test] +fn a_rule_in_an_item_is_of_that_item() { + for (text, markdown) in [ + ("- # a", "- # a"), + ("- [ ] a", "- [ ] a"), + ("- [x] a", "- [x] a"), + ("- 1. a", "1. a"), + ("- ```js a", "- ```js\n a\n ```"), + ] { + assert_eq!(typed(text), markdown, "{text}"); + } } #[test] -fn block_rules_turn_the_paragraph_into_what_its_start_writes() { - assert_eq!(typed("## Titre"), "## Titre"); - assert_eq!(typed("> cité"), "> cité"); - assert_eq!(typed("- un"), "- un"); - assert_eq!(typed("+ un"), "- un"); - assert_eq!(typed("3. trois"), "3. trois"); - assert_eq!(typed("[x] fait"), "- [x] fait"); - assert_eq!(typed("[ ] à faire"), "- [ ] à faire"); - assert_eq!(typed("```sql code"), "```sql\ncode\n```"); - assert_eq!(typed("---"), "---"); - assert_eq!(typed("####### sept"), "####### sept", "seven is no heading"); +fn a_mark_closed_at_the_caret_is_put_on_what_it_encloses() { + for (text, markdown) in [ + ("**a b**", "**a b**"), + ("du **gras** ici", "du **gras** ici"), + ("__a__", "**a**"), + ("un *mot*", "un *mot*"), + ("un _mot_", "un *mot*"), + ("~~a~~", "~~a~~"), + ("a `b` c", "a `b` c"), + ("a`b`", "a`b`"), + ("`a b `", "`a b `"), + ("**é**x", "**é**x"), + ] { + assert_eq!(typed(text), markdown, "{text}"); + } +} + +/// What is typed next does not wear it. +#[test] +fn the_mark_applied_is_named() { + for (text, mark) in [ + ("**a**", Mark::Bold), + ("*a*", Mark::Italic), + ("~~a~~", Mark::Strike), + ("`a`", Mark::Code), + ] { + let mut document = read(""); + document + .blocks + .push(Block::Paragraph(vec![Inline::text(text)])); + let end = Position { + path: vec![0], + offset: text.chars().count(), + }; + + let applied = after_typing(&mut document, &Selection::caret(end)).unwrap(); + assert_eq!(applied.mark, Some(mark), "{text}"); + assert_eq!( + applied.selection, + Selection::caret(Position { + path: vec![0], + offset: 1 + }) + ); + } } #[test] -fn marks_close_at_the_caret_and_spaced_emphasis_stays_as_typed() { - assert_eq!(typed("du **gras** ici"), "du **gras** ici"); - assert_eq!(typed("un *mot*"), "un *mot*"); - assert_eq!(typed("un _mot_"), "un *mot*"); - assert_eq!(typed("du ~~barré~~"), "du ~~barré~~"); - assert_eq!(typed("du `code`"), "du `code`"); - assert_eq!(typed("2 * 3 * 4"), "2 * 3 * 4"); - assert_eq!( - typed("snake_case_name"), +fn what_encloses_nothing_or_stands_in_a_word_stays_text() { + for text in [ + "2 * 3 * 4", + "2 *3 * 4", + "2 * 3* 4", + "a*b*", "snake_case_name", - "no italic inside a word" - ); + "a**b**", + "a~~b~~", + "****", + "** **", + "a * *", + "~~~~", + "~a~", + "`", + "``", + "``a`", + "** a", + "*a", + "__", + "_ _", + "**a*", + ] { + assert!(stays(text), "{text}: {:?}", typed_in("", text)); + } +} + +#[test] +fn nothing_is_read_inside_code() { + let mut document = read("`a *b`"); + let code = Marks { + code: true, + ..Marks::default() + }; + let end = Selection::caret(Position { + path: vec![0], + offset: 4, + }); + + let after = edit::insert_text(&mut document, &end, "*", &code); + assert!(after_typing(&mut document, &after).is_none()); + assert_eq!(write(&document), "`a *b*`"); +} + +#[test] +fn nothing_is_read_over_a_selection_or_off_a_text() { + let mut document = read("*a*"); + let place = |path: usize, offset| Position { + path: vec![path], + offset, + }; + document.blocks = vec![Block::Paragraph(vec![Inline::text("*a*")])]; + + let selected = Selection { + anchor: place(0, 0), + head: place(0, 3), + }; + assert!(after_typing(&mut document, &selected).is_none()); + assert!(after_typing(&mut document, &Selection::caret(place(4, 0))).is_none()); + let mut code = read("```\n*a*\n```"); + assert!(after_typing(&mut code, &Selection::caret(place(0, 3))).is_none()); +} + +/// Under a hundred billion billions: past that, a number has no start of its own. +#[test] +fn a_number_too_long_to_hold_starts_at_one() { + assert_eq!(typed(&format!("{}. a", "9".repeat(30))), "1. a"); } /// Enter has opened the next item already: its marker typed by habit is not a second one. diff --git a/crates/richtext/src/table.rs b/crates/richtext/src/table.rs index aa9d71d6c..a7bd0d120 100644 --- a/crates/richtext/src/table.rs +++ b/crates/richtext/src/table.rs @@ -139,40 +139,202 @@ mod tests { use super::*; use crate::{read, write}; + const TABLE: &str = "x\n\n| a | b |\n| --- | --- |\n| c | d |\n\ny"; + fn at(path: &[usize]) -> Selection { caret(path.to_vec()) } + /// Each row as its cells' text. + fn cells(document: &Document) -> Vec> { + document + .blocks + .iter() + .find_map(|block| match block { + Block::Table(rows) => Some(rows), + _ => None, + }) + .map(|rows| { + let row = + |row: &Vec| row.iter().map(|cell| crate::inlines::plain(cell)).collect(); + rows.iter().map(row).collect() + }) + .unwrap_or_default() + } + + type Edit = fn(&mut Document, &Selection) -> Selection; + + fn after(edit: Edit, row: usize, column: usize) -> (Vec>, Vec) { + let mut document = read(TABLE); + let selection = edit(&mut document, &at(&[1, row, column])); + (cells(&document), selection.head.path) + } + + #[test] + fn a_new_table_goes_after_the_top_block_three_rows_of_three_columns() { + for (markdown, path, landed) in [ + ("a\n\nb", vec![0], 1), + ("- a\n- b", vec![0, 1, 0], 1), + ("a", vec![7], 1), + ] { + let mut document = read(markdown); + let selection = insert(&mut document, &at(&path)); + assert_eq!(selection, at(&[landed, 0, 0])); + assert_eq!(cells(&document), vec![vec![String::new(); 3]; 3]); + assert!(matches!(document.blocks[landed], Block::Table(_))); + } + } + + #[test] + fn a_cell_is_its_table_its_row_and_its_column() { + let document = read("- | a | b |\n | --- | --- |\n | c | d |\n- e"); + + assert_eq!( + cell_of(&document, &[0, 0, 0, 1, 0]), + Some((vec![0, 0, 0], 1, 0)) + ); + for path in [&[0, 1, 0][..], &[0], &[]] { + assert_eq!(cell_of(&document, path), None, "{path:?}"); + } + } + + #[test] + fn a_row_is_added_under_the_caret_s() { + assert_eq!( + after(add_row_after, 0, 1), + ( + vec![ + vec!["a".into(), "b".into()], + vec![String::new(); 2], + vec!["c".into(), "d".into()] + ], + vec![1, 1, 1] + ) + ); + assert_eq!(after(add_row_after, 1, 0).1, [1, 2, 0]); + } + + #[test] + fn a_column_is_added_right_of_the_caret_s() { + assert_eq!( + after(add_column_after, 1, 0), + ( + vec![ + vec!["a".into(), String::new(), "b".into()], + vec!["c".into(), String::new(), "d".into()] + ], + vec![1, 1, 1] + ) + ); + assert_eq!(after(add_column_after, 0, 1).0[0], ["a", "b", ""]); + } + + /// Imported, a row can hold fewer cells than the others. #[test] - fn rows_and_columns_come_and_go_and_the_table_with_them() { - let mut document = read("| a | b |\n| --- | --- |\n| 1 | 2 |"); - let after = add_row_after(&mut document, &at(&[0, 1, 1])); - assert_eq!(after, at(&[0, 2, 1])); - let after = add_column_after(&mut document, &at(&[0, 0, 0])); - assert_eq!(after, at(&[0, 0, 1])); + fn a_column_is_added_at_the_end_of_a_row_too_short() { + let cell = |text: &str| vec![crate::Inline::text(text)]; + let mut document = Document { + blocks: vec![Block::Table(vec![ + vec![cell("a"), cell("b")], + vec![cell("c")], + ])], + }; + + add_column_after(&mut document, &at(&[0, 0, 1])); + assert_eq!(cells(&document), [vec!["a", "b", ""], vec!["c", ""]]); + delete_column(&mut document, &at(&[0, 0, 2])); + assert_eq!(cells(&document), [vec!["a", "b"], vec!["c", ""]]); + } + + #[test] + fn the_caret_s_row_goes_and_the_caret_is_in_the_one_that_takes_its_place() { assert_eq!( - write(&document), - "| a | | b |\n| --- | --- | --- |\n| 1 | | 2 |\n| | | |" + after(delete_row, 0, 1), + (vec![vec!["c".into(), "d".into()]], vec![1, 0, 1]) ); - delete_column(&mut document, &at(&[0, 0, 1])); - delete_row(&mut document, &at(&[0, 2, 0])); assert_eq!( - write(&document), - "| a | b |\n| --- | --- |\n| 1 | 2 |" + after(delete_row, 1, 1), + (vec![vec!["a".into(), "b".into()]], vec![1, 0, 1]) ); - delete(&mut document, &at(&[0, 1, 0])); - assert_eq!(write(&document), ""); } #[test] - fn tab_walks_the_cells_and_adds_a_row_past_the_last() { - let mut document = read("| a | b |\n| --- | --- |\n| 1 | 2 |"); - assert_eq!(step(&mut document, &at(&[0, 0, 1]), false), at(&[0, 1, 0])); - assert_eq!(step(&mut document, &at(&[0, 1, 0]), true), at(&[0, 0, 1])); - assert_eq!(step(&mut document, &at(&[0, 1, 1]), false), at(&[0, 2, 0])); + fn the_caret_s_column_goes_and_the_caret_is_in_the_one_that_takes_its_place() { assert_eq!( - write(&document), - "| a | b |\n| --- | --- |\n| 1 | 2 |\n| | |" + after(delete_column, 1, 0), + (vec![vec!["b".into()], vec!["d".into()]], vec![1, 1, 0]) ); + assert_eq!(after(delete_column, 1, 1).1, [1, 1, 0]); + } + + #[test] + fn the_last_row_or_the_last_column_takes_the_table_with_it() { + for edit in [delete_row as Edit, delete_column] { + let mut document = read("x\n\n| a |\n| --- |\n\ny"); + let selection = edit(&mut document, &at(&[1, 0, 0])); + assert_eq!(write(&document), "x\n\ny"); + assert_eq!(selection, at(&[1])); + } + } + + #[test] + fn a_table_deleted_leaves_the_caret_in_the_next_text() { + let mut document = read(TABLE); + assert_eq!(delete(&mut document, &at(&[1, 0, 1])), at(&[1])); + assert_eq!(write(&document), "x\n\ny"); + } + + #[test] + fn a_table_deleted_alone_leaves_a_paragraph_to_type_in() { + for markdown in ["| a |\n| --- |", "> | a |\n> | --- |"] { + let mut document = read(markdown); + let path = tree::leaves(&document).remove(0); + let selection = delete(&mut document, &at(&path)); + let left = tree::leaves(&document); + assert_eq!(left.len(), 1, "{markdown}"); + assert_eq!(selection, at(&left[0])); + } + } + + #[test] + fn tab_goes_to_the_next_cell_and_shift_tab_to_the_one_before() { + let mut document = read(TABLE); + for (from, back, to) in [ + ([0, 0], false, [0, 1]), + ([0, 1], false, [1, 0]), + ([1, 1], true, [1, 0]), + ([1, 0], true, [0, 1]), + ([0, 0], true, [0, 0]), + ] { + let from = at(&[1, from[0], from[1]]); + assert_eq!(step(&mut document, &from, back), at(&[1, to[0], to[1]])); + } + assert_eq!(cells(&document).len(), 2); + } + + #[test] + fn tab_past_the_last_cell_adds_a_row() { + let mut document = read(TABLE); + + assert_eq!(step(&mut document, &at(&[1, 1, 1]), false), at(&[1, 2, 0])); + assert_eq!(cells(&document)[2], ["", ""]); + } + + #[test] + fn out_of_a_table_nothing_is_done() { + let tab: Edit = |document, selection| step(document, selection, false); + for edit in [ + add_row_after as Edit, + add_column_after, + delete_row, + delete_column, + delete, + tab, + ] { + let mut document = read(TABLE); + let outside = at(&[0]); + assert_eq!(edit(&mut document, &outside), outside); + assert_eq!(document, read(TABLE)); + } } } diff --git a/crates/richtext/src/tree.rs b/crates/richtext/src/tree.rs index 20ee3a90c..6c871eae8 100644 --- a/crates/richtext/src/tree.rs +++ b/crates/richtext/src/tree.rs @@ -199,3 +199,181 @@ pub fn clamp(document: &Document, position: &Position) -> Position { offset: leaf(document, path).map_or(0, |found| found.len()), }) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::read; + + /// A paragraph, a list with a nested one, a quote, a table and code, an image and a rule among + /// them. + const NOTE: &str = "ab\n\n- c\n - d\n\n e\n\n---\n\n> f\n>\n> - g\n\n![h](i)\n\n| j | k |\n| --- | --- |\n| l | m |\n\n```\nnop\n```"; + + fn text(document: &Document, path: &[usize]) -> Option { + leaf(document, path).map(|found| match found { + Leaf::Inlines(content) => crate::inlines::plain(content), + Leaf::Code(text) => text.clone(), + }) + } + + #[test] + fn the_leaves_are_met_in_reading_order() { + let document = read(NOTE); + let met: Vec = leaves(&document) + .iter() + .map(|path| text(&document, path).unwrap()) + .collect(); + + assert_eq!( + met, + ["ab", "c", "d", "e", "f", "g", "j", "k", "l", "m", "nop"] + ); + } + + #[test] + fn a_path_that_ends_on_no_text_is_no_leaf() { + let mut document = read(NOTE); + for path in [ + &[][..], + &[9], + &[0, 0], + &[1], + &[1, 0], + &[1, 0, 9], + &[1, 9, 0], + &[2], + &[3], + &[3, 9], + &[4], + &[5], + &[5, 0], + &[5, 9, 0], + &[5, 0, 9], + &[5, 0, 0, 0], + &[6, 0], + ] { + assert!(leaf(&document, path).is_none(), "{path:?}"); + assert!(leaf_mut(&mut document, path).is_none(), "{path:?}"); + } + } + + #[test] + fn each_leaf_is_changed_by_its_path() { + let mut document = read(NOTE); + for path in leaves(&document) { + match leaf_mut(&mut document, &path) { + Some(LeafMut::Inlines(content)) => *content = vec![Inline::text("x")], + Some(LeafMut::Code(code)) => "x".clone_into(code), + None => panic!("{path:?}"), + } + assert_eq!(text(&document, &path).as_deref(), Some("x"), "{path:?}"); + } + } + + #[test] + fn a_leaf_s_length_counts_chars_and_breaks() { + let document = read("é \nb\n\n```\né\nb\n```"); + + assert_eq!( + [0, 1].map(|block| leaf(&document, &[block]).unwrap().len()), + [3, 3] + ); + assert!(!leaf(&document, &[0]).unwrap().is_empty()); + assert!(leaf(&read("-"), &[0, 0, 0]).unwrap().is_empty()); + } + + #[test] + fn a_block_is_found_with_the_blocks_it_sits_among() { + let mut document = read(NOTE); + for (path, among) in [ + (&[2][..], 7), + (&[1, 0, 2], 3), + (&[1, 0, 1, 0, 0], 1), + (&[3, 1], 2), + (&[3, 1, 0, 0], 1), + ] { + let found = block(&document, path).cloned(); + let (blocks, index) = siblings_mut(&mut document, path).unwrap(); + assert_eq!(blocks.len(), among, "{path:?}"); + assert_eq!(blocks.get(index), found.as_ref(), "{path:?}"); + } + } + + #[test] + fn a_cell_and_what_is_past_the_end_are_no_block() { + let mut document = read(NOTE); + for path in [ + &[][..], + &[7], + &[0, 0], + &[1, 0], + &[1, 9, 0], + &[1, 0, 3], + &[3, 2], + &[5, 0, 0], + &[9, 0], + ] { + assert!(block(&document, path).is_none(), "{path:?}"); + assert!(siblings_mut(&mut document, path).is_none(), "{path:?}"); + } + } + + #[test] + fn a_leaf_s_item_is_that_of_the_innermost_list() { + let document = read(NOTE); + for (path, found) in [ + (&[1, 0, 0][..], Some((vec![1], 0, vec![0]))), + (&[1, 0, 2], Some((vec![1], 0, vec![2]))), + (&[1, 0, 1, 0, 0], Some((vec![1, 0, 1], 0, vec![0]))), + (&[3, 1, 0, 0], Some((vec![3, 1], 0, vec![0]))), + (&[3, 0], None), + (&[0], None), + (&[1], None), + (&[1, 9, 0], None), + (&[9], None), + (&[], None), + ] { + assert_eq!(innermost_item(&document, path), found, "{path:?}"); + } + } + + #[test] + fn a_position_is_brought_back_on_a_text() { + let document = read(NOTE); + let clamped = |path: &[usize], offset| { + let found = clamp( + &document, + &Position { + path: path.to_vec(), + offset, + }, + ); + (found.path, found.offset) + }; + + assert_eq!(clamped(&[0], 1), (vec![0], 1)); + assert_eq!(clamped(&[0], 9), (vec![0], 2)); + assert_eq!(clamped(&[1], 9), (vec![1, 0, 0], 0)); + assert_eq!(clamped(&[2], 0), (vec![3, 0], 0)); + assert_eq!(clamped(&[3, 1, 0, 9], 0), (vec![5, 0, 0], 0)); + assert_eq!(clamped(&[], 4), (vec![0], 0)); + assert_eq!(clamped(&[9], 0), (vec![6], 3)); + } + + #[test] + fn a_document_without_text_holds_no_position() { + let alone = read("![a](b)"); + + assert!(leaves(&alone).is_empty()); + assert_eq!( + clamp( + &alone, + &Position { + path: vec![3], + offset: 1 + } + ), + Position::default() + ); + } +} diff --git a/crates/richtext/src/write.rs b/crates/richtext/src/write.rs index 97d06e84a..76787cbd5 100644 --- a/crates/richtext/src/write.rs +++ b/crates/richtext/src/write.rs @@ -424,6 +424,7 @@ mod tests { for (content, expected) in [ (vec![run("b", "a "), run("bi", "b")], "**a *b***"), (vec![run("bi", "a"), run("b", " b")], "***a* b**"), + (vec![run("bi", "a"), run("i", " b")], "***a** b*"), ( vec![run("i", "a "), run("bi", "b"), run("i", " c")], "*a **b** c*", @@ -450,6 +451,11 @@ mod tests { ¶graph(vec![run("b", "a"), Inline::HardBreak, run("b", "b")]), "**a** \n**b**", ); + let spaced = paragraph(vec![run("b", "a"), Inline::HardBreak, run("b", " b")]); + assert_eq!(write(&spaced), "**a** \n **b**"); + let tabbed = paragraph(vec![run("", "a"), Inline::HardBreak, run("", "\tb")]); + assert_eq!(write(&tabbed), "a \n b"); + written(¶graph(vec![run("bc", " "), run("b", "a")]), "**` `a**"); } /// `**a **b` is stars and letters, for Markdown. @@ -587,6 +593,8 @@ mod tests { ("- a\n\n 0. b", false), ("- a\n\n 1. ", false), ("- a\n\n - ", false), + ("- a\n\n - \n ---", false), + ("- \n ---\n - b", true), ("- > a\n\n b", false), ("- > a\n\n > b", false), ("- - a\n\n b", false), From aaeed0f5e78ca375c3d0a301f3924ffb9eda96f9 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 08:52:44 +0100 Subject: [PATCH 66/95] Request scripts: unit tests rewritten for the engine and its API (#1799) Co-authored-by: Claude Opus 5.5 --- crates/engine/src/http/scripts/engine.rs | 1753 ++++++++++++++++++---- 1 file changed, 1422 insertions(+), 331 deletions(-) diff --git a/crates/engine/src/http/scripts/engine.rs b/crates/engine/src/http/scripts/engine.rs index cacac9590..2a54f2bbb 100644 --- a/crates/engine/src/http/scripts/engine.rs +++ b/crates/engine/src/http/scripts/engine.rs @@ -307,9 +307,10 @@ impl Engine { mod tests { use super::*; use crate::http::scripts::model::{ - LayerScope, Phase, Script, ScriptBody, ScriptKind, ScriptLayer, ScriptLevel, ScriptRequest, - ScriptResponse, ScriptRow, WriteScope, + LayerScope, Phase, Script, ScriptBody, ScriptCookie, ScriptInfo, ScriptKind, ScriptLayer, + ScriptLevel, ScriptRequest, ScriptResponse, ScriptRow, TestResult, WriteScope, }; + use serde_json::json; #[derive(Default)] struct Seen { @@ -323,26 +324,19 @@ mod tests { impl Host for Fake { fn call(&mut self, kind: &str, payload: &str) -> String { let payload: serde_json::Value = serde_json::from_str(payload).unwrap(); - self.0 - .borrow_mut() - .calls - .push((kind.to_string(), payload.clone())); - match kind { + let answer = match kind { "send" if payload["method"] == "DELETE" => { - serde_json::json!({ "error": "refused", "code": "httpScriptProtected" }) - .to_string() + json!({ "error": "refused", "code": "httpScriptProtected" }) } - "send" => serde_json::json!({ "ok": { - "code": 200, - "reason": "OK", + "send" => json!({ "ok": { + "code": 200, "reason": "OK", "millis": 12, "size": 40, "headers": [{ "key": "Content-Type", "value": "application/json" }], - "body": serde_json::json!({ "url": payload["url"] }).to_string(), - "millis": 12, - "size": 40, - }}) - .to_string(), - _ => serde_json::json!({ "ok": [] }).to_string(), - } + "body": json!({ "url": payload["url"] }).to_string(), + }}), + _ => json!({ "ok": [] }), + }; + self.0.borrow_mut().calls.push((kind.to_string(), payload)); + answer.to_string() } fn log(&mut self, entry: LogEntry) { @@ -355,132 +349,195 @@ mod tests { (Engine::new(Box::new(Fake(Rc::clone(&seen)))).unwrap(), seen) } - fn script(id: &str, kind: ScriptKind, source: &str) -> Script { + /// `QuickJS` is given more stack than a test thread has: each test runs on a thread like the + /// host's. + fn hosted(test: impl FnOnce() -> T + Send + 'static) -> T { + std::thread::Builder::new() + .stack_size(2 * STACK) + .spawn(test) + .unwrap() + .join() + .unwrap_or_else(|panic| std::panic::resume_unwind(panic)) + } + + const SECONDS: Duration = Duration::from_secs(5); + + fn script(id: &str, source: &str) -> Script { Script { id: id.to_string(), level: ScriptLevel::Request, - kind, - name: "Payer".to_string(), + kind: ScriptKind::Before, + name: "Pay".to_string(), owner: None, source: source.to_string(), } } fn layer(scope: LayerScope, values: &[(&str, &str)]) -> ScriptLayer { + let values = values + .iter() + .map(|(key, value)| ((*key).to_string(), (*value).to_string())) + .collect(); ScriptLayer { scope, from: String::new(), - values: values - .iter() - .map(|(key, value)| ((*key).to_string(), (*value).to_string())) - .collect(), + values, + } + } + + fn row(key: &str, value: &str) -> ScriptRow { + ScriptRow { + key: key.to_string(), + value: value.to_string(), + ..ScriptRow::default() } } + /// A phase before the send: a `POST` of `{{baseUrl}}/pay?page=1`, on Staging. fn before(source: &str) -> Job { Job { phase: Phase::Before, - scripts: vec![script("request:before", ScriptKind::Before, source)], + scripts: vec![script("request:before", source)], request: ScriptRequest { method: "POST".to_string(), - url: "{{baseUrl}}/pay".to_string(), - headers: vec![ScriptRow { - key: "Accept".to_string(), - value: "application/json".to_string(), - ..ScriptRow::default() - }], + url: "{{baseUrl}}/pay?page=1".to_string(), + headers: vec![row("Accept", "application/json")], ..ScriptRequest::default() }, layers: vec![ - layer( - LayerScope::Environment, - &[("baseUrl", "https://api.example.com")], - ), - layer(LayerScope::Globals, &[("tenant", "acme")]), + layer(LayerScope::Data, &[("customer", "cus_1")]), + layer(LayerScope::Collection, &[("tenant", "near"), ("page", "2")]), + layer(LayerScope::Environment, &[("baseUrl", "https://api.test")]), + layer(LayerScope::Globals, &[("tenant", "far")]), ], environment: Some("Staging".to_string()), + info: ScriptInfo { + iteration: 2, + iteration_count: 5, + request_name: "Pay".to_string(), + request_id: Some("r1".to_string()), + }, ..Job::default() } } - fn after(source: &str, body: &str) -> Job { + fn cookie(name: &str, value: &str) -> ScriptCookie { + ScriptCookie { + name: name.to_string(), + value: value.to_string(), + ..ScriptCookie::default() + } + } + + /// A phase after the answer: a `402` whose body is `{"currency":"usd","items":[{"id":7}]}`. + fn after(source: &str) -> Job { Job { phase: Phase::After, - scripts: vec![script("request:tests", ScriptKind::Tests, source)], + scripts: vec![script("request:tests", source)], response: Some(ScriptResponse { code: 402, reason: "Payment Required".to_string(), - headers: vec![ScriptRow { - key: "Content-Type".to_string(), - value: "application/json".to_string(), - ..ScriptRow::default() - }], - body: body.to_string(), + headers: vec![ + row("Content-Type", "application/json"), + row("Vary", "a"), + row("vary", "b"), + ], + body: r#"{"currency":"usd","items":[{"id":7}]}"#.to_string(), millis: 203, - size: 40, - cookies: Vec::new(), + size: 37, + cookies: vec![cookie("sid", "42")], }), + cookies: vec![cookie("jar", "1")], ..before("") } } - /// `QuickJS` is given more stack than a test thread has: each test runs on a thread like the host's. - fn hosted(test: impl FnOnce() -> T + Send + 'static) -> T { - std::thread::Builder::new() - .stack_size(2 * STACK) - .spawn(test) - .unwrap() - .join() - .unwrap_or_else(|panic| std::panic::resume_unwind(panic)) + fn run(job: &Job) -> Outcome { + engine().0.run(job, SECONDS) } - const SECOND: Duration = Duration::from_secs(5); + fn failure(source: &str) -> ScriptFailure { + run(&before(source)).failure.unwrap() + } - fn run(source: &str) -> Outcome { - engine().0.run(&before(source), SECOND) + /// Each expression, and its value as JSON, said in the console. They run in order, in one + /// script. + fn hold(make: fn(&str) -> Job, cases: &'static [(&'static str, &'static str)]) { + hosted(move || { + let lines: Vec = cases + .iter() + .map(|(expression, _)| { + format!("console.log(String(JSON.stringify({expression})));") + }) + .collect(); + let (engine, seen) = engine(); + let outcome = engine.run( + &make(&lines.join( + " +", + )), + SECONDS, + ); + assert_eq!(outcome.failure, None); + let seen = seen.borrow(); + for (log, (expression, expected)) in seen.logs.iter().zip(cases) { + assert_eq!(log.text, *expected, "{expression}"); + } + assert_eq!(seen.logs.len(), cases.len()); + }); } - #[test] - fn a_before_script_changes_the_request_through_req_and_pm_request() { - hosted(|| { - let outcome = run("req.method = 'put'; - req.url = req.url + '?retry=1'; - req.headers.set('X-Signature', 'abc'); - pm.request.headers.add({ key: 'X-Trace', value: 1 }); - pm.request.body.update(JSON.stringify({ amount: 2 }));"); + fn tested(source: &'static str) -> Vec { + hosted(move || { + let outcome = run(&after(source)); assert_eq!(outcome.failure, None); - let request = outcome.request.unwrap(); - assert_eq!(request.method, "PUT"); - assert_eq!(request.url, "{{baseUrl}}/pay?retry=1"); - let keys: Vec<&str> = request.headers.iter().map(|row| row.key.as_str()).collect(); - assert_eq!(keys, ["Accept", "X-Signature", "X-Trace"]); - assert_eq!(request.headers[2].value, "1"); - assert_eq!(request.body.mode, "raw"); - assert_eq!(request.body.raw, "{\"amount\":2}"); + outcome.tests + }) + } + + /// Each assertion stands alone as a test: whether it holds. + fn judge(cases: &'static [(&'static str, bool)]) { + hosted(move || { + let tests: Vec = cases + .iter() + .map(|(assertion, _)| format!("test('t', () => {{ {assertion}; }});")) + .collect(); + let outcome = run(&after(&tests.join("\n"))); + assert_eq!((outcome.failure, outcome.tests.len()), (None, cases.len())); + for (test, (assertion, passed)) in outcome.tests.iter().zip(cases) { + assert_eq!(test.passed, *passed, "{assertion}: {:?}", test.message); + } }); } - /// Read as a text, its path left in place of the file (#1765). + // ── The request ── + #[test] - fn a_form_s_file_part_stays_a_file_through_a_script() { + fn a_script_changes_the_request_through_req_and_pm_request() { hosted(|| { - let mut job = before("pm.request.body.formdata.add({ key: 'note', value: 'x' });"); - job.request.body = ScriptBody { - mode: "formdata".to_string(), - formdata: vec![ScriptRow { - key: "scan".to_string(), - value: "/tmp/scan.png".to_string(), - part: Some("file".to_string()), - ..ScriptRow::default() - }], - ..ScriptBody::default() - }; - let parts = engine().0.run(&job, SECOND).request.unwrap().body.formdata; - let parts: Vec<(&str, Option<&str>)> = parts - .iter() - .map(|part| (part.key.as_str(), part.part.as_deref())) - .collect(); - assert_eq!(parts, [("scan", Some("file")), ("note", Some("text"))]); + let outcome = run(&before( + "req.method = 'put'; + req.url = req.url + '&retry=1'; + req.headers.set('X-Signature', 'abc'); + pm.request.headers.add({ key: 'X-Trace', value: 1 }); + pm.request.body.update(JSON.stringify({ amount: 2 }));", + )); + assert_eq!(outcome.failure, None); + let request = outcome.request.unwrap(); + assert_eq!( + (request.method.as_str(), request.url.as_str()), + ("PUT", "{{baseUrl}}/pay?page=1&retry=1") + ); + let headers = [ + row("Accept", "application/json"), + row("X-Signature", "abc"), + row("X-Trace", "1"), + ]; + assert_eq!(request.headers, headers); + assert_eq!( + (request.body.mode.as_str(), request.body.raw.as_str()), + ("raw", "{\"amount\":2}") + ); }); } @@ -501,59 +558,526 @@ mod tests { ] { let mut job = before(""); job.request.url = url.to_string(); - assert_eq!(engine.run(&job, SECOND).request.unwrap().url, url); + assert_eq!(engine.run(&job, SECONDS).request.unwrap().url, url); } }); } + /// Read as a text, its path left in place of the file (#1765). + #[test] + fn a_form_s_file_part_stays_a_file_through_a_script() { + hosted(|| { + let mut job = before("pm.request.body.formdata.add({ key: 'note', value: 'x' });"); + let scan = ScriptRow { + part: Some("file".to_string()), + ..row("scan", "/tmp/scan.png") + }; + job.request.body = ScriptBody { + mode: "formdata".to_string(), + formdata: vec![scan], + ..ScriptBody::default() + }; + let parts = run(&job).request.unwrap().body.formdata; + let parts: Vec<_> = parts + .iter() + .map(|part| (part.key.as_str(), part.part.as_deref())) + .collect(); + assert_eq!(parts, [("scan", Some("file")), ("note", Some("text"))]); + }); + } + + #[test] + fn a_phase_after_the_answer_leaves_the_request_alone() { + hosted(|| assert_eq!(run(&after("req.method = 'PUT';")).request, None)); + } + + #[test] + fn the_request_reads_as_the_user_wrote_it() { + hold( + before, + &[ + ( + "[req.method, req.url, req.body]", + r#"["POST","{{baseUrl}}/pay?page=1",""]"#, + ), + ("req.headers.get('accept')", r#""application/json""#), + ("request.headers", r#"{"Accept":"application/json"}"#), + ( + "[request.method, request.url]", + r#"["POST","{{baseUrl}}/pay?page=1"]"#, + ), + ( + "pm.request.getHeaders({ ignoreCase: true })", + r#"{"accept":"application/json"}"#, + ), + ( + "(pm.request.addHeader({ key: 'A', value: 'b', disabled: true }), pm.request.getHeaders({ enabled: true }))", + r#"{"Accept":"application/json"}"#, + ), + ( + "(pm.request.upsertHeader('A: c'), pm.request.removeHeader('accept'), pm.request.getHeaders())", + r#"{"A":"c"}"#, + ), + ], + ); + } + + /// `req.body` is the body a script reads as JSON, and sets as a text. + #[test] + fn a_body_is_read_and_set_in_four_words() { + hold( + before, + &[ + ("(req.body = { a: 1 }, req.body)", r#""{\"a\":1}""#), + ("req.json()", r#"{"a":1}"#), + ("(req.body = 'plain', pm.request.body.mode)", r#""raw""#), + ("pm.request.body.isEmpty()", "false"), + ( + "(pm.request.body.update({ mode: 'urlencoded', urlencoded: [{ key: 'a b', value: '&' }, { key: 'x', value: '1', disabled: true }] }), req.body)", + r#""a%20b=%26""#, + ), + ("pm.request.body.isEmpty()", "false"), + ( + "(pm.request.body.update({ mode: 'formdata' }), [pm.request.body.isEmpty(), req.body])", + r#"[true,""]"#, + ), + ( + "(pm.request.body.update({ mode: 'file', file: { src: '' } }), pm.request.body.isEmpty())", + "true", + ), + ( + "(pm.request.body.update(null), [pm.request.body.mode, pm.request.body.isEmpty()])", + r#"["none",true]"#, + ), + ], + ); + } + + /// As typed: `{{baseUrl}}/pay` is not a URL a parser accepts. + #[test] + fn a_url_is_read_in_its_parts() { + hold( + before, + &[ + ( + "[pm.request.url.getHost(), pm.request.url.getPath(), pm.request.url.getQueryString()]", + r#"["{{baseUrl}}","/pay","page=1"]"#, + ), + ( + "(req.url = 'https://u:p@a.test:80/b/c?d=1&e#f', [pm.request.url.protocol, pm.request.url.auth, pm.request.url.getRemote(), pm.request.url.hash])", + r#"["https","u:p","a.test:80","f"]"#, + ), + ("pm.request.url.getPathWithQuery()", r#""/b/c?d=1&e""#), + ( + "(pm.request.url.addQueryParams('g=2&h'), pm.request.url.removeQueryParams(['d', { key: 'h' }]), req.url)", + r#""https://u:p@a.test:80/b/c?e&g=2#f""#, + ), + ( + "(pm.request.url.addQueryParams([{ key: 'i', value: 3 }]), pm.request.url.getQueryString())", + r#""e&g=2&i=3""#, + ), + ( + "(req.url = 'a.test', [pm.request.url.getRemote(), pm.request.url.getPath(), pm.request.url.getPathWithQuery(), pm.request.url])", + r#"["a.test","/","/","a.test"]"#, + ), + ], + ); + } + + /// Headers whatever their case, as Postman's lists. + #[test] + fn a_list_of_rows_answers_as_postman_s_does() { + hold( + before, + &[ + ( + "(pm.request.headers.clear(), pm.request.headers.populate([{ key: 'A', value: '1' }, { name: 'B', value: null, disabled: true }, 'C: 3']), pm.request.headers.count())", + "3", + ), + ( + "pm.request.headers.all()", + r#"[{"key":"A","value":"1","disabled":false},{"key":"B","value":"","disabled":true},{"key":"C","value":"3","disabled":false}]"#, + ), + ( + "[pm.request.headers.get('a'), pm.request.headers.get('b'), pm.request.headers.one('b').key]", + r#"["1",null,"B"]"#, + ), + ( + "[pm.request.headers.has('a'), pm.request.headers.has('a', 1), pm.request.headers.has('a', 2), pm.request.headers.has('b')]", + "[true,true,false,false]", + ), + ("pm.request.headers.toString()", r#""A: 1\nC: 3""#), + ( + "[pm.request.headers.toObject(), pm.request.headers.toObject(true)]", + r#"[{"A":"1","B":"","C":"3"},{"A":"1","C":"3"}]"#, + ), + ( + "[pm.request.headers.idx(0).key, pm.request.headers.map((row) => row.key), pm.request.headers.filter((row) => row.disabled).length, pm.request.headers.find((row) => row.value === '3').key, pm.request.headers.reduce((sum, row) => sum + row.key, '')]", + r#"["A",["A","B","C"],1,"C","ABC"]"#, + ), + ("[...pm.request.headers].length", "3"), + ( + "(() => { const keys = []; pm.request.headers.each((row) => keys.push(row.key)); return keys; })()", + r#"["A","B","C"]"#, + ), + ( + "(pm.request.headers.prepend('Z', 0), pm.request.headers.append('Y'), pm.request.headers.upsert({ key: 'a', value: 9 }), pm.request.headers.map((row) => row.key + row.value))", + r#"["Z0","a9","B","C3","Y"]"#, + ), + ( + "(pm.request.headers.remove('z'), pm.request.headers.remove({ key: 'y' }), pm.request.headers.remove((row) => row.value === '3'), pm.request.headers.delete('A'), pm.request.headers.repopulate([{ key: 'last' }]), pm.request.headers)", + r#"[{"key":"last","value":"","disabled":false}]"#, + ), + ( + "(pm.request.headers.set('last'), pm.request.headers.get('last'))", + r#""""#, + ), + ], + ); + } + + #[test] + fn headers_are_given_as_a_list_an_object_or_lines() { + hosted(|| { + let (engine, seen) = engine(); + let asking = |header: &str| { + format!("await pm.sendRequest({{ url: 'https://a.test', header: {header} }});") + }; + let source = [ + "[{ key: 'A', value: '1' }]", + "{ A: 1 }", + "'A: 1\\r\\nnot a header'", + "null", + ] + .map(asking) + .join("\n"); + assert_eq!(engine.run(&before(&source), SECONDS).failure, None); + let sent: Vec<_> = seen + .borrow() + .calls + .iter() + .map(|(_, payload)| payload["headers"].clone()) + .collect(); + let one = json!([{ "key": "A", "value": "1", "disabled": false }]); + assert_eq!(sent, [one.clone(), one.clone(), one, json!([])]); + }); + } + + // ── The answer ── + + #[test] + fn the_answer_reads_in_plain_values_through_res() { + hold( + after, + &[ + ( + "[res.status, res.statusText, res.time, res.size]", + r#"[402,"Payment Required",203,37]"#, + ), + // Two headers of one name are one, as a browser joins them. + ( + "res.headers", + r#"{"content-type":"application/json","vary":"a, b"}"#, + ), + ( + "[res.body === res.text(), res.json().currency, res.cookies]", + r#"[true,"usd",{"sid":"42"}]"#, + ), + ], + ); + } + + #[test] + fn the_answer_reads_as_postman_s_through_pm_response() { + hold( + after, + &[ + ( + "[pm.response.code, pm.response.status, pm.response.reason(), pm.response.responseTime, pm.response.responseSize]", + r#"[402,"Payment Required","Payment Required",203,37]"#, + ), + ("pm.response.size()", r#"{"body":37,"header":0,"total":37}"#), + ( + "[pm.response.json().items[0].id, pm.response.stream.length, pm.response.headers.get('VARY')]", + r#"[7,37,"a"]"#, + ), + ( + "Object.keys(pm.response.toJSON())", + r#"["code","status","headers","body"]"#, + ), + ], + ); + } + + #[test] + fn the_answer_reads_under_postman_s_older_names() { + hold( + after, + &[ + ( + "[responseBody === res.body, responseCode, responseTime]", + r#"[true,{"code":402,"name":"Payment Required","detail":"Payment Required"},203]"#, + ), + ( + "[responseHeaders['Content-Type'], responseCookies[0].name]", + r#"["application/json","sid"]"#, + ), + ( + "[postman.getResponseHeader('content-type'), postman.getResponseCookie('sid').value]", + r#"["application/json","42"]"#, + ), + ("xml2Json('1')", r#"{"a":{"b":"1"}}"#), + ], + ); + } + + #[test] + fn before_the_send_there_is_no_answer() { + hold( + before, + &[ + ( + "[typeof res, pm.response, typeof responseBody]", + r#"["undefined",null,"undefined"]"#, + ), + ( + "[postman.getResponseHeader('a') === undefined, postman.getResponseCookie('a') === undefined]", + "[true,true]", + ), + ], + ); + } + + #[test] + fn an_answer_that_is_not_json_says_so_when_read_as_json() { + hosted(|| { + let mut job = after("res.json();"); + job.response.as_mut().unwrap().body = "".to_string(); + let failure = run(&job).failure.unwrap(); + assert!( + failure + .message + .starts_with("SyntaxError: The response is not JSON: "), + "{}", + failure.message + ); + }); + } + + #[test] + fn the_cookies_of_the_url_and_of_the_answer_are_lists() { + hold( + after, + &[ + ( + "[pm.cookies.get('jar'), pm.cookies.has('jar'), pm.cookies.has('gone'), pm.cookies.get('gone') === undefined]", + r#"["1",true,false,true]"#, + ), + ( + "[pm.cookies.count(), pm.cookies.one('jar').value, pm.cookies.all()[0].name, pm.cookies.toObject()]", + r#"[1,"1","jar",{"jar":"1"}]"#, + ), + ( + "(() => { const names = []; pm.response.cookies.each((cookie) => names.push(cookie.name)); return names; })()", + r#"["sid"]"#, + ), + ], + ); + } + + // ── Variables ── + + #[test] + fn a_variable_reads_from_the_nearest_level_that_holds_it() { + hold( + before, + &[ + ( + "[env.get('tenant'), pm.variables.get('tenant'), pm.globals.get('tenant'), pm.collectionVariables.get('tenant')]", + r#"["near","near","far","near"]"#, + ), + ( + "[env.has('customer'), env.has('gone'), pm.variables.has('gone'), pm.environment.has('tenant')]", + "[true,false,false,false]", + ), + ( + "[pm.iterationData.get('customer'), data.customer, environment.baseUrl, globals.tenant]", + r#"["cus_1","cus_1","https://api.test","far"]"#, + ), + ( + "[pm.environment.name, pm.environment.toObject(), pm.environment.values.get('baseUrl')]", + r#"["Staging",{"baseUrl":"https://api.test"},"https://api.test"]"#, + ), + ( + "pm.variables.toObject()", + r#"{"tenant":"near","baseUrl":"https://api.test","page":"2","customer":"cus_1"}"#, + ), + ], + ); + } + #[test] - fn env_writes_the_active_environment_and_with_none_the_globals() { + fn a_text_is_filled_with_what_its_names_resolve_to() { + hold( + before, + &[ + ( + "pm.variables.replaceIn('{{baseUrl}}/{{tenant}}/{{missing}}/{{ not }}')", + r#""https://api.test/near/{{missing}}/{{ not }}""#, + ), + ( + "[env.replaceIn('{{page}}'), pm.environment.replaceIn('{{page}}'), env.replaceIn(3)]", + r#"["2","2",3]"#, + ), + ], + ); + } + + #[test] + fn what_a_script_sets_is_read_back_at_once() { + hold( + before, + &[ + ( + "(pm.variables.set('tenant', 'local'), [env.get('tenant'), pm.variables.toObject().tenant, env.replaceIn('{{tenant}}')])", + r#"["local","local","local"]"#, + ), + ( + "(pm.variables.unset('tenant'), env.get('tenant'))", + r#""near""#, + ), + ( + "(pm.variables.set('a', 1), pm.variables.clear(), env.has('a'))", + "false", + ), + ], + ); + } + + /// What a variable holds is a text, as an environment stores it. + #[test] + fn a_value_is_stored_as_a_text() { hosted(|| { - let source = "env.set('token', 'abc'); env.secret('key', 42); env.unset('old'); - pm.globals.set('g', { a: 1 }); pm.collectionVariables.set('c', true);"; - let outcome = run(source); - let writes: Vec<(WriteScope, &str, Option<&str>, bool)> = outcome + let outcome = run(&before( + "for (const value of ['a', 42, true, null, undefined, { a: 1 }, [1, 2]]) pm.globals.set('v', value); + const loop = {}; loop.self = loop; pm.globals.set('v', loop);", + )); + let values: Vec<_> = outcome .writes .iter() - .map(|write| { - ( - write.scope, - write.name.as_str(), - write.value.as_deref(), - write.secret, - ) - }) + .map(|write| write.value.as_deref().unwrap()) .collect(); assert_eq!( - writes, + values, + [ + "a", + "42", + "true", + "", + "", + "{\"a\":1}", + "[1,2]", + "[object Object]" + ] + ); + }); + } + + fn writes(outcome: &Outcome) -> Vec<(WriteScope, &str, Option<&str>, bool)> { + let writes = outcome.writes.iter(); + writes + .map(|write| { + ( + write.scope, + write.name.as_str(), + write.value.as_deref(), + write.secret, + ) + }) + .collect() + } + + #[test] + fn a_write_goes_to_the_level_it_names() { + hosted(|| { + let outcome = run(&before( + "env.set('token', 'abc'); env.secret('key', 42); env.unset('old'); + pm.environment.set('e', 1); pm.environment.unset('e'); + pm.globals.set('g', 1); pm.collectionVariables.set('c', 2); pm.iterationData.unset('customer');", + )); + assert_eq!( + writes(&outcome), [ (WriteScope::Environment, "token", Some("abc"), false), (WriteScope::Environment, "key", Some("42"), true), (WriteScope::Environment, "old", None, false), - (WriteScope::Globals, "g", Some("{\"a\":1}"), false), - (WriteScope::Collection, "c", Some("true"), false), + (WriteScope::Environment, "e", Some("1"), false), + (WriteScope::Environment, "e", None, false), + (WriteScope::Globals, "g", Some("1"), false), + (WriteScope::Collection, "c", Some("2"), false), + (WriteScope::Data, "customer", None, false), ] ); + }); + } - let mut job = before("env.set('token', 'abc');"); + #[test] + fn with_no_environment_chosen_env_writes_the_globals() { + hosted(|| { + let mut job = before("env.set('a', 1); pm.environment.set('b', 2);"); job.environment = None; - let outcome = engine().0.run(&job, SECOND); - assert_eq!(outcome.writes[0].scope, WriteScope::Globals); + let outcome = run(&job); + assert!( + outcome + .writes + .iter() + .all(|write| write.scope == WriteScope::Globals) + ); + assert_eq!(outcome.writes.len(), 2); }); } #[test] - fn a_variable_resolves_from_the_nearest_level_and_what_a_script_set_is_read_back() { + fn clearing_a_level_unsets_each_of_its_variables() { hosted(|| { - let outcome = run( - "if (env.get('baseUrl') !== 'https://api.example.com') throw new Error('env'); - if (pm.variables.get('tenant') !== 'acme') throw new Error('globals'); - env.set('baseUrl', 'http://localhost'); - if (pm.environment.get('baseUrl') !== 'http://localhost') throw new Error('write'); - const filled = pm.variables.replaceIn('{{baseUrl}}/{{tenant}}/{{missing}}'); - if (filled !== 'http://localhost/acme/{{missing}}') throw new Error(filled);", + let outcome = run(&before("pm.collectionVariables.clear();")); + let cleared = writes(&outcome); + assert_eq!( + cleared, + [ + (WriteScope::Collection, "page", None, false), + (WriteScope::Collection, "tenant", None, false) + ] ); - assert_eq!(outcome.failure, None); + }); + } + + #[test] + fn postman_s_older_names_write_the_same_levels() { + hosted(|| { + let outcome = run(&before( + "postman.setEnvironmentVariable('a', postman.getEnvironmentVariable('baseUrl')); + postman.clearEnvironmentVariable('a'); postman.clearEnvironmentVariables(); + postman.setGlobalVariable('b', postman.getGlobalVariable('tenant')); + postman.clearGlobalVariable('b'); postman.clearGlobalVariables(); + postman.setNextRequest('Next');", + )); + let written: Vec<_> = writes(&outcome) + .into_iter() + .map(|(scope, name, value, _)| (scope, name, value)) + .collect(); + assert_eq!( + written, + [ + (WriteScope::Environment, "a", Some("https://api.test")), + (WriteScope::Environment, "a", None), + (WriteScope::Environment, "baseUrl", None), + (WriteScope::Globals, "b", Some("far")), + (WriteScope::Globals, "b", None), + (WriteScope::Globals, "tenant", None), + ] + ); + assert_eq!(outcome.next.name.as_deref(), Some("Next")); }); } @@ -561,178 +1085,444 @@ mod tests { fn a_local_variable_lasts_from_the_script_before_to_the_tests_after() { hosted(|| { let (engine, _) = engine(); - engine.run(&before("pm.variables.set('started', 'yes');"), SECOND); + let outcome = engine.run(&before("pm.variables.set('started', 'yes');"), SECONDS); + assert_eq!( + outcome.locals, + [("started".to_string(), "yes".to_string())].into() + ); + assert!(outcome.writes.is_empty()); + let outcome = engine.run( - &after( - "test('kept', () => expect(pm.variables.get('started')).toBe('yes'));", - "{}", - ), - SECOND, + &after("env.set('kept', pm.variables.get('started'));"), + SECONDS, ); - assert!(outcome.tests[0].passed, "{:?}", outcome.tests); + assert_eq!(outcome.writes[0].value.as_deref(), Some("yes")); }); } #[test] fn the_dynamic_variables_fill_a_text_each_time_anew() { hosted(|| { - let outcome = run( - "const a = pm.variables.replaceIn('{{$guid}}'); - const b = pm.variables.replaceIn('{{$randomUUID}}'); - if (!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(a)) throw new Error(a); - if (a === b) throw new Error('same'); - if (!/^\\d{10}$/.test(pm.variables.replaceIn('{{$timestamp}}'))) throw new Error('timestamp'); - if (Number.isNaN(Date.parse(pm.variables.replaceIn('{{$isoTimestamp}}')))) throw new Error('iso'); - const n = Number(pm.variables.replaceIn('{{$randomInt}}')); - if (!(n >= 0 && n <= 1000)) throw new Error('int');", - ); + let outcome = run(&before( + "const fill = (name) => pm.variables.replaceIn('{{$' + name + '}}'); + const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; + if (!uuid.test(fill('guid')) || !uuid.test(fill('randomUUID')) || !uuid.test(crypto.randomUUID())) throw new Error('uuid'); + if (fill('guid') === fill('guid')) throw new Error('same'); + if (!/^\\d{10}$/.test(fill('timestamp'))) throw new Error('timestamp'); + if (Number.isNaN(Date.parse(fill('isoTimestamp')))) throw new Error('iso'); + const n = Number(fill('randomInt')); + if (!(n >= 0 && n <= 1000)) throw new Error('int'); + if (fill('unknown') !== '{{$unknown}}') throw new Error('unknown');", + )); assert_eq!(outcome.failure, None); }); } + // ── Tests ── + #[test] - fn a_test_reports_what_was_expected_what_came_and_the_line_in_both_syntaxes() { - hosted(|| { - let source = "test('Le statut est 200 ou 402', () => { - expect([200, 402]).toContain(res.status); - }); - pm.test('Le montant est débité en euros', () => { - pm.expect(res.json().currency).to.equal('eur'); - }); - test('Répond vite', () => expect(res.time).toBeLessThan(100)); - test.skip('Plus tard');"; - let outcome = engine() - .0 - .run(&after(source, "{\"currency\":\"usd\"}"), SECOND); - assert_eq!(outcome.failure, None); - let tests = &outcome.tests; - assert_eq!(tests.len(), 4); - assert!(tests[0].passed); - assert!(!tests[1].passed); - assert_eq!(tests[1].expected.as_deref(), Some("\"eur\"")); - assert_eq!(tests[1].actual.as_deref(), Some("\"usd\"")); - assert_eq!(tests[1].line, Some(5)); - assert_eq!(tests[1].script.as_deref(), Some("request:tests")); - assert_eq!(tests[2].expected.as_deref(), Some("100")); - assert_eq!(tests[2].actual.as_deref(), Some("203")); - assert!(tests[3].skipped); - }); - } - - #[test] - fn the_jest_words_read_like_jest_and_say_not() { - hosted(|| { - let source = " - test('a', () => expect({ a: { b: [1, 2] } }).toEqual({ a: { b: [1, 2] } })); - test('b', () => expect(res.headers).toHaveProperty('content-type', 'application/json')); - test('c', () => expect('DevNotes').toMatch(/notes/i)); - test('d', () => expect(null).not.toBeDefined()); - test('e', () => expect(() => { throw new TypeError('no'); }).toThrow(TypeError)); - test('f', () => expect({ a: 1, b: 2 }).toMatchObject({ a: 1 })); - test('g', () => expect([1, 2, 3]).toHaveLength(3)); - test('h', () => expect(0.1 + 0.2).toBeCloseTo(0.3)); - test('i', () => expect(1).not.toBe(1));"; - let outcome = engine().0.run(&after(source, "{}"), SECOND); - let passed: Vec = outcome.tests.iter().map(|test| test.passed).collect(); - assert_eq!( - passed, - [true, true, true, false, true, true, true, true, false], - "{:?}", - outcome.tests - ); - }); + fn a_test_that_fails_says_what_was_expected_what_came_and_the_line() { + let tests = tested( + "test('passes', () => expect(1).toBe(1)); + pm.test('fails', () => { + pm.expect(res.json().currency).to.equal('eur'); + });", + ); + assert!(tests[0].passed && tests[0].line.is_none() && tests[0].message.is_none()); + let failed = &tests[1]; + assert!(!failed.passed && !failed.skipped); + assert_eq!( + (failed.expected.as_deref(), failed.actual.as_deref()), + (Some("\"eur\""), Some("\"usd\"")) + ); + assert_eq!( + (failed.script.as_deref(), failed.line), + (Some("request:tests"), Some(3)) + ); + assert!(failed.message.as_deref().unwrap().contains("eur")); } #[test] - fn postman_s_response_assertions_and_older_names_work() { - hosted(|| { - let source = " - pm.test('status', () => pm.response.to.have.status(402)); - pm.test('client error', () => pm.response.to.be.clientError); - pm.test('header', () => pm.response.to.have.header('content-type', 'application/json')); - pm.test('json', () => pm.response.to.have.jsonBody('currency', 'usd')); - pm.test('not ok', () => pm.response.to.be.ok); - pm.test('plain ok', () => pm.expect(1).to.be.ok); - tests['legacy'] = responseCode.code === 402;"; - let outcome = engine() - .0 - .run(&after(source, "{\"currency\":\"usd\"}"), SECOND); - let passed: Vec<(&str, bool)> = outcome - .tests + fn a_test_skipped_neither_passes_nor_fails() { + let tests = + tested("test.skip('later'); pm.test.skip('never', () => { throw new Error('ran'); });"); + assert_eq!(tests.len(), 2); + assert!( + tests .iter() - .map(|test| (test.name.as_str(), test.passed)) - .collect(); - assert_eq!( - passed, - [ - ("status", true), - ("client error", true), - ("header", true), - ("json", true), - ("not ok", false), - ("plain ok", true), - ("legacy", true), - ] + .all(|test| test.skipped && !test.passed && test.message.is_none()) + ); + } + + #[test] + fn a_test_fails_by_whatever_it_throws() { + let tests = tested( + "test('error', () => { throw new TypeError('no'); }); + test('text', () => { throw 'plain'; }); + test('nothing', () => { throw undefined; }); + test('no body');", + ); + let messages: Vec<_> = tests.iter().map(|test| test.message.as_deref()).collect(); + assert_eq!( + messages, + [Some("no"), Some("plain"), Some("undefined"), None] + ); + assert!(tests[0].expected.is_none() && tests[0].actual.is_none()); + assert!(tests[3].passed); + } + + /// One that answers later is waited for, by its promise or the callback it takes. + #[test] + fn a_test_that_answers_later_is_waited_for() { + let tests = tested( + "test('promise', async () => { await new Promise((r) => setTimeout(r, 5)); expect(1).toBe(2); }); + test('callback', (done) => setTimeout(done, 5)); + test('passes', async () => {});", + ); + let passed: Vec = tests.iter().map(|test| test.passed).collect(); + assert_eq!(passed, [false, true, true]); + assert_eq!(tests[0].actual.as_deref(), Some("1")); + } + + #[test] + fn the_older_tests_object_is_one_test_an_entry() { + let tests = tested("tests['holds'] = responseCode.code === 402; tests['fails'] = 0;"); + let read: Vec<_> = tests + .iter() + .map(|test| (test.name.as_str(), test.passed, test.message.as_deref())) + .collect(); + assert_eq!( + read, + [("holds", true, None), ("fails", false, Some("false"))] + ); + } + + /// As the prelude writes a value: a text quoted, the rest as JSON, a long one cut. + #[test] + fn a_value_compared_is_shown_as_it_reads() { + let tests = tested( + "for (const value of ['a', undefined, null, NaN, 12n, Symbol('s'), () => 1, function named() {}, new RangeError('r'), { a: [1] }, 'x'.repeat(10)]) + test('t', () => expect(value).toBe('never')); + const loop = {}; loop.self = loop; + test('loop', () => { const e = new Error('m'); e.actual = loop; throw e; }); + test('long', () => { const e = new Error('m'); e.actual = [...'x'.repeat(3000)]; throw e; });", + ); + let shown: Vec<_> = tests + .iter() + .take(12) + .map(|test| test.actual.as_deref().unwrap()) + .collect(); + assert_eq!( + shown, + [ + "\"a\"", + "undefined", + "null", + "NaN", + "12n", + "Symbol(s)", + "[Function value]", + "[Function named]", + "RangeError: r", + "{\"a\":[1]}", + "\"xxxxxxxxxx\"", + "[object Object]" + ] + .map(|shown| if shown == "[Function value]" { + "[Function]" + } else { + shown + }) + ); + let long = tests[12].actual.as_deref().unwrap(); + assert!( + long.ends_with('…') && long.chars().count() == 2001, + "{}", + long.len() + ); + } + + #[test] + fn the_jest_words_hold_and_fail_as_jest_s_do() { + judge(&[ + ("expect(1).toBe(1)", true), + ("expect(NaN).toBe(NaN)", true), + ("expect({}).toBe({})", false), + ( + "expect({ a: { b: [1, 2] } }).toEqual({ a: { b: [1, 2] } })", + true, + ), + ("expect({ a: 1 }).toEqual({ a: 2 })", false), + ("expect([1]).toStrictEqual([1])", true), + ("expect([1]).toStrictEqual([2])", false), + ("expect('DevNotes').toContain('Notes')", true), + ("expect([1, 2]).toContain(2)", true), + ("expect([{ a: 1 }]).toContain({ a: 1 })", false), + ("expect(null).toContain(1)", false), + ("expect([{ a: 1 }]).toContainEqual({ a: 1 })", true), + ("expect([{ a: 1 }]).toContainEqual({ a: 2 })", false), + ("expect('DevNotes').toMatch(/notes/i)", true), + ("expect('DevNotes').toMatch('notes')", false), + ( + "expect({ a: 1, b: { c: 2, d: 3 } }).toMatchObject({ b: { c: 2 } })", + true, + ), + ("expect({ a: [1, 2] }).toMatchObject({ a: [1] })", false), + ("expect({ a: 1 }).toMatchObject({ b: undefined })", false), + ("expect('a').toMatchObject({ a: 1 })", false), + ("expect(1).toMatchObject(1)", true), + ("expect(1).toBeLessThan(2)", true), + ("expect(2).toBeLessThan(2)", false), + ("expect(2).toBeLessThanOrEqual(2)", true), + ("expect(2).toBeGreaterThan(2)", false), + ("expect(2).toBeGreaterThanOrEqual(2)", true), + ("expect(0.1 + 0.2).toBeCloseTo(0.3)", true), + ("expect(0.31).toBeCloseTo(0.3)", false), + ("expect(0.31).toBeCloseTo(0.3, 1)", true), + ( + "expect(res.headers).toHaveProperty('content-type', 'application/json')", + true, + ), + ("expect(res.json()).toHaveProperty('items[0].id', 7)", true), + ( + "expect(res.json()).toHaveProperty(['items', 0, 'id'])", + true, + ), + ("expect(res.json()).toHaveProperty('items[1].id')", false), + ( + "expect(res.json()).toHaveProperty('currency', 'eur')", + false, + ), + ("expect(null).toHaveProperty('a')", false), + ("expect([1, 2, 3]).toHaveLength(3)", true), + ("expect('abc').toHaveLength(2)", false), + ("expect(null).toHaveLength(0)", false), + ("expect('a').toBeTruthy()", true), + ("expect(0).toBeTruthy()", false), + ("expect(0).toBeFalsy()", true), + ("expect(null).toBeNull()", true), + ("expect(undefined).toBeNull()", false), + ("expect(undefined).toBeUndefined()", true), + ("expect(null).toBeDefined()", true), + ("expect(null).not.toBeDefined()", false), + ("expect(NaN).toBeNaN()", true), + ("expect('NaN').toBeNaN()", false), + ("expect(new TypeError('x')).toBeInstanceOf(Error)", true), + ("expect({}).toBeInstanceOf(Error)", false), + ( + "expect(() => { throw new TypeError('no'); }).toThrow()", + true, + ), + ( + "expect(() => { throw new TypeError('no'); }).toThrow(TypeError)", + true, + ), + ( + "expect(() => { throw new TypeError('no'); }).toThrow(RangeError)", + false, + ), + ( + "expect(() => { throw new TypeError('no way'); }).toThrow('way')", + true, + ), + ( + "expect(() => { throw new TypeError('no way'); }).toThrow(/^way/)", + false, + ), + ("expect(() => { throw 'plain'; }).toThrow('plain')", true), + ("expect(() => {}).toThrow()", false), + ("expect(() => {}).not.toThrow()", true), + ("expect(1).not.toBe(1)", false), + ("expect(1, 'said').to.equal(1)", true), + ]); + } + + #[test] + fn postman_s_response_assertions_hold_and_fail_as_postman_s_do() { + judge(&[ + ("pm.response.to.have.status(402)", true), + ("pm.response.to.have.status(200)", false), + ("pm.response.to.have.status('Payment Required')", true), + ("pm.response.to.not.have.status(200)", true), + ("pm.response.not.to.have.status(402)", false), + ("pm.response.to.be.clientError", true), + ("pm.response.to.be.error", true), + ("pm.response.to.be.success", false), + ("pm.response.to.be.info", false), + ("pm.response.to.be.redirection", false), + ("pm.response.to.be.serverError", false), + ("pm.response.to.be.ok", false), + ("pm.response.to.be.accepted", false), + ("pm.response.to.be.badRequest", false), + ("pm.response.to.be.unauthorized", false), + ("pm.response.to.be.forbidden", false), + ("pm.response.to.be.notFound", false), + ("pm.response.to.not.be.rateLimited", true), + ("pm.response.to.have.header('content-type')", true), + ( + "pm.response.to.have.header('Content-Type', 'application/json')", + true, + ), + ( + "pm.response.to.have.header('Content-Type', 'text/html')", + false, + ), + ("pm.response.to.have.header('X-Gone')", false), + ("pm.response.to.have.body()", true), + ("pm.response.to.have.body(responseBody)", true), + ("pm.response.to.have.body('other')", false), + ("pm.response.to.have.body(/usd/)", true), + ( + "pm.response.to.have.body({ currency: 'usd', items: [{ id: 7 }] })", + true, + ), + ("pm.response.to.have.body({ currency: 'eur' })", false), + ("pm.response.to.have.jsonBody()", true), + ("pm.response.to.have.jsonBody('items[0].id')", true), + ("pm.response.to.have.jsonBody('items[0].id', 7)", true), + ("pm.response.to.have.jsonBody('items[0].id', 8)", false), + ("pm.response.to.have.jsonBody('gone')", false), + ( + "pm.response.to.have.jsonBody({ currency: 'usd', items: [{ id: 7 }] })", + true, + ), + ("pm.response.to.be.json", true), + ("pm.response.to.be.withBody", true), + ("pm.expect(pm.response).to.have.responseTime(203)", true), + ("pm.expect(pm.response).to.have.responseTime(202)", false), + // Chai's own words stay chai's for anything but a response. + ("pm.expect(1).to.be.ok", true), + ("pm.expect(0).to.be.ok", false), + ]); + } + + #[test] + fn an_answer_of_200_is_ok_and_one_that_is_empty_has_no_body() { + hosted(|| { + let mut job = after( + "test('ok', () => pm.response.to.be.ok); + test('success', () => pm.response.to.be.success); + test('body', () => pm.response.to.have.body()); + test('withBody', () => pm.response.to.be.withBody); + test('json', () => pm.response.to.be.json); + test('jsonBody', () => pm.response.to.have.jsonBody());", ); + let response = job.response.as_mut().unwrap(); + (response.code, response.body) = (200, String::new()); + let passed: Vec = run(&job).tests.iter().map(|test| test.passed).collect(); + assert_eq!(passed, [true, true, false, false, false, false]); }); } + // ── How a script stops ── + #[test] fn an_error_names_its_script_and_line_and_stops_the_phase() { hosted(|| { - let mut job = before("const a = 1;\nconst b = 2;\ntokn.read();\nenv.set('never', 1);"); - job.scripts.push(script( - "collection:before", - ScriptKind::Before, - "env.set('later', 1);", - )); - let outcome = engine().0.run(&job, SECOND); - let failure = outcome.failure.unwrap(); - assert_eq!(failure.kind, FailureKind::Error); - assert_eq!(failure.script.as_deref(), Some("request:before")); - assert_eq!(failure.line, Some(3)); + let mut job = + before("env.set('first', 1);\nconst b = 2;\ntokn.read();\nenv.set('never', 1);"); + job.scripts + .push(script("collection:before", "env.set('later', 1);")); + let outcome = run(&job); + let failure = outcome.failure.clone().unwrap(); + assert_eq!( + (failure.kind, failure.script.as_deref(), failure.line), + (FailureKind::Error, Some("request:before"), Some(3)) + ); assert!( - failure.message.starts_with("ReferenceError"), + failure.message.starts_with("ReferenceError: "), "{}", failure.message ); - assert!(outcome.writes.is_empty()); + // What it did before it stopped is kept. + assert_eq!( + writes(&outcome), + [(WriteScope::Environment, "first", Some("1"), false)] + ); + }); + } + + #[test] + fn an_error_of_a_later_script_names_that_one() { + hosted(|| { + let mut job = before("const a = 1;"); + job.scripts + .push(script("collection:before", "\nthrow new Error('x');")); + let failure = run(&job).failure.unwrap(); + assert_eq!( + (failure.script.as_deref(), failure.line), + (Some("collection:before"), Some(2)) + ); + }); + } + + #[test] + fn a_script_stops_by_whatever_it_throws() { + hosted(|| { + for (source, message) in [ + ("throw 'plain';", "plain"), + ("throw null;", "null"), + ("throw { message: 'object' };", "Error: object"), + ( + "await Promise.reject(new TypeError('late'));", + "TypeError: late", + ), + ( + "test('t', () => {}); throw new RangeError('after');", + "RangeError: after", + ), + ] { + let failure = failure(source); + assert_eq!( + (failure.kind, failure.message.as_str()), + (FailureKind::Error, message), + "{source}" + ); + assert_eq!(failure.script.as_deref(), Some("request:before")); + } }); } #[test] - fn a_script_that_does_not_read_is_a_syntax_failure_on_its_line() { + fn a_script_that_does_not_read_is_a_syntax_failure_on_its_line_and_nothing_runs() { hosted(|| { let mut job = before("env.set('ran', 1);"); - job.scripts.push(script( - "folder:before", - ScriptKind::Before, - "const ok = 1;\nif (ok {\n}", - )); - let outcome = engine().0.run(&job, SECOND); + job.scripts + .push(script("folder:before", "const ok = 1;\nif (ok {\n}")); + let outcome = run(&job); let failure = outcome.failure.unwrap(); - assert_eq!(failure.kind, FailureKind::Syntax); - assert_eq!(failure.script.as_deref(), Some("folder:before")); - assert_eq!(failure.line, Some(2)); + assert_eq!( + (failure.kind, failure.script.as_deref(), failure.line), + (FailureKind::Syntax, Some("folder:before"), Some(2)) + ); assert!( !failure.message.is_empty() && !failure.message.starts_with("SyntaxError"), "{}", failure.message ); - assert!( - outcome.writes.is_empty(), - "nothing runs when one script does not read" - ); + assert!(outcome.writes.is_empty()); }); } #[test] - fn an_endless_loop_ends_at_the_deadline_as_a_timeout() { + fn an_endless_loop_ends_at_the_deadline_and_the_engine_still_runs() { hosted(|| { + let (engine, _) = engine(); let started = Instant::now(); - let outcome = engine() - .0 - .run(&before("while (true) {}"), Duration::from_millis(300)); + let outcome = engine.run(&before("while (true) {}"), Duration::from_millis(300)); + assert_eq!(outcome.failure.unwrap().kind, FailureKind::Timeout); + assert!(started.elapsed() < Duration::from_secs(3)); + + assert_eq!(engine.run(&before(""), SECONDS).failure, None); + }); + } + + #[test] + fn a_wait_past_the_deadline_ends_there() { + hosted(|| { + let started = Instant::now(); + let late = before("await new Promise((done) => setTimeout(done, 60000));"); + let outcome = engine().0.run(&late, Duration::from_millis(200)); assert_eq!(outcome.failure.unwrap().kind, FailureKind::Timeout); assert!(started.elapsed() < Duration::from_secs(3)); }); @@ -741,86 +1531,192 @@ mod tests { #[test] fn a_script_that_takes_all_memory_ends_as_a_memory_failure() { hosted(|| { - let outcome = run("const kept = []; while (true) kept.push(new Array(1e6).fill(1));"); - assert_eq!(outcome.failure.unwrap().kind, FailureKind::Memory); + let failure = + failure("const kept = []; while (true) kept.push(new Array(1e6).fill(1));"); + assert_eq!(failure.kind, FailureKind::Memory); }); } #[test] fn a_wait_nothing_ends_is_said_rather_than_waited_for() { hosted(|| { - let outcome = run("await new Promise(() => {});"); - assert_eq!(outcome.failure.unwrap().kind, FailureKind::Timeout); + let failure = failure("await new Promise(() => {});"); + assert_eq!(failure.kind, FailureKind::Timeout); + assert!( + failure.message.contains("nothing settles"), + "{}", + failure.message + ); }); } + /// Private: the stack a failure is read from is the engine's, whatever its shape. + #[test] + fn a_stack_names_the_script_and_the_line() { + for (stack, place) in [ + (" at f (script-2:12:5)\n", Some((2, 12))), + ( + " at prelude:40\n at (script-0:3)\n", + Some((0, 3)), + ), + (" at script-x:1\n at script-1:7\n", Some((1, 7))), + (" at script-4\n", None), + (" at prelude:40\n", None), + ("", None), + ] { + assert_eq!(place_in(stack), place, "{stack}"); + } + } + + // ── What a script has around it ── + + /// A script is over when what it scheduled has run, by deadline. #[test] fn timers_run_before_the_phase_ends_and_in_their_order() { hosted(|| { - let outcome = run("const order = []; + let outcome = run(&before( + "const order = []; setTimeout(() => { order.push('late'); env.set('order', order.join(',')); }, 40); - setTimeout(() => order.push('soon'), 10); + setTimeout((word) => order.push(word), 10, 'soon'); const id = setInterval(() => { order.push('tick'); clearInterval(id); }, 5); + clearTimeout(setTimeout(() => order.push('cleared'), 1)); + setImmediate(() => order.push('now')); + process.nextTick(() => order.push('tick0')); const busy = Date.now() + 20; while (Date.now() < busy) {} - await new Promise((resolve) => setTimeout(resolve, 1));"); + await new Promise((resolve) => setTimeout(resolve, 1));", + )); assert_eq!(outcome.failure, None); - assert_eq!(outcome.writes[0].value.as_deref(), Some("tick,soon,late")); + assert_eq!( + outcome.writes[0].value.as_deref(), + Some("tick0,now,tick,soon,late") + ); + }); + } + + #[test] + fn a_timer_that_throws_or_is_given_no_function_stops_the_script() { + hosted(|| { + assert_eq!( + failure("setTimeout(() => { throw new Error('late'); }, 1);").message, + "Error: late" + ); + assert_eq!( + failure("setTimeout('code', 1);").message, + "TypeError: The callback must be a function" + ); }); } #[test] fn there_is_no_file_system_no_process_and_no_module_beyond_the_list() { hosted(|| { - let outcome = run( - "for (const name of ['fs', 'child_process', 'net', 'os', 'http']) { + let outcome = run(&before( + "for (const name of ['fs', 'child_process', 'net', 'os', 'http', 'node:fs']) { try { require(name); throw new Error(name + ' was found'); } catch (error) { if (error.code !== 'MODULE_NOT_FOUND') throw error; } } if (typeof std !== 'undefined' || typeof os !== 'undefined') throw new Error('quickjs-libc'); + if (typeof __native !== 'undefined') throw new Error('native'); if (Object.keys(process.env).length !== 0) throw new Error('env');", - ); + )); assert_eq!(outcome.failure, None); }); } #[test] fn every_library_a_postman_script_requires_loads_and_works() { - hosted(|| { - let outcome = run(r#" - const _ = require('lodash'); - if (_.chunk([1, 2, 3], 2).length !== 2) throw new Error('lodash'); - if (require('moment')('2026-10-19').format('DD/MM/YYYY') !== '19/10/2026') throw new Error('moment'); - require('chai').expect(1).to.equal(1); - const CryptoJS = require('crypto-js'); - if (CryptoJS.SHA256('abc').toString() !== 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad') throw new Error('crypto-js'); - if (!/^[0-9a-f-]{36}$/.test(require('uuid').v4())) throw new Error('uuid'); - const Ajv = require('ajv'); - if (!new Ajv().validate({ type: 'object', required: ['id'] }, { id: 1 })) throw new Error('ajv'); - if (!require('tv4').validate({ id: 1 }, { type: 'object' })) throw new Error('tv4'); - let parsed; - require('xml2js').parseString('1', { async: false }, (error, result) => { parsed = result; }); - if (parsed.a.b[0] !== '1') throw new Error('xml2js'); - if (require('cheerio').load('

    Bonjour

    ')('.x').text() !== 'Bonjour') throw new Error('cheerio'); - if (require('csv-parse/lib/sync')('a,b\n1,2', { columns: true })[0].b !== '2') throw new Error('csv-parse'); - if (require('csv-parse/sync').parse('a,b\n1,2')[1][0] !== '1') throw new Error('csv-parse/sync'); - if (Buffer.from('DevNotes').toString('base64') !== 'RGV2Tm90ZXM=') throw new Error('buffer'); - if (atob(btoa('é')) !== 'é') throw new Error('base64'); - const events = new (require('events'))(); let heard = false; events.on('x', () => { heard = true; }); events.emit('x'); - if (!heard) throw new Error('events'); - if (require('path').join('/a', 'b', '../c') !== '/a/c') throw new Error('path'); - if (require('querystring').stringify({ a: 1, b: 'x y' }) !== 'a=1&b=x%20y') throw new Error('querystring'); - if (require('url').parse('https://example.com:8080/p?q=1').port !== '8080') throw new Error('url'); - if (require('util').format('%s=%d', 'a', 1) !== 'a=1') throw new Error('util'); - require('assert').deepStrictEqual({ a: [1] }, { a: [1] }); - if (require('punycode').toASCII('mañana.com') !== 'xn--maana-pta.com') throw new Error('punycode'); - if (new (require('string_decoder').StringDecoder)('utf8').write(Buffer.from('é')) !== 'é') throw new Error('string_decoder'); - if (typeof require('stream').Readable !== 'function') throw new Error('stream'); - if (typeof require('timers').setTimeout !== 'function') throw new Error('timers'); - if (typeof _ !== 'function' || typeof CryptoJS.MD5 !== 'function') throw new Error('globals'); - "#); - assert_eq!(outcome.failure, None); - }); + hold( + before, + &[ + ( + "[require('lodash').chunk([1, 2, 3], 2).length, _.chunk([1, 2, 3], 2).length]", + "[2,2]", + ), + ( + "[require('moment')('2026-10-19').format('DD/MM/YYYY'), typeof moment]", + r#"["19/10/2026","function"]"#, + ), + ( + "require('chai').expect(1).to.equal(1) !== undefined", + "true", + ), + ( + "CryptoJS.SHA256('abc').toString() === require('crypto-js').SHA256('abc').toString()", + "true", + ), + ( + "CryptoJS.SHA256('abc').toString()", + r#""ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad""#, + ), + ("/^[0-9a-f-]{36}$/.test(require('uuid').v4())", "true"), + ( + "new (require('ajv'))().validate({ type: 'object', required: ['id'] }, { id: 1 })", + "true", + ), + ( + "[tv4.validate({ id: 1 }, { type: 'object' }), tv4.validate(1, { type: 'object' })]", + "[true,false]", + ), + ( + "(() => { let read; require('xml2js').parseString('1', { async: false }, (error, result) => { read = result; }); return read; })()", + r#"{"a":{"b":["1"]}}"#, + ), + ( + "[require('cheerio').load('

    Bonjour

    ')('.x').text(), typeof cheerio.load]", + r#"["Bonjour","function"]"#, + ), + ( + "require('csv-parse/lib/sync')('a,b\\n1,2', { columns: true })", + r#"[{"a":"1","b":"2"}]"#, + ), + ( + "require('csv-parse/sync').parse('a,b\\n1,2')", + r#"[["a","b"],["1","2"]]"#, + ), + ( + "[Buffer.from('DevNotes').toString('base64'), require('node:buffer').Buffer === Buffer]", + r#"["RGV2Tm90ZXM=",true]"#, + ), + ( + "(() => { const events = new (require('events'))(); let heard = 0; events.on('x', (n) => { heard = n; }); events.emit('x', 3); return heard; })()", + "3", + ), + ( + "[require('path').join('/a', 'b', '../c'), require('path-browserify') === require('path/')]", + r#"["/a/c",true]"#, + ), + ( + "require('querystring').stringify({ a: 1, b: 'x y' })", + r#""a=1&b=x%20y""#, + ), + ( + "require('url').parse('https://example.com:8080/p?q=1').port", + r#""8080""#, + ), + ("require('util').format('%s=%d', 'a', 1)", r#""a=1""#), + ( + "require('assert').deepStrictEqual({ a: [1] }, { a: [1] })", + "undefined", + ), + ( + "require('punycode').toASCII('mañana.com')", + r#""xn--maana-pta.com""#, + ), + ( + "new (require('string_decoder').StringDecoder)('utf8').write(Buffer.from('é'))", + r#""é""#, + ), + ( + "[typeof require('stream').Readable, typeof require('timers').setTimeout]", + r#"["function","function"]"#, + ), + ( + "[require('atob')('YQ=='), require('btoa')('a')]", + r#"["a","YQ=="]"#, + ), + ], + ); } /// lodash reads `_` while it loads, and was given itself half made (#1769). @@ -838,13 +1734,139 @@ mod tests { format!("require('{library}') === {global}"), format!("{global} === require('{library}')"), ] { - let outcome = run(&format!("if (!({same})) throw new Error('not the same');")); + let outcome = run(&before(&format!( + "if (!({same})) throw new Error('not the same');" + ))); assert_eq!(outcome.failure, None, "{same}"); } } }); } + #[test] + fn text_and_bytes_are_read_and_written() { + hold( + before, + &[ + ( + "[btoa('é'), atob(btoa('é')), btoa(''), btoa('ab'), btoa('abc')]", + r#"["6Q==","é","","YWI=","YWJj"]"#, + ), + ( + "(() => { try { require('btoa')('€'); } catch (error) { return error.message; } })()", + r#""btoa: the string holds a character outside Latin-1""#, + ), + ( + "(() => { try { require('atob')('*'); } catch (error) { return error.message; } })()", + r#""atob: the string is not Base64""#, + ), + ( + "[[...new TextEncoder().encode('é')], new TextDecoder().decode(new Uint8Array([195, 169])), new TextDecoder().decode(new Uint8Array([195, 169]).buffer), new TextDecoder().decode()]", + r#"[[195,169],"é","é",""]"#, + ), + ( + "[new TextEncoder().encoding, new TextDecoder().encoding, new TextEncoder().encode().length]", + r#"["utf-8","utf-8",0]"#, + ), + ( + "[crypto.getRandomValues(new Uint8Array(4)).length, crypto.getRandomValues(new Uint16Array(64)).some((value) => value !== 0)]", + "[4,true]", + ), + ( + "(() => { try { crypto.getRandomValues([]); } catch (error) { return error.message; } })()", + r#""Expected a typed array""#, + ), + ], + ); + } + + #[test] + fn a_script_knows_where_it_runs() { + hold( + before, + &[ + ( + "pm.info", + r#"{"eventName":"prerequest","iteration":2,"iterationCount":5,"requestName":"Pay","requestId":"r1"}"#, + ), + ("[iteration, pm.execution.location]", r#"[2,["Pay"]]"#), + ], + ); + hold(after, &[("pm.info.eventName", r#""test""#)]); + } + + /// Postman's own services, none of which is here: they answer rather than break a script. + #[test] + fn what_postman_has_and_this_has_not_is_said_or_answers_nothing() { + hosted(|| { + let (engine, seen) = engine(); + let outcome = engine.run( + &before( + "pm.visualizer.set('

    '); pm.visualizer.clear(); + env.set('vault', String(await pm.vault.get('a'))); await pm.vault.set('a', 1); await pm.vault.unset('a'); + try { pm.require('@team/a'); } catch (error) { env.set('require', error.message); }", + ), + SECONDS, + ); + assert_eq!(outcome.failure, None); + assert_eq!(outcome.writes[0].value.as_deref(), Some("undefined")); + assert!( + outcome.writes[1] + .value + .as_deref() + .unwrap() + .contains("not available here") + ); + assert!(seen.borrow().logs[0].text.contains("not supported")); + }); + } + + #[test] + fn console_lines_reach_the_host_with_their_level_and_their_script() { + use crate::http::scripts::model::LogLevel; + hosted(|| { + let (engine, seen) = engine(); + engine.run( + &before( + "console.log('signé', { a: 1 }, 2); console.error(new TypeError('x')); console.info(undefined); + console.debug(null); console.warn('w'); console.trace('t'); console.dir([1]); console.table({ a: 1 }); + console.assert(true, 'held'); console.assert(false, 'not held'); + console.time('a'); console.timeEnd('a'); console.group('g'); console.groupEnd(); console.clear();", + ), + SECONDS, + ); + let said: Vec<_> = seen + .borrow() + .logs + .iter() + .map(|log| (log.level, log.text.clone())) + .collect(); + let expected = [ + (LogLevel::Log, "signé {\"a\":1} 2"), + (LogLevel::Error, "TypeError: x"), + (LogLevel::Info, "undefined"), + (LogLevel::Debug, "null"), + (LogLevel::Warn, "w"), + (LogLevel::Debug, "t"), + (LogLevel::Log, "[1]"), + (LogLevel::Log, "{\"a\":1}"), + (LogLevel::Error, "Assertion failed not held"), + ]; + assert_eq!( + said, + expected.map(|(level, text)| (level, text.to_string())) + ); + assert!( + seen.borrow() + .logs + .iter() + .all(|log| log.script.as_deref() == Some("request:before")) + ); + }); + } + + // ── What a script asks ── + #[test] fn send_request_goes_to_the_host_and_answers_by_callback_or_promise() { hosted(|| { @@ -853,74 +1875,143 @@ mod tests { &before( "pm.sendRequest('https://example.com/a', (error, response) => { if (error) throw error; - env.set('first', response.json().url); + env.set('callback', response.json().url); }); const second = await pm.sendRequest({ url: 'https://example.com/b', method: 'POST', header: { 'Content-Type': 'application/json' }, body: { mode: 'raw', raw: '{}' }, }); - env.set('second', second.code); - try { await pm.sendRequest({ url: 'https://example.com/c', method: 'DELETE' }); } - catch (error) { env.set('refused', error.code); }", + env.set('promise', second.code);", ), - SECOND, + SECONDS, ); assert_eq!(outcome.failure, None); - let values: Vec> = outcome + let values: Vec<_> = outcome .writes .iter() .map(|write| write.value.as_deref()) .collect(); + assert_eq!(values, [Some("https://example.com/a"), Some("200")]); + let calls = &seen.borrow().calls; assert_eq!( - values, - [ - Some("https://example.com/a"), - Some("200"), - Some("httpScriptProtected") - ] + (calls[0].1["method"].as_str(), calls[0].1["script"].as_str()), + (Some("GET"), Some("request:before")) ); - let calls = &seen.borrow().calls; - assert_eq!(calls.len(), 3); - assert_eq!(calls[0].1["method"], "GET"); assert_eq!(calls[1].1["headers"][0]["key"], "Content-Type"); assert_eq!(calls[1].1["body"]["raw"], "{}"); }); } #[test] - fn console_logs_reach_the_host_with_their_script() { + fn a_send_refused_is_an_error_with_its_code_by_callback_or_promise() { + hosted(|| { + let outcome = run(&before( + "const asked = { url: 'https://example.com/c', method: 'DELETE' }; + pm.sendRequest(asked, (error, response) => env.set('callback', error.code + ' ' + response)); + try { await pm.sendRequest(asked); } catch (error) { env.set('promise', error.message); }", + )); + let values: Vec<_> = outcome + .writes + .iter() + .map(|write| write.value.as_deref()) + .collect(); + assert_eq!( + values, + [Some("httpScriptProtected undefined"), Some("refused")] + ); + }); + } + + #[test] + fn a_jar_s_calls_name_their_url_and_their_cookie() { hosted(|| { let (engine, seen) = engine(); engine.run( - &before("console.log('signé', { a: 1 }, 2); console.error(new TypeError('x'));"), - SECOND, + &before( + "const jar = pm.cookies.jar(); + jar.get('https://a.test', 'one', () => {}); + jar.getAll('https://a.test', { any: 1 }, () => {}); + jar.set('https://a.test', 'two', 2); + jar.set('https://a.test', { name: 'three', value: { a: 1 }, httpOnly: true, path: '/p' }, () => {}); + jar.unset('https://a.test', 'four'); + jar.clear('https://a.test');", + ), + SECONDS, ); - let logs = &seen.borrow().logs; - assert_eq!(logs[0].text, "signé {\"a\":1} 2"); - assert_eq!(logs[0].script.as_deref(), Some("request:before")); - assert_eq!(logs[1].text, "TypeError: x"); + let calls = &seen.borrow().calls; + let kinds: Vec<_> = calls.iter().map(|(kind, _)| kind.as_str()).collect(); + assert_eq!( + kinds, + [ + "jarGet", "jarAll", "jarSet", "jarSet", "jarUnset", "jarClear" + ] + ); + assert!( + calls + .iter() + .all(|(_, payload)| payload["url"] == "https://a.test") + ); + assert_eq!(calls[2].1["cookie"], json!({ "name": "two", "value": "2" })); + assert_eq!( + calls[3].1["cookie"], + json!({ "name": "three", "value": "{\"a\":1}", "httpOnly": true, "path": "/p" }) + ); + assert_eq!(calls[4].1["name"], "four"); }); } #[test] - fn a_script_can_skip_the_request_or_name_the_next_one() { + fn a_script_can_skip_the_request_before_it_leaves_alone() { hosted(|| { - let outcome = run("pm.execution.skipRequest(); pm.execution.setNextRequest('Reçu');"); - assert!(outcome.skip); - assert!(outcome.next.set); - assert_eq!(outcome.next.name.as_deref(), Some("Reçu")); - assert!(!run("").next.set); + assert!(run(&before("pm.execution.skipRequest();")).skip); + assert!(!run(&before("")).skip); + let failure = run(&after("pm.execution.skipRequest();")).failure.unwrap(); + assert!( + failure.message.contains("only before the request is sent"), + "{}", + failure.message + ); }); } #[test] - fn a_stack_names_the_script_and_the_line() { - assert_eq!(place_in(" at f (script-2:12:5)\n"), Some((2, 12))); - assert_eq!( - place_in(" at prelude:40\n at (script-0:3)\n"), - Some((0, 3)) - ); - assert_eq!(place_in(" at prelude:40\n"), None); + fn a_script_names_the_next_request_or_none_to_end_the_run() { + hosted(|| { + let next = |source: &str| { + let next = run(&after(source)).next; + (next.set, next.name) + }; + assert_eq!(next(""), (false, None)); + assert_eq!( + next("pm.execution.setNextRequest('Reçu');"), + (true, Some("Reçu".to_string())) + ); + assert_eq!(next("pm.execution.setNextRequest(null);"), (true, None)); + }); + } + + /// A phase starts afresh: what one left to Rust is not left again by the next. + #[test] + fn a_phase_leaves_only_what_it_did() { + hosted(|| { + let (engine, _) = engine(); + engine.run(&before("env.set('a', 1); test('t', () => {}); pm.execution.skipRequest(); pm.execution.setNextRequest('x');"), SECONDS); + let outcome = engine.run(&before(""), SECONDS); + assert!( + outcome.writes.is_empty() + && outcome.tests.is_empty() + && !outcome.skip + && !outcome.next.set + ); + }); + } + + /// As Postman's: a name assigned without being declared is a variable of the script. + #[test] + fn a_script_runs_in_sloppy_mode() { + let outcome = run(&before("undeclared = 3; console.log(String(undeclared));")); + + assert!(outcome.failure.is_none(), "{:?}", outcome.failure); } } From 267c9e89e8bad7d53ecc2361cf9bb91eddf4b272 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:18:40 +0100 Subject: [PATCH 67/95] Preferences: a shortcut reset to its default can be applied (#1801) Co-authored-by: Claude Opus 5.5 --- crates/ui/src/services/preferences.rs | 12 ++++++------ crates/ui/src/services/settings.rs | 13 +++++++++++++ 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/crates/ui/src/services/preferences.rs b/crates/ui/src/services/preferences.rs index 18d997bcb..cab223d29 100644 --- a/crates/ui/src/services/preferences.rs +++ b/crates/ui/src/services/preferences.rs @@ -2,7 +2,7 @@ //! string. Two of them: the application's, in the profile, and the open library's, in its directory, //! for `devnotes.notes.*`. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::io; use std::path::Path; @@ -40,12 +40,12 @@ impl Preferences { self.0.get(key).and_then(Value::as_str) } - /// How many keys of `other` say something else here. + /// How many keys the two do not say alike, one of them alone having it included. pub fn differences(&self, other: &Self) -> u32 { - let differing = other - .0 - .iter() - .filter(|(key, value)| self.0.get(*key) != Some(*value)); + let keys: BTreeSet<&String> = self.0.keys().chain(other.0.keys()).collect(); + let differing = keys + .into_iter() + .filter(|key| self.0.get(*key) != other.0.get(*key)); u32::try_from(differing.count()).unwrap_or(u32::MAX) } diff --git a/crates/ui/src/services/settings.rs b/crates/ui/src/services/settings.rs index a09594010..f8095c754 100644 --- a/crates/ui/src/services/settings.rs +++ b/crates/ui/src/services/settings.rs @@ -529,6 +529,19 @@ mod tests { assert!(!draft.is_changed()); } + /// A key put back leaves the file: what is no longer there counts too. + #[test] + fn a_key_put_back_to_its_default_waits_for_apply() { + let mut draft = SettingsDraft::open(Settings { + bindings: moved_key(), + ..Settings::default() + }); + assert_eq!(draft.pending(), 0); + + draft.edit(|settings| settings.bindings.reset(shortcuts::ACTIONS[9])); + assert_eq!(draft.pending(), 1); + } + #[test] fn the_defaults_of_the_reference_read_from_an_empty_file() { let read = Settings::read(&Preferences::default()); From a90fb4be8f075af5df0cb6bdb13f15b844106c68 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:18:58 +0100 Subject: [PATCH 68/95] Tools: unit tests rewritten for what each tool answers (#1803) Co-authored-by: Claude Opus 5.5 --- crates/ui/src/tools/catalogue.rs | 2 + .../ui/src/tools/catalogue/answers_tests.rs | 819 ++++++++++++++++++ crates/ui/src/tools/catalogue/calc_tests.rs | 12 +- .../ui/src/tools/catalogue/encoding_tests.rs | 52 +- 4 files changed, 856 insertions(+), 29 deletions(-) create mode 100644 crates/ui/src/tools/catalogue/answers_tests.rs diff --git a/crates/ui/src/tools/catalogue.rs b/crates/ui/src/tools/catalogue.rs index 55ec25e05..6c4a0bb8b 100644 --- a/crates/ui/src/tools/catalogue.rs +++ b/crates/ui/src/tools/catalogue.rs @@ -625,6 +625,8 @@ pub static TOOLS: [ToolEntry; 32] = [ ), ]; +#[cfg(test)] +mod answers_tests; #[cfg(test)] mod calc_tests; #[cfg(test)] diff --git a/crates/ui/src/tools/catalogue/answers_tests.rs b/crates/ui/src/tools/catalogue/answers_tests.rs new file mode 100644 index 000000000..62d9a1051 --- /dev/null +++ b/crates/ui/src/tools/catalogue/answers_tests.rs @@ -0,0 +1,819 @@ +//! What each tool answers, case by case: what is typed, what is pressed, and the line that says it. + +use std::sync::Arc; + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use platform::dialog::{Fixed, NoDialog}; + +use super::text_tests::{click, has, opened, output_values, type_in, value_of, waits_for}; +use crate::notes::bench::{Bench, settle}; +use crate::testing::painted; + +enum Do { + /// Into the field of that id. + Type(&'static str, &'static str), + Press(&'static str), +} +use Do::{Press, Type}; + +/// The tool with each thing done, and the line of that id on screen. +#[track_caller] +fn says(tool: &str, done: &[Do], id: &str) -> Harness<'static, Bench> { + let mut harness = opened(tool); + // The whole page: what is below the window is not drawn. + harness.set_size(egui::vec2(1_300.0, 3_000.0)); + settle(&mut harness); + for each in done { + match each { + Type(field, text) => type_in(&mut harness, field, text), + Press(control) => click(&mut harness, control), + } + } + waits_for(&mut harness, &format!("{tool} says {id}"), |harness| { + has(harness, id) + }); + for text in painted(&harness) { + assert!( + !text.contains("{{") && !text.starts_with("tools."), + "{tool}: {text}" + ); + } + harness +} + +fn saying(harness: &Harness<'_, Bench>, id: &str, part: &str) { + let said = value_of(harness, id); + assert!(said.contains(part), "{id}: {said:?} lacks {part:?}"); +} + +// Base64 + +#[test] +fn a_text_is_written_in_its_six_encodings_with_what_it_weighs() { + let harness = says( + "base64", + &[Type("base64-input", "Café")], + "base64-encodings", + ); + let values = output_values(&harness); + + for value in [ + "Q2Fmw6k=", + "Q2Fmw6k", + "INQWNQ5J", + "43 61 66 c3 a9", + "67 97 102 195 169", + ] { + assert!( + values.iter().any(|shown| shown == value), + "{value} in {values:?}" + ); + } + saying(&harness, "base64-facts", "é"); +} + +#[test] +fn hexadecimal_is_spaced_and_lowercase_unless_asked() { + let harness = says( + "base64", + &[ + Type("base64-input", "Café"), + Press("base64-spaced"), + Press("base64-uppercase"), + ], + "base64-encodings", + ); + + assert!( + output_values(&harness) + .iter() + .any(|value| value == "436166C3A9") + ); +} + +#[test] +fn what_is_decoded_says_how_it_was_read() { + let harness = says( + "base64", + &[ + Press("base64-direction-1"), + Type("base64-input", "Q2Fmw6k="), + ], + "base64-output", + ); + saying(&harness, "base64-output", "Café"); + assert!(has(&harness, "base64-reading")); + + let harness = says( + "base64", + &[ + Press("base64-direction-1"), + Type("base64-input", "data:text/plain;base64,Q2Fmw6k="), + ], + "base64-output", + ); + saying(&harness, "base64-reading", "text/plain"); +} + +#[test] +fn what_does_not_decode_says_where() { + for (typed, reading) in [ + ("Q2F*w6k=", "base64-reading-choice-1"), + ("4x", "base64-reading-choice-4"), + ("012", "base64-reading-choice-5"), + ] { + let harness = says( + "base64", + &[ + Press("base64-direction-1"), + Type("base64-input", typed), + Press(reading), + ], + "base64-problem", + ); + assert!(!value_of(&harness, "base64-problem").is_empty()); + } +} + +#[test] +fn bytes_that_are_no_text_are_offered_as_a_file() { + let directory = tempfile::tempdir().unwrap(); + let file = directory.path().join("decoded.bin"); + let mut harness = says( + "base64", + &[ + Press("base64-direction-1"), + Type("base64-input", "/wD+AQ=="), + ], + "base64-binary", + ); + harness.state_mut().state.dialog = Arc::new(NoDialog); + click(&mut harness, "base64-save-file"); + harness.state_mut().state.dialog = Arc::new(Fixed(file.clone())); + assert!(!file.exists()); + + click(&mut harness, "base64-save-file"); + waits_for(&mut harness, "the file is written", |_| file.exists()); + settle(&mut harness); + assert_eq!(std::fs::read(&file).unwrap(), [0xff, 0x00, 0xfe, 0x01]); +} + +#[test] +fn a_file_is_read_as_its_two_base64() { + let directory = tempfile::tempdir().unwrap(); + let file = directory.path().join("cafe.txt"); + std::fs::write(&file, "Café").unwrap(); + let mut harness = opened("base64"); + harness.state_mut().state.dialog = Arc::new(Fixed(file)); + click(&mut harness, "base64-source-1"); + click(&mut harness, "base64-pick-file"); + waits_for(&mut harness, "the file is read", |harness| { + has(harness, "base64-file") + }); + + saying(&harness, "base64-file", "cafe.txt"); + assert_eq!(output_values(&harness), ["Q2Fmw6k=", "Q2Fmw6k"]); +} + +#[test] +fn a_file_that_is_not_there_says_so() { + let mut harness = opened("base64"); + harness.state_mut().state.dialog = Arc::new(Fixed("no-such-file.bin".into())); + click(&mut harness, "base64-source-1"); + click(&mut harness, "base64-pick-file"); + + waits_for(&mut harness, "it is refused", |harness| { + has(harness, "base64-file-problem") + }); +} + +#[test] +fn a_picture_decoded_is_shown_with_its_size() { + // A 1 × 1 GIF. + let gif = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"; + let mut harness = says( + "base64", + &[Press("base64-direction-1"), Type("base64-input", gif)], + "base64-image-facts", + ); + saying(&harness, "base64-image-facts", "GIF · 1 × 1 px"); + waits_for(&mut harness, "it is drawn", |harness| { + has(harness, "base64-image-picture") + }); +} + +// Cron + +#[test] +fn each_expression_is_read_in_words() { + for expression in [ + "* * * * * *", + "*/10 * * * * *", + "5,20 * * * *", + "0 * * * *", + "0 */4 * * *", + "0 2 1-15/2 * *", + "0 2 L * *", + "0 2 15W * *", + "0 2 * * 5L", + "0 2 * * 5#2", + "0 2 1 1,7 *", + "0 2 10 3 *", + ] { + let harness = says("cron", &[Type("cron-input", expression)], "cron-sentence"); + assert!( + value_of(&harness, "cron-sentence").chars().count() > 8, + "{expression}" + ); + } +} + +#[test] +fn a_shortcut_is_expanded_and_a_reboot_has_no_time() { + let harness = says("cron", &[Type("cron-input", "@daily")], "cron-expanded"); + saying(&harness, "cron-expanded", "0 0 * * *"); + says("cron", &[Type("cron-input", "@reboot")], "cron-reboot"); +} + +#[test] +fn a_day_of_the_month_and_of_the_week_are_either_one() { + says( + "cron", + &[Type("cron-input", "0 2 1 * 1")], + "cron-either-day", + ); +} + +#[test] +fn a_date_asked_of_a_schedule_is_answered_with_the_nearest_runs() { + let harness = says( + "cron", + &[ + Type("cron-input", "0 2 * * *"), + Type("cron-check", "2026-10-14 03:00"), + ], + "cron-nearest-after", + ); + saying(&harness, "cron-nearest-before", "2026-10-14 02:00"); + saying(&harness, "cron-nearest-after", "2026-10-15 02:00"); + says( + "cron", + &[Type("cron-input", "0 2 * * *"), Type("cron-check", "soon")], + "cron-verdict", + ); +} + +#[test] +fn a_window_is_counted_or_says_why_not() { + let window = |from, until| { + [ + Type("cron-input", "0 2 * * *"), + Type("cron-from", from), + Type("cron-until", until), + ] + }; + let harness = says( + "cron", + &window("2026-10-01", "2026-10-31"), + "cron-window-count", + ); + saying(&harness, "cron-window-count", "30"); + for (from, until) in [ + ("soon", "2026-10-31"), + ("2026-10-31", "2026-10-01"), + ("2026-10-01", "2126-10-01"), + ] { + says("cron", &window(from, until), "cron-window-problem"); + } +} + +#[test] +fn a_long_window_lists_its_first_and_last_runs() { + let harness = says( + "cron", + &[ + Type("cron-input", "0 * * * *"), + Type("cron-from", "2026-10-01"), + Type("cron-until", "2026-10-31"), + ], + "cron-window-gap", + ); + assert!(has(&harness, "cron-run")); +} + +#[test] +fn an_expression_that_never_runs_says_so() { + says("cron", &[Type("cron-input", "0 0 30 2 *")], "cron-no-runs"); +} + +#[test] +fn a_zone_is_found_chosen_and_left_for_the_local_one() { + let mut harness = says( + "cron", + &[ + Type("cron-input", "0 2 * * *"), + Type("cron-zone-search", "auckland"), + ], + "cron-zone-found-Pacific/Auckland", + ); + click(&mut harness, "cron-zone-found-Pacific/Auckland"); + waits_for(&mut harness, "it is chosen", |harness| { + has(harness, "cron-zone-local") + }); + click(&mut harness, "cron-zone-local"); + assert!(!has(&harness, "cron-zone-local")); +} + +// Dates and durations + +#[test] +fn a_gap_is_measured_or_says_why_not() { + let gap = |from, to| [Type("dates-from", from), Type("dates-to", to)]; + says( + "dates", + &gap("2026-10-14 10:00", "2026-10-16 12:30"), + "dates-gap-calendar", + ); + says( + "dates", + &gap("2026-10-16", "2026-10-14"), + "dates-gap-negative", + ); + says("dates", &gap("soon", "2026-10-14"), "dates-gap-problem"); +} + +#[test] +fn now_is_put_where_a_gap_ends() { + let mut harness = opened("dates"); + type_in(&mut harness, "dates-from", "2026-01-01"); + click(&mut harness, "dates-to-now"); + + assert!(!value_of(&harness, "dates-to").is_empty()); +} + +#[test] +fn a_duration_is_read_or_says_why_not() { + says( + "dates", + &[Type("dates-duration", "PT1H30M")], + "dates-duration-read", + ); + says( + "dates", + &[Type("dates-duration", "1h 30m")], + "dates-duration-read", + ); + says("dates", &[Type("dates-duration", "P1M")], "dates-no-totals"); + says( + "dates", + &[Type("dates-duration", "1 furlong")], + "dates-duration-problem", + ); +} + +#[test] +fn a_date_that_does_not_read_says_so() { + for typed in ["the day before", "2026-13-45"] { + says("dates", &[Type("dates-input", typed)], "dates-problem"); + } +} + +// Time zones + +#[test] +fn zones_are_added_found_by_their_city_and_removed() { + let mut harness = says( + "zones", + &[ + Type("zones-input", "2026-10-14 10:00"), + Type("zones-search", "auckland"), + ], + "zones-found-Pacific/Auckland", + ); + click(&mut harness, "zones-found-Pacific/Auckland"); + waits_for(&mut harness, "it is a row", |harness| { + has(harness, "zones-remove-Pacific/Auckland") + }); + click(&mut harness, "zones-remove-Pacific/Auckland"); + assert!(!has(&harness, "zones-remove-Pacific/Auckland")); + says("zones", &[Type("zones-search", "zzzzz")], "zones-no-match"); +} + +#[test] +fn a_time_that_does_not_read_says_so() { + says( + "zones", + &[Type("zones-input", "half past")], + "zones-problem", + ); +} + +// Hashes + +#[test] +fn a_digest_says_what_it_could_be() { + for digest in [ + "d41d8cd98f00b204e9800998ecf8427e", + "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824", + "abc", + "not a digest at all", + "LPJNul+wow4m6DsqxbninhsWHlwfp0JecwQzYpOLmCQ=", + ] { + says("hash", &[Type("hash-expected", digest)], "hash-shape"); + } +} + +#[test] +fn a_digest_that_is_not_the_text_s_says_so() { + let digest = "d41d8cd98f00b204e9800998ecf8427e"; + let harness = says( + "hash", + &[Type("hash-input", "hello"), Type("hash-expected", digest)], + "hash-verdict", + ); + assert!(!value_of(&harness, "hash-verdict").contains("MD5 matches")); +} + +#[test] +fn a_file_is_hashed_and_one_that_is_not_there_says_so() { + let directory = tempfile::tempdir().unwrap(); + let file = directory.path().join("hello.txt"); + std::fs::write(&file, "hello").unwrap(); + let mut harness = opened("hash"); + harness.state_mut().state.dialog = Arc::new(Fixed(file)); + click(&mut harness, "hash-source-1"); + click(&mut harness, "hash-pick-file"); + waits_for(&mut harness, "it is hashed", |harness| { + has(harness, "hash-results") + }); + let sha256 = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"; + assert!(output_values(&harness).iter().any(|value| value == sha256)); + + harness.state_mut().state.dialog = Arc::new(Fixed("no-such-file.txt".into())); + click(&mut harness, "hash-pick-file"); + waits_for(&mut harness, "it is refused", |harness| { + has(harness, "hash-problem") + }); +} + +// Checks + +#[test] +fn each_iban_says_what_is_wrong_with_it() { + for (iban, part) in [ + ("FR76 3000 6000 0112 3456 7890 189", ""), + ("FR77 3000 6000 0112 3456 7890 189", "76"), + ("FR76 3000 6000 0112", "27"), + ("FR76 30!0", ""), + ("ZZ68 5390 0754 7034", "ZZ"), + ("DE89 3704 0044 0532 0130 00", ""), + ("GB82 WEST 1234 5698 7654 32", ""), + ] { + let mut harness = opened("checks"); + type_in(&mut harness, "checks-input", iban); + waits_for(&mut harness, iban, |harness| { + has(harness, "checks-verdict") || has(harness, "checks-problem") + }); + assert!( + painted(&harness).iter().any(|text| text.contains(part)), + "{iban}" + ); + } +} + +#[test] +fn a_number_is_checked_by_luhn_or_says_why_not() { + for (number, id) in [ + ("4539 1488 0343 6467", "checks-verdict"), + ("4539 1488 0343 6468", "checks-verdict"), + ("7", "checks-problem"), + ("4539x1488", "checks-problem"), + ] { + says( + "checks", + &[Press("checks-kind-1"), Type("checks-input", number)], + id, + ); + } +} + +// Networks + +#[test] +fn a_network_of_either_family_is_described() { + for network in [ + "10.0.0.0/8", + "192.168.1.17/29", + "203.0.113.0/27", + "2001:db8::/32", + "fe80::1/64", + "10.0.0.1", + ] { + says("cidr", &[Type("cidr-network", network)], "cidr-facts"); + } + says( + "cidr", + &[Type("cidr-network", "300.0.0.0/8")], + "cidr-problem", + ); +} + +#[test] +fn an_address_is_in_a_network_or_out_of_it() { + for address in ["10.1.2.3", "192.168.0.1", "not an address"] { + says( + "cidr", + &[ + Type("cidr-network", "10.0.0.0/8"), + Type("cidr-member", address), + ], + "cidr-membership", + ); + } +} + +#[test] +fn a_network_is_split_and_the_rest_counted() { + let mut harness = says( + "cidr", + &[Type("cidr-network", "10.0.0.0/8")], + "cidr-split-choice-11", + ); + click(&mut harness, "cidr-split-choice-11"); + waits_for(&mut harness, "it is split", |harness| { + painted(harness) + .iter() + .any(|text| text.contains("10.32.0.0/11")) + }); +} + +#[test] +fn a_plan_says_what_has_no_room_and_what_does_not_read() { + let plan = "web 100 +huge 100000 +nothing"; + let harness = says( + "cidr", + &[Type("cidr-network", "10.0.0.0/24"), Type("cidr-plan", plan)], + "cidr-plan-lines", + ); + assert!( + painted(&harness) + .iter() + .any(|text| text.contains("10.0.0.0/25")) + ); + assert!( + painted(&harness) + .iter() + .any(|text| text.contains("nothing")) + ); +} + +#[test] +fn a_list_of_networks_is_summed_and_what_does_not_read_is_named() { + let list = "10.0.0.0/25 +10.0.0.128/25 +abc"; + let harness = says( + "cidr", + &[Type("cidr-network", "10.0.0.0/8"), Type("cidr-list", list)], + "cidr-list-unreadable", + ); + saying(&harness, "cidr-list-unreadable", "abc"); + assert!( + painted(&harness) + .iter() + .any(|text| text.contains("10.0.0.0/24")) + ); +} + +// Differences + +#[test] +fn two_texts_are_compared_by_lines_words_or_characters() { + for granularity in [ + "text-diff-granularity-0", + "text-diff-granularity-1", + "text-diff-granularity-2", + ] { + let harness = says( + "diff", + &[ + Type("text-diff-a", "one two\nthree"), + Type("text-diff-b", "one too\nthree\nfour"), + Press(granularity), + ], + "text-diff-added", + ); + assert!(has(&harness, "text-diff-removed")); + } +} + +#[test] +fn a_difference_reads_side_by_side_or_as_one() { + let harness = says( + "diff", + &[ + Type("text-diff-a", "one\ntwo"), + Type("text-diff-b", "one\nthree"), + Press("text-diff-layout-1"), + ], + "text-diff-unified", + ); + let lines: Vec = harness + .query_all_by(|node| node.author_id() == Some("text-diff-unified-line")) + .filter_map(|node| node.accesskit_node().label()) + .collect(); + assert!( + lines.contains(&"-two".to_owned()) && lines.contains(&"+three".to_owned()), + "{lines:?}" + ); +} + +#[test] +fn what_is_ignored_leaves_two_texts_identical() { + says( + "diff", + &[ + Type("text-diff-a", "One two"), + Type("text-diff-b", "one two"), + Press("text-diff-ignore-case"), + Press("text-diff-ignore-whitespace"), + ], + "text-diff-identical", + ); +} + +#[test] +fn two_documents_are_offered_as_values_and_a_text_as_text() { + let mut harness = says( + "diff", + &[ + Type("text-diff-a", r#"{"a": 1}"#), + Type("text-diff-b", r#"{"a": 2}"#), + ], + "text-diff-json", + ); + click(&mut harness, "text-diff-as-values"); + waits_for(&mut harness, "compared as values", |harness| { + has(harness, "structured-diff-modified") + }); + + let mut harness = says( + "diff", + &[ + Press("diff-mode-1"), + Type("structured-diff-a", "just words"), + Type("structured-diff-b", "other words"), + ], + "structured-diff-not-structured-a", + ); + click(&mut harness, "structured-diff-as-text-a"); + waits_for(&mut harness, "compared as texts", |harness| { + has(harness, "text-diff-rows") + }); +} + +#[test] +fn values_are_compared_key_by_key_in_any_format() { + for (a, b) in [ + (r#"{"a": 1, "c": {"d": 1}}"#, r#"{"a": 2, "e": {"f": 1}}"#), + (r#"{"a": [1, 2]}"#, r#"{"a": null}"#), + (r#"{"b": [1, 2]}"#, r#"{"b": [2, 1]}"#), + ("a: 1\nb: two\n", "a: 1\nb: three\nc: 4\n"), + ("a = 1\n[t]\nb = 2\n", "a = 1\n[t]\nb = 3\n"), + ("1", "2"), + ] { + says( + "diff", + &[ + Press("diff-mode-1"), + Type("structured-diff-a", a), + Type("structured-diff-b", b), + ], + "structured-diff-change", + ); + } +} + +#[test] +fn a_change_of_values_is_shown_where_it_is() { + let mut harness = says( + "diff", + &[ + Press("diff-mode-1"), + Type("structured-diff-a", r#"{"a": 1, "b": 2}"#), + Type("structured-diff-b", r#"{"a": 1, "b": 3}"#), + ], + "structured-diff-change", + ); + harness + .query_all_by(|node| node.author_id() == Some("structured-diff-change")) + .next() + .unwrap() + .click(); + settle(&mut harness); + click(&mut harness, "structured-diff-layout-1"); + assert!(has(&harness, "structured-diff-line")); +} + +#[test] +fn values_that_do_not_read_or_do_not_differ_say_so() { + says( + "diff", + &[ + Press("diff-mode-1"), + Type("structured-diff-a", r#"{"a": 1"#), + Type("structured-diff-b", r#"{"a": 1}"#), + ], + "structured-diff-unreadable-a", + ); + says( + "diff", + &[ + Press("diff-mode-1"), + Type("structured-diff-a", r#"{"a": 1}"#), + Type("structured-diff-b", r#"{ "a":1 }"#), + ], + "structured-diff-identical", + ); +} + +// The others + +#[test] +fn a_size_or_a_transfer_that_does_not_read_says_so() { + says( + "sizes", + &[Type("sizes-input", "12 parsecs")], + "sizes-problem", + ); + says("sizes", &[Type("sizes-input", "1536 KiB")], "sizes-results"); +} + +#[test] +fn permissions_are_read_from_either_notation_or_refused() { + says( + "permissions", + &[Type("permissions-symbolic", "rwxz")], + "permissions-problem", + ); + says( + "permissions", + &[Type("permissions-umask", "9")], + "permissions-umask-problem", + ); + says("permissions", &[], "permissions-umask-result"); +} + +#[test] +fn a_document_that_does_not_convert_says_so() { + says( + "convert", + &[Type("convert-input", r#"{"a": "#)], + "convert-unreadable", + ); +} + +#[test] +fn a_token_that_is_no_token_says_so() { + says("jwt", &[Type("jwt-token", "not.a.token")], "jwt-problem"); +} + +#[test] +fn a_url_that_does_not_read_says_so() { + says( + "url-codec", + &[Press("url-tab-1"), Type("url-parser-input", "http://")], + "url-parser-problem", + ); +} + +/// What was shown of it goes with it, and nothing is left for the next opening. +#[test] +fn a_tool_cleared_has_nothing_typed_left() { + for (tool, fields) in [ + ("base64", vec!["base64-input"]), + ("cron", vec!["cron-input"]), + ("dates", vec!["dates-input"]), + ("checks", vec!["checks-input"]), + ("cidr", vec!["cidr-network"]), + ("diff", vec!["text-diff-a", "text-diff-b"]), + ("hash", vec!["hash-input"]), + ("jwt", vec!["jwt-token"]), + ("url-codec", vec!["url-codec-decoded", "url-codec-encoded"]), + ("convert", vec!["convert-input"]), + ("text-stats", vec!["text-stats-input"]), + ] { + let mut harness = opened(tool); + click(&mut harness, "tool-sample"); + waits_for(&mut harness, tool, |harness| { + !value_of(harness, fields[0]).is_empty() + }); + click(&mut harness, "tool-clear"); + for field in fields { + assert_eq!(value_of(&harness, field), "", "{tool} {field}"); + } + } +} diff --git a/crates/ui/src/tools/catalogue/calc_tests.rs b/crates/ui/src/tools/catalogue/calc_tests.rs index 34fa2caa9..1435ee2d7 100644 --- a/crates/ui/src/tools/catalogue/calc_tests.rs +++ b/crates/ui/src/tools/catalogue/calc_tests.rs @@ -166,24 +166,16 @@ fn a_valid_iban_names_its_country_and_its_parts() { } #[test] -fn a_wrong_card_number_gives_the_digit_it_asks_for_and_leaves_no_trace() { +fn a_wrong_card_number_is_invalid_and_never_saved_as_a_note() { let mut harness = opened("checks"); type_in(&mut harness, "checks-input", "4111111111111112"); waits_for(&mut harness, "the number is checked", |harness| { has(harness, "checks-result") }); - assert_eq!(value_of(&harness, "checks-verdict"), "Invalid"); + assert_eq!(value_of(&harness, "checks-verdict"), "Invalid"); assert!(!has(&harness, "tool-save-as-note")); - click(&mut harness, "tool-back"); - let bench = harness.state_mut(); - let open = crate::action::Action::Tools(crate::tools::Action::Open("checks")); - bench - .state - .apply(open, &egui::Context::default(), &bench.backend); - settle(&mut harness); - assert_eq!(value_of(&harness, "checks-input"), ""); } #[test] diff --git a/crates/ui/src/tools/catalogue/encoding_tests.rs b/crates/ui/src/tools/catalogue/encoding_tests.rs index f26536847..3040d6a03 100644 --- a/crates/ui/src/tools/catalogue/encoding_tests.rs +++ b/crates/ui/src/tools/catalogue/encoding_tests.rs @@ -65,7 +65,7 @@ fn the_hash_tool_finds_the_algorithm_of_a_digest() { } #[test] -fn an_hmac_key_changes_the_digests_and_goes_with_the_tool() { +fn an_hmac_key_changes_the_digests() { let mut harness = opened("hash"); type_in(&mut harness, "hash-input", "hello"); waits_for(&mut harness, "it is hashed", |harness| { @@ -78,15 +78,38 @@ fn an_hmac_key_changes_the_digests_and_goes_with_the_tool() { waits_for(&mut harness, "it is keyed", |harness| { output_values(harness) != plain }); +} - click(&mut harness, "tool-back"); - let bench = harness.state_mut(); - let open = crate::action::Action::Tools(crate::tools::Action::Open("hash")); - bench - .state - .apply(open, &egui::Context::default(), &bench.backend); - settle(&mut harness); - assert_eq!(value_of(&harness, "hash-key"), ""); +/// Nothing secret outlives the tool it was typed in. +#[test] +fn a_secret_typed_goes_with_its_tool() { + for (tool, before, field) in [ + ("hash", Some("hash-hmac"), "hash-key"), + ("jwt", None, "jwt-token"), + ("jwt", None, "jwt-secret"), + ("checks", None, "checks-input"), + ] { + let mut harness = opened(tool); + if let Some(before) = before { + click(&mut harness, before); + } + type_in(&mut harness, field, "4111111111111111"); + assert!(!value_of(&harness, field).is_empty(), "{field}"); + + click(&mut harness, "tool-back"); + let bench = harness.state_mut(); + let open = crate::action::Action::Tools(crate::tools::Action::Open(tool)); + bench + .state + .apply(open, &egui::Context::default(), &bench.backend); + settle(&mut harness); + if let Some(before) = before + && !has(&harness, field) + { + click(&mut harness, before); + } + assert_eq!(value_of(&harness, field), "", "{field}"); + } } #[test] @@ -118,7 +141,7 @@ fn no_character_set_left_is_said() { } #[test] -fn a_token_is_decoded_verified_and_gone_with_the_tool() { +fn a_token_is_decoded_and_its_signature_verified() { let mut harness = opened("jwt"); click(&mut harness, "tool-sample"); @@ -128,15 +151,6 @@ fn a_token_is_decoded_verified_and_gone_with_the_tool() { assert!(value_of(&harness, "jwt-header").contains("HS256")); assert!(value_of(&harness, "jwt-payload").contains("Ada Lovelace")); assert!(value_of(&harness, "jwt-verification").contains("Valid signature.")); - - click(&mut harness, "tool-back"); - let bench = harness.state_mut(); - let open = crate::action::Action::Tools(crate::tools::Action::Open("jwt")); - bench - .state - .apply(open, &egui::Context::default(), &bench.backend); - settle(&mut harness); - assert_eq!(value_of(&harness, "jwt-token"), ""); } #[test] From 51f8e2bbeb0d51f4bea12b46265fb4724d5ded37 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:39:07 +0100 Subject: [PATCH 69/95] Vault: a library damaged in its first page can be set aside (#1805) Co-authored-by: Claude Opus 5.5 --- crates/engine/src/db.rs | 46 ++++++++++++++++++++++++++++++++++------- 1 file changed, 38 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/db.rs b/crates/engine/src/db.rs index 3c8d95e64..d9a57fc0f 100644 --- a/crates/engine/src/db.rs +++ b/crates/engine/src/db.rs @@ -189,6 +189,15 @@ pub(crate) fn quick_check(connection: &mut SqliteConnection) -> Result<(), Stora )) } +/// A file whose first page SQLite cannot read: the check that names a damage never runs, and +/// diesel hands SQLite's words without their code. +fn is_unreadable(error: &StorageError) -> bool { + let said = error.to_string(); + ["file is not a database", "database disk image is malformed"] + .iter() + .any(|words| said.contains(words)) +} + /// Every failure names the file: this is the error a user meets before any window has /// anything in it, and the database sits in a directory they have never opened. pub fn open(path: &Path, vault: Vault) -> Result { @@ -198,16 +207,19 @@ pub fn open(path: &Path, vault: Vault) -> Result { let mut connection = SqliteConnection::establish(&path.to_string_lossy()).map_err(|error| named(&error))?; - configure(&mut connection).map_err(|error| named(&error))?; + let damaged = + |error: &StorageError| StorageError::Damaged(format!("{}: {error}", path.display())); + configure(&mut connection).map_err(|error| { + if is_unreadable(&error) { + damaged(&error) + } else { + named(&error) + } + })?; // ⚠️ Before the migrations, which write: running them over a damaged file is how a // salvageable database becomes an unsalvageable one. - if let Err(error) = quick_check(&mut connection) { - return Err(StorageError::Damaged(format!( - "{}: {error}", - path.display() - ))); - } + quick_check(&mut connection).map_err(|error| damaged(&error))?; migration::run(&mut connection).map_err(|error| named(&error))?; @@ -450,7 +462,6 @@ mod tests { crate::spaces::store::create(&mut library, &format!("Space {at}")).unwrap(); } } - // Garbage past the header: a broken header fails to open rather than to check. let mut bytes = std::fs::read(&path).unwrap(); assert!(bytes.len() > 4096, "the corpus did not reach a second page"); bytes[4096..4096 + 512].fill(0x42); @@ -463,6 +474,25 @@ mod tests { assert!(error.to_string().contains(&named), "{error}"); } + /// The check never runs on a first page nothing reads: the first statement fails. + #[test] + fn a_file_whose_first_page_is_damaged_is_named_as_such_too() { + for from in [0, 100] { + let scratch = tempfile::tempdir().unwrap(); + let path = scratch.path().join(crate::layout::DATABASE); + drop(opened(&scratch)); + let mut bytes = std::fs::read(&path).unwrap(); + bytes[from..].fill(0x42); + std::fs::write(&path, &bytes).unwrap(); + + let error = refusal(&path); + + assert!(matches!(error, StorageError::Damaged(_)), "{from}: {error}"); + let named = path.display().to_string(); + assert!(error.to_string().contains(&named), "{error}"); + } + } + /// A directory fails to open the way a permission would. #[test] fn a_database_that_will_not_open_says_which_file() { From 9666e0a77d4d0e04900ac0206655790e17590e07 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:39:35 +0100 Subject: [PATCH 70/95] Interface: unit tests rewritten for the state and the services (#1802) * Interface: unit tests rewritten for the state and the services Co-Authored-By: Claude Opus 5.5 * Interface: no duration in the backend's tests Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/ui/src/backend.rs | 78 +++ crates/ui/src/keys.rs | 184 ++++- crates/ui/src/services/autostart.rs | 31 + crates/ui/src/services/errors.rs | 92 +++ crates/ui/src/services/global_keys.rs | 61 ++ crates/ui/src/services/highlight.rs | 68 ++ crates/ui/src/services/notices.rs | 20 +- crates/ui/src/services/preferences.rs | 47 ++ crates/ui/src/services/settings.rs | 170 +++++ crates/ui/src/services/shortcuts.rs | 98 +++ crates/ui/src/services/status.rs | 13 + crates/ui/src/services/time.rs | 25 + crates/ui/src/services/updates.rs | 97 +++ crates/ui/src/state/held.rs | 94 +++ crates/ui/src/state/http/area_tests.rs | 892 +++++++++++++++++++++++++ crates/ui/src/state/http/mod.rs | 2 + crates/ui/src/state/mod.rs | 8 + crates/ui/src/state/notes_tests.rs | 592 ++++++++++++++++ crates/ui/src/state/refused_tests.rs | 418 ++++++++++++ crates/ui/src/state/transfer.rs | 153 +++++ crates/ui/src/state/window_tests.rs | 550 +++++++++++++++ 21 files changed, 3686 insertions(+), 7 deletions(-) create mode 100644 crates/ui/src/state/held.rs create mode 100644 crates/ui/src/state/http/area_tests.rs create mode 100644 crates/ui/src/state/notes_tests.rs create mode 100644 crates/ui/src/state/refused_tests.rs create mode 100644 crates/ui/src/state/window_tests.rs diff --git a/crates/ui/src/backend.rs b/crates/ui/src/backend.rs index d3623f5da..cfdc85b79 100644 --- a/crates/ui/src/backend.rs +++ b/crates/ui/src/backend.rs @@ -338,4 +338,82 @@ mod tests { drop(pendings); assert_eq!(*order.lock().unwrap(), (0..20).collect::>()); } + + #[test] + fn a_job_that_fails_is_its_error_whatever_the_queue() { + let (backend, _profile) = testing::backend(); + let failed = || AppError::from(StorageError::WrongPassphrase); + + let mut answers = [ + backend.db(move |_| Err::<(), _>(failed())), + backend.compute(move |_| Err(failed())), + backend.spawn(move |_| async move { Err(failed()) }), + ]; + backend.settle(); + for answer in &mut answers { + assert_eq!( + answer.poll().unwrap().unwrap_err().code, + ErrorCode::WrongPassphrase + ); + } + } + + #[test] + fn work_begun_behind_an_answer_is_waited_for_until_it_ends() { + let (backend, _profile) = testing::backend(); + let launched = backend.launched(); + let background = backend.background(); + assert_eq!(backend.launched(), launched + 1); + let ended = Arc::new(Mutex::new(false)); + let flag = Arc::clone(&ended); + let _begun = backend.spawn(move |_| async move { + background.run(async move { + for _ in 0..1_000 { + tokio::task::yield_now().await; + } + *flag.lock().unwrap() = true; + }); + Ok(()) + }); + + backend.settle(); + assert!(*ended.lock().unwrap()); + } + + /// Never begun, it still lets go: nothing would be waited for for good. + #[test] + fn work_never_begun_lets_go_and_wakes_the_window() { + let (backend, _profile) = testing::backend(); + let ctx = egui::Context::default(); + backend.waker.fill(&ctx); + + drop(backend.background()); + backend.settle(); + assert!(ctx.has_requested_repaint()); + } + + #[test] + fn an_answer_not_there_yet_is_nothing() { + let (backend, _profile) = testing::backend(); + + let (mut pending, answer) = backend.pending::(); + assert!(pending.poll().is_none()); + answer.send(Ok(7)); + assert_eq!(pending.poll().unwrap().unwrap(), 7); + assert!(pending.poll().is_none()); + } + + #[test] + fn the_exit_does_not_wait_past_its_limit() { + let (backend, _profile) = testing::backend(); + let (release, held) = std::sync::mpsc::channel::<()>(); + let _busy = backend.db(move |_| { + let _ = held.recv(); + Ok(()) + }); + + assert!(!backend.drain(std::time::Duration::ZERO)); + drop(release); + backend.settle(); + } } diff --git a/crates/ui/src/keys.rs b/crates/ui/src/keys.rs index 21149a821..0a988092c 100644 --- a/crates/ui/src/keys.rs +++ b/crates/ui/src/keys.rs @@ -139,8 +139,6 @@ const fn area(key: Key, area: Area) -> Binding { } } -/// The first binding of `levels`, top level first, that a key pressed this frame and left by -/// the widgets matches. The key is consumed. /// Who reads what the widgets left of the keys, on what is on screen: the one answer the window /// and the tests' bench both ask. A modal takes the keys, and what is under it hears none; the /// palette lets the application's through. A modal the stack does not know of (one held in a @@ -170,6 +168,8 @@ pub fn read(state: &crate::state::AppState, ctx: &Context) -> Option { dispatch(ctx, levels) } +/// The first binding of `levels`, top level first, that a key pressed this frame and left by +/// the widgets matches. The key is consumed. pub fn dispatch(ctx: &Context, levels: &[&[Binding]]) -> Option { if composing(ctx) { return None; @@ -360,4 +360,184 @@ mod tests { }); output.textures_delta.clear(); } + + /// What `read` answers to a keystroke, on the state given. + fn heard(state: &crate::state::AppState, pressed: Event) -> Option { + let ctx = Context::default(); + let mut input = egui::RawInput::default(); + input.events.push(pressed); + let mut answer = None; + let mut output = ctx.run_ui(input, |ui| answer = read(state, ui.ctx())); + output.textures_delta.clear(); + answer + } + + fn unlocked() -> crate::state::held::Held { + crate::state::held::held(crate::testing::unlocked()) + } + + fn ctrl(letter: Key) -> Event { + key(letter, letter, Modifiers::COMMAND) + } + + fn bare(letter: Key) -> Event { + key(letter, letter, Modifiers::NONE) + } + + const ELSEWHERE: Action = Action::App(AppAction::ShowArea(Area::Tools)); + + #[test] + fn each_area_hears_its_own_keys_and_the_application_s() { + let mut held = unlocked(); + for (area, pressed, answer) in [ + (Area::Notes, ctrl(Key::K), Some(NOTES[0].action.clone())), + (Area::Tools, ctrl(Key::K), Some(TOOLS[0].action.clone())), + (Area::Http, ctrl(Key::K), None), + (Area::Http, ctrl(Key::S), Some(HTTP[0].action.clone())), + (Area::Http, ctrl(Key::Enter), Some(HTTP[1].action.clone())), + (Area::Notes, ctrl(Key::S), None), + (Area::Tools, ctrl(Key::Enter), None), + ] { + held.state.settings.area = area; + assert_eq!(heard(&held.state, pressed), answer, "{area:?}"); + assert_eq!( + heard(&held.state, ctrl(Key::Num2)), + Some(ELSEWHERE), + "{area:?}" + ); + assert_eq!( + heard(&held.state, ctrl(Key::B)), + Some(Action::App(AppAction::ToggleRail)), + "{area:?}" + ); + } + } + + #[test] + fn before_the_library_is_open_only_the_application_hears() { + let state = + crate::state::AppState::new(crate::services::preferences::Preferences::default(), true); + + assert_eq!(heard(&state, ctrl(Key::K)), None); + assert_eq!(heard(&state, ctrl(Key::B)), None); + assert_eq!(heard(&state, ctrl(Key::Num2)), Some(ELSEWHERE)); + } + + #[test] + fn a_modal_keeps_the_keys_from_all_that_is_under_it() { + let mut held = unlocked(); + held.state.dialogs.open( + crate::widgets::Layer::App, + egui::Id::unique("a-modal"), + None, + ); + + for pressed in [ctrl(Key::K), ctrl(Key::Num2), bare(Key::J)] { + assert_eq!(heard(&held.state, pressed), None); + } + } + + /// A modal held in a view: the stack does not know of it, egui does. + #[test] + fn a_modal_only_egui_knows_of_keeps_the_keys_too() { + let held = unlocked(); + let ctx = Context::default(); + let mut answers = Vec::new(); + for pass in 0..2 { + let mut input = egui::RawInput::default(); + input.events.push(ctrl(Key::Num2)); + let mut output = ctx.run_ui(input, |ui| { + if pass == 1 { + answers.push(read(&held.state, ui.ctx())); + } + egui::Modal::new(egui::Id::unique("in-a-view")) + .show(ui.ctx(), |ui| ui.label("kept")); + }); + output.textures_delta.clear(); + } + assert_eq!(answers, [None]); + } + + #[test] + fn the_palette_lets_the_application_s_keys_through() { + let mut held = unlocked(); + held.state.palette.open(&held.backend, false); + held.settle(); + + assert_eq!(heard(&held.state, ctrl(Key::Num2)), Some(ELSEWHERE)); + assert_eq!(heard(&held.state, ctrl(Key::K)), None); + } + + /// The canvas's keys are the cards'; with a note open, J and K are the note's. + #[test] + fn the_canvas_hears_its_keys_until_a_note_is_open() { + let (backend, profile) = crate::testing::unlocked(); + let id = crate::testing::note(&backend, "psql").id.clone(); + let mut held = crate::state::held::held((backend, profile)); + let pin = Action::Notes(crate::notes::Action::Canvas( + crate::notes::canvas::shortcuts::CanvasKey::Pin, + )); + assert_eq!(heard(&held.state, bare(Key::P)), Some(pin)); + assert_eq!(heard(&held.state, bare(Key::J)), None); + + held.notes(crate::notes::Action::OpenNote(id)); + assert!(held.state.editor.is_open()); + assert_eq!(heard(&held.state, bare(Key::P)), None); + assert_eq!( + heard(&held.state, bare(Key::J)), + Some(EDITOR[0].action.clone()) + ); + + held.notes(crate::notes::Action::Trash(crate::notes::Trash::Open)); + assert_eq!( + heard(&held.state, bare(Key::J)), + None, + "the trash is over the note" + ); + assert_eq!(heard(&held.state, ctrl(Key::K)), None); + } + + #[test] + fn the_rail_answers_on_the_key_it_was_moved_to() { + let mut held = unlocked(); + held.state + .settings + .bindings + .set(crate::services::shortcuts::RAIL_ACTION, "Ctrl+L".to_owned()); + + assert_eq!( + heard(&held.state, ctrl(Key::L)), + Some(Action::App(AppAction::ToggleRail)) + ); + assert_eq!(heard(&held.state, ctrl(Key::B)), None); + } + + #[test] + fn a_composition_ended_gives_the_keys_back() { + let ime = |text: &str| { + Event::Ime(ImeEvent::Preedit { + text: text.to_owned(), + active_range_chars: None, + }) + }; + let area = [escape(GlobalAction::NewNote)]; + let ctx = Context::default(); + let mut answers = Vec::new(); + for events in [ + vec![ime("か")], + vec![bare(Key::Escape)], + vec![ime("")], + vec![bare(Key::Escape)], + ] { + let input = egui::RawInput { + events, + ..Default::default() + }; + let mut output = ctx.run_ui(input, |ui| { + answers.push(dispatch(ui.ctx(), &[&area]).is_some()); + }); + output.textures_delta.clear(); + } + assert_eq!(answers, [false, false, false, true]); + } } diff --git a/crates/ui/src/services/autostart.rs b/crates/ui/src/services/autostart.rs index 34027eecf..53df28e7e 100644 --- a/crates/ui/src/services/autostart.rs +++ b/crates/ui/src/services/autostart.rs @@ -177,4 +177,35 @@ mod tests { assert!(!followed); assert!(settings.start_with_system); } + + #[test] + fn a_system_that_could_not_be_read_is_told_nothing_until_the_switch_moves() { + let fake = Arc::new(Fake::default()); + *fake.unreadable.lock().unwrap() = true; + let mut settings = Settings::default(); + let (mut state, backend, _) = launched(&fake, &mut settings); + + state.update(&backend, &mut settings); + backend.settle(); + assert!(fake.writes.lock().unwrap().is_empty()); + + settings.start_with_system = true; + state.update(&backend, &mut settings); + backend.settle(); + assert_eq!(*fake.writes.lock().unwrap(), [true]); + } + + /// Turned off from the system meanwhile, writing the same again would bring the entry back. + #[test] + fn a_system_that_already_agrees_is_not_written_to() { + let fake = Arc::new(Fake::default()); + let mut settings = Settings::default(); + let (mut state, backend, _) = launched(&fake, &mut settings); + *fake.enabled.lock().unwrap() = true; + + settings.start_with_system = true; + state.update(&backend, &mut settings); + backend.settle(); + assert!(fake.writes.lock().unwrap().is_empty()); + } } diff --git a/crates/ui/src/services/errors.rs b/crates/ui/src/services/errors.rs index 755354907..74f08579b 100644 --- a/crates/ui/src/services/errors.rs +++ b/crates/ui/src/services/errors.rs @@ -170,4 +170,96 @@ mod tests { "errors.httpTimeout.request" ); } + + /// Every sub-key of a group is chosen by its value; a value the interface does not know leaves + /// the action's own message. + #[test] + fn each_sentence_of_a_group_is_chosen_by_its_value() { + let translations: serde_json::Value = + serde_json::from_str(include_str!("../../../i18n/translations/en.json")).unwrap(); + for (code, group, parameter) in [ + (ErrorCode::HttpTimeout, "httpTimeout", "source"), + ( + ErrorCode::HttpTooManyRedirects, + "httpTooManyRedirects", + "source", + ), + (ErrorCode::HttpHeaderName, "httpHeaderName", "source"), + (ErrorCode::HttpHeaderValue, "httpHeaderValue", "source"), + (ErrorCode::HttpScript, "httpScript", "failure"), + (ErrorCode::HttpRunData, "httpRunData", "fault"), + ] { + let values = translations["errors"][group].as_object().unwrap(); + assert!(!values.is_empty(), "{group}"); + for value in values.keys() { + let error = of(code, &[(parameter, value)]); + let key = message_of(&error).unwrap().key; + assert_eq!(key.path(), format!("errors.{group}.{value}")); + } + assert_eq!( + message_of(&of(code, &[(parameter, "unknown")])), + None, + "{group}" + ); + } + } + + fn of(code: ErrorCode, params: &[(&str, &str)]) -> AppError { + let mut error = AppError::from(engine::error::StorageError::WrongPassphrase); + error.code = code; + error.params = params + .iter() + .map(|(name, value)| ((*name).to_owned(), (*value).to_owned())) + .collect(); + error + } + + #[test] + fn a_sentence_carries_the_values_of_its_error() { + let error = of( + ErrorCode::FileTooLarge, + &[("name", "plan.pdf"), ("limitMb", "10")], + ); + let message = message_of(&error).unwrap(); + + assert_eq!(message.key, keys::errors::FILE_TOO_LARGE); + assert_eq!(message.params.len(), 2); + assert!(message.text(i18n::Language::En).contains("plan.pdf")); + } + + #[test] + fn a_fallback_that_carries_what_was_typed_gives_way_to_a_sentence_of_the_core() { + let mut errors = ErrorNotifier::default(); + let typed = || Message::new(keys::errors::FOLDER_CREATE_FAILED).with("name", "Runbooks"); + + errors.report_message( + typed(), + &AppError::from(engine::error::ValidationError::new("name", "too long")), + ); + assert!( + errors + .notice() + .unwrap() + .text(i18n::Language::En) + .contains("Runbooks") + ); + errors.report_message(typed(), &of(ErrorCode::DuplicateFolderName, &[])); + assert_eq!( + errors.notice().unwrap().key, + keys::errors::FOLDER_NAME_TAKEN + ); + } + + #[test] + fn the_same_failure_stands_once() { + let mut errors = ErrorNotifier::default(); + for _ in 0..3 { + errors.report( + keys::errors::UNLOCK_FAILED, + &of(ErrorCode::WrongPassphrase, &[]), + ); + } + + assert_eq!(errors.shown().count(), 1); + } } diff --git a/crates/ui/src/services/global_keys.rs b/crates/ui/src/services/global_keys.rs index bdd41665b..e49da1594 100644 --- a/crates/ui/src/services/global_keys.rs +++ b/crates/ui/src/services/global_keys.rs @@ -196,4 +196,65 @@ mod tests { assert_eq!(fake.sets.lock().unwrap().len(), 2); assert!(errors.notice().is_none(), "it was said when they were set"); } + + #[test] + fn a_key_that_is_free_again_is_held_no_more() { + let fake = Fake::default(); + *fake.held_elsewhere.lock().unwrap() = vec!["Ctrl+Alt+P".to_owned()]; + let mut keys = keys_on(&fake); + let mut errors = ErrorNotifier::default(); + let mut bindings = Bindings::default(); + keys.update(&bindings, false, &mut errors); + + fake.held_elsewhere.lock().unwrap().clear(); + bindings.set(shortcuts::ACTIONS[0], "Ctrl+Alt+K".to_owned()); + keys.update(&bindings, false, &mut errors); + + assert!(keys.held().is_empty()); + assert_eq!(errors.shown().count(), 1, "nothing more to say"); + } + + #[test] + fn a_key_moved_while_a_field_listened_is_taken_when_it_is_done() { + let fake = Fake::default(); + let mut keys = keys_on(&fake); + let mut errors = ErrorNotifier::default(); + let mut bindings = Bindings::default(); + keys.update(&bindings, false, &mut errors); + keys.update(&bindings, true, &mut errors); + + bindings.set(shortcuts::ACTIONS[0], "Ctrl+Alt+K".to_owned()); + keys.update(&bindings, true, &mut errors); + assert_eq!(fake.sets.lock().unwrap().len(), 1); + keys.update(&bindings, false, &mut errors); + assert_eq!(fake.sets.lock().unwrap()[1][0].1, "Ctrl+Alt+K"); + } + + #[test] + fn only_the_keys_of_the_whole_machine_are_taken_and_each_is_described() { + let each: Vec = wanted(&Bindings::default()) + .into_iter() + .map(|(key, _)| key) + .collect(); + + assert_eq!(each, [Global::Palette, Global::Capture, Global::NewNote]); + for language in Language::ALL { + let described = described(language); + assert!( + described + .iter() + .map(|(key, _)| *key) + .eq(each.iter().copied()) + ); + assert!(described.iter().all(|(_, words)| !words.is_empty())); + } + } + + #[test] + fn the_exit_lets_go_of_the_keys() { + let fake = Fake::default(); + keys_on(&fake).release(); + + assert_eq!(*fake.releases.lock().unwrap(), 1); + } } diff --git a/crates/ui/src/services/highlight.rs b/crates/ui/src/services/highlight.rs index 0ac41dc8a..9be843ca8 100644 --- a/crates/ui/src/services/highlight.rs +++ b/crates/ui/src/services/highlight.rs @@ -260,4 +260,72 @@ mod tests { assert!(lines[0].iter().any(|(_, token)| *token == Token::Keyword)); assert!(Colouring::new(&ctx, "Not a language").is_none()); } + + /// Comments and emphasis lean; nothing else does. + #[test] + fn each_class_has_its_colour_and_two_lean() { + let p = &crate::theme::tokens::DARK; + for (token, expected, leans) in [ + (Token::Keyword, p.blue, false), + (Token::String, p.green, false), + (Token::Literal, p.amber_text, false), + (Token::Name, p.purple, false), + (Token::Property, p.text_0, false), + (Token::Strong, p.text_0, false), + (Token::Meta, p.text_1, false), + (Token::Comment, p.text_2, true), + (Token::Deleted, p.red, false), + (Token::Emphasis, p.text_1, true), + ] { + assert_eq!(colour(p, token), (expected, leans), "{token:?}"); + } + } + + #[test] + fn a_newer_window_keeps_the_earliest_edit_it_has_not_seen() { + let request = |generation, invalid_from| Request { + generation, + invalid_from, + rope: text::Rope::new(), + visible: 0..10, + }; + for (older, newer, from) in [ + (Some(3), Some(9), Some(3)), + (Some(9), Some(3), Some(3)), + (Some(3), None, Some(3)), + (None, Some(9), Some(9)), + (None, None, None), + ] { + let merged = merged(&request(1, older), request(2, newer)); + assert_eq!((merged.generation, merged.invalid_from), (2, from)); + } + } + + #[test] + fn an_edit_leaves_the_lines_above_it_as_they_are() { + text::highlight::warm(); + let rope = rope(100); + let mut colouring = Colouring::new(&egui::Context::default(), "JavaScript").unwrap(); + assert!(coloured(&mut colouring, &rope, 0..50)); + + colouring.edited(30); + colouring.edited(40); + let fresh = |line: usize| colouring.fresh.contains(&line); + assert!((0..30).all(fresh) && !(30..50).any(fresh)); + assert_eq!(colouring.invalid_from, Some(30), "from the first one"); + } + + #[test] + fn a_window_known_is_not_asked_again() { + text::highlight::warm(); + let rope = rope(100); + let mut colouring = Colouring::new(&egui::Context::default(), "JavaScript").unwrap(); + assert!(coloured(&mut colouring, &rope, 0..50)); + colouring.asked = None; + + colouring.window(&rope, 10..20); + assert!(colouring.asked.is_none()); + colouring.window(&rope, 60..70); + assert_eq!(colouring.asked, Some((0, 60..70))); + } } diff --git a/crates/ui/src/services/notices.rs b/crates/ui/src/services/notices.rs index af5c86c26..83cd4894c 100644 --- a/crates/ui/src/services/notices.rs +++ b/crates/ui/src/services/notices.rs @@ -48,16 +48,26 @@ mod tests { } #[test] - fn the_latest_is_first_the_oldest_makes_room_and_one_is_dismissed_alone() { + fn the_latest_is_first_and_the_oldest_makes_room() { let mut notices = Notices::default(); for _ in 0..KEPT + 2 { notices.push(Message::new(keys::errors::RETRY)); } + assert_eq!(numbers(¬ices), [6, 5, 4, 3]); - notices.dismiss(5); - assert_eq!(numbers(¬ices), [6, 4, 3]); - notices.dismiss(5); - assert_eq!(numbers(¬ices), [6, 4, 3]); + } + + #[test] + fn one_is_dismissed_by_its_number_alone() { + let mut notices = Notices::default(); + for _ in 0..3 { + notices.push(Message::new(keys::errors::RETRY)); + } + notices.dismiss(2); + assert_eq!(numbers(¬ices), [3, 1]); + + notices.dismiss(2); + assert_eq!(numbers(¬ices), [3, 1]); } #[test] diff --git a/crates/ui/src/services/preferences.rs b/crates/ui/src/services/preferences.rs index cab223d29..96ab47e42 100644 --- a/crates/ui/src/services/preferences.rs +++ b/crates/ui/src/services/preferences.rs @@ -93,4 +93,51 @@ mod tests { std::fs::write(&file, "{ half").unwrap(); assert_eq!(Preferences::read(&file), Preferences::default()); } + + #[test] + fn only_a_text_is_the_value_of_a_key() { + let directory = tempfile::tempdir().unwrap(); + let file = directory.path().join("preferences.json"); + std::fs::write(&file, r#"{ "a": "x", "b": 3, "c": null, "d": true }"#).unwrap(); + let preferences = Preferences::read(&file); + + assert_eq!( + ["a", "b", "c", "d", "e"].map(|key| preferences.get(key)), + [Some("x"), None, None, None, None] + ); + } + + #[test] + fn what_two_files_say_otherwise_is_counted() { + let of = |pairs: &[(&str, &str)]| { + let mut preferences = Preferences::default(); + for (key, value) in pairs { + preferences.set(key, value); + } + preferences + }; + let here = of(&[("a", "1"), ("b", "2")]); + + assert_eq!(here.differences(&here), 0); + assert_eq!(here.differences(&of(&[("a", "1"), ("b", "x")])), 1); + assert_eq!( + here.differences(&of(&[("a", "1"), ("b", "2"), ("c", "3")])), + 1 + ); + } + + #[test] + fn a_key_removed_is_written_no_more() { + let directory = tempfile::tempdir().unwrap(); + let file = directory.path().join("nested").join("preferences.json"); + let mut preferences = Preferences::default(); + preferences.set("a", "1"); + preferences.set("b", "2"); + preferences.remove("a"); + preferences.write(&file).unwrap(); + + let mut expected = Preferences::default(); + expected.set("b", "2"); + assert_eq!(Preferences::read(&file), expected); + } } diff --git a/crates/ui/src/services/settings.rs b/crates/ui/src/services/settings.rs index f8095c754..426c48613 100644 --- a/crates/ui/src/services/settings.rs +++ b/crates/ui/src/services/settings.rs @@ -549,4 +549,174 @@ mod tests { assert_eq!(read, Settings::default()); assert!(read.close_to_tray && read.automatic_backups && read.copy_confirmation); } + + fn stored(key: &str, value: &str) -> Settings { + let mut preferences = Preferences::default(); + preferences.set(key, value); + Settings::read(&preferences) + } + + #[test] + fn a_rail_is_brought_back_within_its_bounds() { + for (written, width) in [ + ("159", 160), + ("160", 160), + ("520", 520), + ("521", 520), + ("wide", RAIL_DEFAULT), + ("-3", RAIL_DEFAULT), + ("", RAIL_DEFAULT), + ] { + assert_eq!( + stored("devnotes.libraryRailWidth", written).rail_width, + width, + "{written}" + ); + } + } + + /// Out of bounds, the request takes the height its content asks. + #[test] + fn a_share_is_read_in_tenths_of_a_percent_within_its_bounds() { + for (written, share) in [ + ("42.3", 423), + ("42.36", 424), + ("5", 50), + ("4.9", 0), + ("95", 950), + ("95.1", 0), + ("0", 0), + ("-10", 0), + ("NaN", 0), + ("half", 0), + ] { + assert_eq!( + stored("devnotes.httpRequestShare", written).http_request_share, + share, + "{written}" + ); + } + } + + #[test] + fn a_number_that_does_not_read_is_the_default() { + assert_eq!( + stored("devnotes.editorPanelWidth", "wide").editor_panel_width, + 0 + ); + assert_eq!( + stored("devnotes.httpHistoryListWidth", "wide").history_list_width, + 380 + ); + for (written, places) in [("auto", None), ("", None), ("2", Some(2)), ("-1", None)] { + assert_eq!( + stored("devnotes.calcDecimals", written).calc_decimals, + places, + "{written}" + ); + } + } + + /// Every switch, by what turns it: those that are on need a plain `false`, the others a plain + /// `true`. + #[test] + fn a_switch_moves_on_its_plain_word_alone() { + type Read = fn(&Settings) -> bool; + let switches: [(&str, bool, Read); 13] = [ + ("showLibraryRail", true, |s| s.rail_shown), + ("editorFullscreen", false, |s| s.editor_fullscreen), + ("editorHeaderFolded", false, |s| s.editor_header_folded), + ("editorFieldsPanel", true, |s| s.editor_fields_open), + ("editorDetails", true, |s| s.editor_details_open), + ("codeWrap", false, |s| s.code_wrap), + ("startWithSystem", false, |s| s.start_with_system), + ("minimizeToTray", false, |s| s.minimize_to_tray), + ("closeToTray", true, |s| s.close_to_tray), + ("showPinnedFirst", true, |s| s.show_pinned_first), + ("automaticBackups", true, |s| s.automatic_backups), + ("copyConfirmation", true, |s| s.copy_confirmation), + ("updateNotifications", true, |s| s.update_notifications), + ]; + for (name, shipped, read) in switches { + let key = format!("devnotes.{name}"); + let moves = if shipped { "false" } else { "true" }; + assert_eq!(read(&stored(&key, moves)), !shipped, "{name}"); + for other in [ + "", + "1", + "0", + "TRUE", + "False", + if shipped { "true" } else { "false" }, + ] { + assert_eq!(read(&stored(&key, other)), shipped, "{name} {other}"); + } + } + } + + #[test] + fn every_choice_reads_back_from_its_word() { + fn round(choices: &[(&'static str, T)]) { + for (word, value) in choices { + let mut preferences = Preferences::default(); + preferences.set("k", name_of(choices, *value)); + assert_eq!(chosen(&preferences, "k", choices), Some(*value)); + assert_eq!(name_of(choices, *value), *word); + } + } + round(&LOCALES); + round(&THEMES); + round(&DENSITIES); + round(&AREAS); + round(&INDENTS); + round(&NOTE_KINDS); + round(&CALC_DATES); + } + + #[test] + fn a_key_put_back_leaves_the_file() { + let mut preferences = Preferences::default(); + Settings { + bindings: moved_key(), + ..Settings::default() + } + .write(&mut preferences); + assert!(preferences.get("devnotes.shortcut.canvas.pin").is_some()); + + Settings::default().write(&mut preferences); + assert_eq!(preferences.get("devnotes.shortcut.canvas.pin"), None); + } + + #[test] + fn tab_inserts_the_unit_chosen_or_the_language_s_own() { + use IndentChoice::{FourSpaces, Language, Tab, TwoSpaces}; + + let rust = engine::notes::language::Language::Rs; + assert_eq!( + [TwoSpaces, FourSpaces, Tab].map(|choice| choice.unit(rust)), + [" ", " ", "\t"] + ); + assert_eq!( + Language.unit(rust), + crate::notes::language::indent_unit(rust) + ); + } + + #[test] + fn a_language_chosen_is_that_one() { + assert_eq!(LocaleChoice::Fr.language(), i18n::Language::Fr); + assert_eq!(LocaleChoice::En.language(), i18n::Language::En); + assert_eq!(LocaleChoice::System.language(), i18n::Language::of_system()); + } + + #[test] + fn a_draft_put_back_has_nothing_to_apply() { + let mut draft = SettingsDraft::open(Settings::default()); + draft.edit(|settings| settings.code_wrap = true); + assert_eq!((draft.pending(), draft.is_changed()), (1, true)); + + draft.edit(|settings| settings.code_wrap = false); + assert_eq!((draft.pending(), draft.is_changed()), (0, false)); + assert_eq!(draft.apply(), Settings::default()); + } } diff --git a/crates/ui/src/services/shortcuts.rs b/crates/ui/src/services/shortcuts.rs index 791aa43ca..ab8bd74e6 100644 --- a/crates/ui/src/services/shortcuts.rs +++ b/crates/ui/src/services/shortcuts.rs @@ -515,4 +515,102 @@ mod tests { assert_eq!(preference_key(GLOBAL), "devnotes.paletteShortcut"); assert_eq!(preference_key(PIN), "devnotes.shortcut.canvas.pin"); } + + #[test] + fn a_keystroke_reads_back_as_it_was_written() { + for (written_key, key, modifiers) in [ + ("P", Key::P, Modifiers::NONE), + ("Ctrl+Alt+P", Key::P, modified()), + ("Ctrl+Alt+Shift+F5", Key::F5, modified() | Modifiers::SHIFT), + (" Ctrl + K ", Key::K, Modifiers::COMMAND), + ("Super+Space", Key::Space, Modifiers::MAC_CMD), + ] { + assert_eq!(parse(written_key), Some((key, modifiers)), "{written_key}"); + } + for unreadable in [ + "", + "Ctrl", + "Ctrl+", + "Hyper+P", + "Ctrl+Nothing", + "P+Ctrl", + "Ctrl++", + ] { + assert_eq!(parse(unreadable), None, "{unreadable}"); + } + } + + #[test] + fn modifiers_are_written_in_one_order_and_super_on_a_global_key_alone() { + let all = Modifiers::ALT | Modifiers::SHIFT | Modifiers::CTRL | Modifiers::MAC_CMD; + + assert_eq!(written(all, "P", Scope::Global), "Ctrl+Alt+Shift+Super+P"); + assert_eq!(written(all, "P", Scope::Canvas), "Ctrl+Alt+Shift+P"); + assert_eq!(written(Modifiers::COMMAND, "P", Scope::Areas), "Ctrl+P"); + assert_eq!(written(Modifiers::NONE, "P", Scope::Canvas), "P"); + } + + /// Its own key pressed again is not taken by another. + #[test] + fn an_action_keeps_the_key_it_has() { + let bindings = Bindings::default(); + + assert_eq!( + capture(PIN, (Key::P, None), Modifiers::NONE, &bindings).as_deref(), + Ok("P") + ); + } + + #[test] + fn a_key_moved_away_is_free_for_another() { + let mut bindings = Bindings::default(); + bindings.set(PIN, "J".to_owned()); + + assert_eq!( + capture(CHECK, (Key::P, None), Modifiers::NONE, &bindings).as_deref(), + Ok("P") + ); + assert!(matches!( + capture(CHECK, (Key::J, None), Modifiers::NONE, &bindings), + Err(Refused::Taken { by, .. }) if by == PIN + )); + } + + /// The navigation's keys are a global key's like any other. + #[test] + fn a_global_key_may_be_one_the_navigation_keeps() { + let bindings = Bindings::default(); + + assert_eq!( + capture( + GLOBAL, + (Key::ArrowUp, Some(Key::ArrowUp)), + modified(), + &bindings + ) + .as_deref(), + Ok("Ctrl+Alt+ArrowUp") + ); + } + + #[test] + fn a_stored_key_that_does_not_read_answers_on_its_default() { + let mut bindings = Bindings::default(); + bindings.set(PIN, "Hyper+P".to_owned()); + + assert_eq!(bindings.of(PIN), "Hyper+P"); + assert_eq!(bindings.keystroke(PIN), Some((Key::P, Modifiers::NONE))); + bindings.reset(PIN); + assert!(bindings.is_default(PIN)); + } + + #[test] + fn a_key_with_no_name_is_told_from_one_that_starts_like_a_function_key() { + assert_eq!(name_of(Key::F), Some("F".to_owned())); + assert_eq!(name_of(Key::F12), Some("F12".to_owned())); + for key in [Key::Escape, Key::Plus, Key::Colon] { + assert_eq!(name_of(key), None, "{key:?}"); + } + assert_eq!(key_named("Escape"), None, "it could not be written back"); + } } diff --git a/crates/ui/src/services/status.rs b/crates/ui/src/services/status.rs index a8fe8ee5a..195150672 100644 --- a/crates/ui/src/services/status.rs +++ b/crates/ui/src/services/status.rs @@ -47,4 +47,17 @@ mod tests { assert_ne!(status.latest().unwrap().0, first); assert_eq!(status.shown().count(), 2); } + + #[test] + fn the_last_report_is_the_one_not_dismissed() { + let mut status = StatusNotifier::default(); + status.report(Message::new(keys::errors::RETRY)); + status.report(Message::new(keys::errors::DISMISS)); + let (last, _) = status.latest().unwrap(); + + status.dismiss(last); + assert_eq!(status.latest().unwrap().1.key, keys::errors::RETRY); + status.dismiss(status.latest().unwrap().0); + assert!(status.latest().is_none()); + } } diff --git a/crates/ui/src/services/time.rs b/crates/ui/src/services/time.rs index e2eafcad6..182f5a092 100644 --- a/crates/ui/src/services/time.rs +++ b/crates/ui/src/services/time.rs @@ -122,6 +122,31 @@ mod tests { // 3 h rounds to 4 h from 3 h 29 min 30 s on. assert_eq!(wait, Duration::from_secs(29 * 60 + 30)); } + + #[test] + fn a_label_of_days_is_drawn_again_within_a_day() { + let clock = FakeClock::at("2026-07-25T09:00:00Z"); + let at: DateTime = "2026-07-15T09:00:00Z".parse().unwrap(); + + let (label, wait) = relative(at, &clock); + assert_eq!( + label, + Message::new(i18n::keys::time::DAYS_AGO).with("count", 10.0) + ); + assert!( + wait <= Duration::from_hours(24) && wait > Duration::from_hours(11), + "{wait:?}" + ); + } + + /// The clock of another machine, a little ahead. + #[test] + fn what_is_dated_in_the_future_is_now() { + let clock = FakeClock::at(AT); + let at: DateTime = "2026-07-25T09:00:10Z".parse().unwrap(); + + assert_eq!(relative(at, &clock).0.key, i18n::keys::time::JUST_NOW); + } } #[cfg(test)] diff --git a/crates/ui/src/services/updates.rs b/crates/ui/src/services/updates.rs index 76bcaffa3..237418511 100644 --- a/crates/ui/src/services/updates.rs +++ b/crates/ui/src/services/updates.rs @@ -512,4 +512,101 @@ mod tests { assert!(bench.errors.notice().is_some()); assert!(!*fake.relaunched.lock().unwrap()); } + + /// « Later » closes the prompt; the menu shows it again without a new check. + #[test] + fn an_offer_put_off_is_shown_again_from_the_menu() { + let mut bench = bench(FakeUpdater::offering("0.26.0")); + bench.check(true); + assert!( + !bench.updates.dismiss(false, &mut bench.settings), + "nothing to save" + ); + assert_eq!(bench.settings.skipped_update, ""); + assert!(bench.updates.offered().is_none() && bench.updates.pending().is_some()); + + let asked = bench.backend.launched(); + bench.updates.reopen(); + assert!(bench.updates.offered().is_some()); + assert_eq!(bench.backend.launched(), asked); + } + + #[test] + fn with_nothing_found_there_is_nothing_to_show_again_nor_to_install() { + let mut bench = bench(Arc::new(FakeUpdater::default())); + bench.check(true); + + bench.updates.reopen(); + bench.updates.install(&bench.backend); + assert_eq!(bench.updates.status(), Status::Idle); + } + + #[test] + fn an_offer_said_on_the_unlock_card_opens_no_prompt_after_it() { + let mut bench = bench(FakeUpdater::offering("0.26.0")); + bench.check(true); + + bench.updates.put_away(); + assert_eq!(bench.updates.status(), Status::Idle); + assert!(bench.updates.has_pending()); + + bench.updates.reopen(); + bench.updates.install(&bench.backend); + bench.updates.put_away(); + assert_eq!(bench.updates.status(), Status::Installing, "too late"); + } + + #[test] + fn what_a_check_found_is_forgotten_with_the_menu_and_one_under_way_is_not() { + let mut bench = bench(Arc::new(FakeUpdater::default())); + bench.check(false); + bench.updates.forget_check(); + assert_eq!(bench.updates.check_state(), CheckState::Idle); + + bench.updates.check(&bench.backend, false); + bench.updates.forget_check(); + assert_eq!(bench.updates.check_state(), CheckState::Checking); + } + + #[test] + fn one_check_at_a_time_and_none_over_an_offer() { + let mut bench = bench(FakeUpdater::offering("0.26.0")); + let before = bench.backend.launched(); + bench.updates.check(&bench.backend, true); + bench.updates.check(&bench.backend, true); + assert_eq!(bench.backend.launched(), before + 1); + bench.settle(); + + bench.updates.check(&bench.backend, false); + assert_eq!(bench.backend.launched(), before + 1); + } + + #[test] + fn no_percent_is_known_before_the_server_says_a_size() { + let mut bench = bench(FakeUpdater::offering("0.26.0")); + bench.check(true); + assert_eq!(bench.updates.progress(), None); + + bench.updates.install(&bench.backend); + bench.settle(); + assert_eq!(bench.updates.progress(), Some(50)); + } + + #[test] + fn a_failed_install_says_what_to_do_and_can_be_tried_again() { + let fake = FakeUpdater::offering("0.26.0"); + let mut bench = bench(Arc::clone(&fake)); + bench.check(true); + *fake.fails.lock().unwrap() = true; + bench.updates.install(&bench.backend); + bench.settle(); + let said = bench.errors.notice().unwrap().text(i18n::Language::En); + assert!(said.contains(METADATA.name), "{said}"); + + *fake.fails.lock().unwrap() = false; + bench.updates.install(&bench.backend); + assert_eq!(bench.updates.progress(), None, "from the start"); + bench.settle(); + assert_eq!(bench.updates.status(), Status::Installed); + } } diff --git a/crates/ui/src/state/held.rs b/crates/ui/src/state/held.rs new file mode 100644 index 000000000..ad7677f55 --- /dev/null +++ b/crates/ui/src/state/held.rs @@ -0,0 +1,94 @@ +//! The state over a real core, without a window: an action applied, and everything it asked of +//! the core adopted. + +use crate::action::Action; +use crate::backend::Backend; +use crate::notes; +use crate::services::preferences::Preferences; +use crate::state::AppState; +use crate::testing; + +pub(crate) struct Held { + pub(crate) state: AppState, + pub(crate) backend: Backend, + pub(crate) ctx: egui::Context, + pub(crate) profile: tempfile::TempDir, +} + +/// An open library, whatever was written through `backend` before. +pub(crate) fn held((backend, profile): (Backend, tempfile::TempDir)) -> Held { + let mut state = AppState::new(Preferences::default(), true); + state.language = i18n::Language::En; + state.gate.ask(&backend); + let mut held = Held { + state, + backend, + ctx: egui::Context::default(), + profile, + }; + held.settle(); + held +} + +impl Held { + pub(crate) fn apply(&mut self, action: Action) { + self.state.apply(action, &self.ctx, &self.backend); + self.settle(); + } + + pub(crate) fn notes(&mut self, action: notes::Action) { + self.apply(Action::Notes(action)); + } + + pub(crate) fn key(&mut self, key: notes::canvas::shortcuts::CanvasKey) { + self.notes(notes::Action::Canvas(key)); + } + + /// Until nothing more is asked of the core: an answer may ask it again. + pub(crate) fn settle(&mut self) { + loop { + self.backend.settle(); + let launched = self.backend.launched(); + let state = &mut self.state; + state + .gate + .update(&self.backend, &mut state.status, &mut state.errors); + state.update_library(&self.ctx, &self.backend); + if self.backend.launched() == launched { + return; + } + } + } + + /// The last thing that failed, in words. + pub(crate) fn failed(&self) -> Option { + Some(self.state.errors.notice()?.text(i18n::Language::En)) + } + + /// The last thing that was done, in words. + pub(crate) fn done(&self) -> Option { + Some(self.state.status.latest()?.1.text(i18n::Language::En)) + } + + /// The titles of the cards shown, in their order. + pub(crate) fn shown(&self) -> Vec { + let view = self.state.notes_query.view(); + view.into_iter() + .flat_map(engine::notes::view::NotesView::cards) + .map(|card| card.title.clone()) + .collect() + } + + pub(crate) fn note(&self, id: &str) -> engine::notes::model::DisplayNote { + let id = id.to_owned(); + engine::db::run_here(self.backend.engine(), move |engine| { + engine::notes::get_note(engine, &id) + }) + .unwrap() + } + + /// The library closed under the window: whatever is asked next, the core refuses. + pub(crate) fn close_library(&self) { + testing::close_library(&self.backend); + } +} diff --git a/crates/ui/src/state/http/area_tests.rs b/crates/ui/src/state/http/area_tests.rs new file mode 100644 index 000000000..5ea39d149 --- /dev/null +++ b/crates/ui/src/state/http/area_tests.rs @@ -0,0 +1,892 @@ +//! The HTTP area's state as the actions change it, without a window. + +use std::sync::Arc; + +use engine::folders::model::FolderColour; +use engine::http::environments::Variable; +use engine::http::model::{ + HttpItem, HttpItemKind, HttpMethod, HttpRequest, RequestBody, RequestKind, +}; +use platform::dialog::{Fixed, NoDialog}; + +use super::bodies::{BodiesLeft, BodyKind, FileFor, body_of_kind, with_file}; +use super::environments::{Asked as Env, Target}; +use super::history::Asked as Hist; +use super::moves::KeyMove; +use super::runner::{Asked as Run, Phase, Target as RunTarget}; +use super::sockets::{Phase as SocketPhase, Sockets}; +use super::tabs::DraftEdit; +use super::{cookies, tree}; +use crate::action::Action; +use crate::http::Action as Http; +use crate::http::tests as http; +use crate::state::held::{Held, held}; +use crate::testing; + +const GET: (RequestKind, HttpMethod) = (RequestKind::Http, HttpMethod::Get); + +/// `API[Auth[Login] Users]`. +struct Area { + held: Held, + login: HttpRequest, + users: HttpRequest, + auth: String, + api: String, +} + +fn area() -> Area { + let (backend, profile) = testing::unlocked(); + let api = http::collection(&backend, "API"); + let auth = http::folder(&backend, &api, "Auth"); + let login = http::request(&backend, (&api, Some(&auth)), "Login", GET); + let users = http::request(&backend, (&api, None), "Users", GET); + let mut held = held((backend, profile)); + held.state.settings.area = crate::state::Area::Http; + held.settle(); + Area { + held, + login, + users, + auth: auth.id, + api: api.id, + } +} + +impl Area { + fn ask(&mut self, action: Http) { + self.held.apply(Action::Http(action)); + } + + fn env(&mut self, asked: Env) { + self.ask(Http::Environments(asked)); + } + + /// A request open in its tab: the tab's key. + fn open(&mut self, id: &str) -> String { + self.ask(Http::OpenRequest(id.to_owned())); + self.held.state.http.tabs().active_key().unwrap().to_owned() + } + + fn edit(&mut self, key: &str, edit: DraftEdit) { + self.ask(Http::Edit { + key: key.to_owned(), + edit, + }); + } + + /// The environment of that name, made. + fn environment(&mut self, name: &str) -> String { + self.env(Env::Create(name.to_owned())); + let made = self + .held + .state + .http + .environments() + .all() + .iter() + .find(|set| set.name == name); + made.unwrap().id.clone() + } + + fn sent(&mut self, path: &str) -> String { + let port = testing::serve(); + let key = self.open(&self.users.id.clone()); + self.edit( + &key, + DraftEdit::Url(format!("http://127.0.0.1:{port}{path}")), + ); + self.ask(Http::Send(Some(key.clone()))); + key + } +} + +fn item(kind: HttpItemKind, id: &str) -> HttpItem { + HttpItem { + kind, + id: id.to_owned(), + } +} + +fn row(name: &str, value: &str) -> Variable { + Variable { + name: name.to_owned(), + value: value.to_owned(), + ..Variable::default() + } +} + +// Environments + +#[test] +fn an_environment_is_made_shown_renamed_recoloured_and_protected() { + let mut area = area(); + let id = area.environment("Prod"); + assert_eq!( + area.held.state.http.environments().target(), + &Target::Environment(id.clone()) + ); + + area.env(Env::Rename { + id: id.clone(), + name: "Production".to_owned(), + }); + area.env(Env::Recolour { + id: id.clone(), + colour: FolderColour::Purple, + }); + area.env(Env::Protect { + id: id.clone(), + protect: true, + }); + let set = area.held.state.http.environments().shown().unwrap(); + assert_eq!( + (set.name.as_str(), set.colour, set.protected), + ("Production", FolderColour::Purple, true) + ); +} + +#[test] +fn the_rows_typed_are_written_in_the_set_they_were_typed_in() { + let mut area = area(); + let id = area.environment("Prod"); + area.env(Env::Rows(vec![row("host", "prod.example.com")])); + area.env(Env::Select(Target::Globals)); + area.env(Env::Rows(vec![row("token", "abc")])); + area.env(Env::Select(Target::Environment(id))); + + let environments = area.held.state.http.environments(); + assert_eq!( + environments.shown().unwrap().variables[0].value, + "prod.example.com" + ); + assert_eq!(environments.globals()[0].value, "abc"); +} + +#[test] +fn an_environment_deleted_is_shown_and_used_no_more() { + let mut area = area(); + let id = area.environment("Prod"); + area.ask(Http::ChooseEnvironment(Some(id.clone()))); + area.env(Env::Rows(vec![row("host", "typed")])); + area.env(Env::Delete(id)); + + let environments = area.held.state.http.environments(); + assert!(environments.all().is_empty()); + assert_eq!( + (environments.active_id(), environments.target()), + (None, &Target::Globals) + ); + assert_eq!( + area.held.failed(), + None, + "what was typed in it is written nowhere" + ); +} + +#[test] +fn a_copy_of_an_environment_keeps_its_rows() { + let mut area = area(); + let id = area.environment("Prod"); + area.env(Env::Rows(vec![row("host", "prod")])); + area.env(Env::Select(Target::Globals)); + area.env(Env::Duplicate { + id, + name: "Staging".to_owned(), + }); + + let copy = area.held.state.http.environments().shown().unwrap(); + assert_eq!( + (copy.name.as_str(), copy.variables[0].value.as_str()), + ("Staging", "prod") + ); +} + +/// Where the send would look first: the environment chosen, or the globals without one. +#[test] +fn a_name_nothing_sets_gets_a_row_where_the_send_looks() { + let mut area = area(); + area.ask(Http::Define("host".to_owned())); + assert_eq!( + area.held.state.http.environments().target(), + &Target::Globals + ); + let names = |area: &Area| -> Vec { + area.held + .state + .http + .environments() + .rows() + .iter() + .map(|row| row.name.clone()) + .collect() + }; + assert_eq!(names(&area), ["host"]); + area.ask(Http::Define("host".to_owned())); + assert_eq!(names(&area), ["host"], "already there"); + + let id = area.environment("Prod"); + area.ask(Http::ChooseEnvironment(Some(id.clone()))); + area.ask(Http::Define("token".to_owned())); + assert_eq!( + area.held.state.http.environments().target(), + &Target::Environment(id) + ); + assert_eq!(names(&area), ["token"]); +} + +// Tabs + +#[test] +fn what_is_typed_in_a_request_is_written_once_saved() { + let mut area = area(); + let key = area.open(&area.users.id.clone()); + area.edit(&key, DraftEdit::Name("People".to_owned())); + area.edit(&key, DraftEdit::Method(HttpMethod::Post)); + assert!(area.held.state.http.tabs().active().unwrap().is_dirty()); + + area.ask(Http::SaveActive); + assert!(!area.held.state.http.tabs().active().unwrap().is_dirty()); + let found = tree::find_request(area.held.state.http.tree(), &area.users.id).unwrap(); + assert_eq!( + (found.name.as_str(), found.method), + ("People", HttpMethod::Post) + ); +} + +#[test] +fn a_modified_tab_asks_before_it_closes_and_a_clean_one_does_not() { + let mut area = area(); + let key = area.open(&area.users.id.clone()); + area.ask(Http::AskClose(key)); + assert!(area.held.state.http.tabs().tabs().is_empty()); + + let key = area.open(&area.users.id.clone()); + area.edit(&key, DraftEdit::Method(HttpMethod::Put)); + area.ask(Http::AskClose(key.clone())); + assert!(area.held.state.http.tabs().closing().is_some()); + area.ask(Http::CancelClose); + assert_eq!(area.held.state.http.tabs().tabs().len(), 1); + area.ask(Http::SaveAndClose(key)); + assert!(area.held.state.http.tabs().tabs().is_empty()); + let found = tree::find_request(area.held.state.http.tree(), &area.users.id).unwrap(); + assert_eq!(found.method, HttpMethod::Put); +} + +#[test] +fn a_tab_is_moved_one_place_at_a_time_and_stays_within_the_strip() { + let mut area = area(); + let first = area.open(&area.users.id.clone()); + let second = area.open(&area.login.id.clone()); + let order = |area: &Area| -> Vec { + area.held + .state + .http + .tabs() + .tabs() + .iter() + .map(|tab| tab.key.clone()) + .collect() + }; + for (key, right, expected) in [ + (&first, true, [&second, &first]), + (&first, true, [&second, &first]), + (&first, false, [&first, &second]), + (&first, false, [&first, &second]), + ] { + area.ask(Http::NudgeTab { + key: key.clone(), + right, + }); + assert_eq!(order(&area), expected.map(Clone::clone)); + } +} + +#[test] +fn what_is_asked_of_a_tab_that_is_gone_does_nothing() { + let mut area = area(); + let key = area.open(&area.users.id.clone()); + let gone = || "gone".to_owned(); + for action in [ + Http::NudgeTab { + key: gone(), + right: true, + }, + Http::MoveTab { + key: gone(), + gap: 0, + }, + Http::AskClose(gone()), + Http::Close(gone()), + Http::Save(gone()), + Http::SaveAndClose(gone()), + Http::ChooseBody { + key: gone(), + kind: BodyKind::Json, + }, + Http::Send(Some(gone())), + Http::SendAnyway(gone()), + Http::SendFile(gone(), "a.txt".to_owned()), + Http::CancelSend(gone()), + Http::ClearResponse(gone()), + Http::SendMessage { + key: gone(), + text: "a".to_owned(), + }, + Http::ClearSocketLog(gone()), + Http::Activate(gone()), + ] { + area.ask(action); + } + + assert_eq!(area.held.state.http.tabs().active_key(), Some(key.as_str())); + assert!(!area.held.state.http.tabs().active().unwrap().is_dirty()); + assert_eq!(area.held.failed(), None); +} + +#[test] +fn a_request_deleted_elsewhere_cannot_be_opened_and_says_so() { + let mut area = area(); + area.ask(Http::OpenRequest("gone".to_owned())); + + assert!(area.held.state.http.tabs().tabs().is_empty()); + assert!(area.held.failed().is_some()); +} + +// Bodies + +#[test] +fn a_file_chosen_goes_where_it_was_asked_for() { + let path = || "a.png".to_owned(); + assert_eq!( + with_file( + &RequestBody::Binary { + path: String::new() + }, + FileFor::Body, + path() + ), + Some(RequestBody::Binary { path: path() }) + ); + let parts = RequestBody::Multipart { parts: Vec::new() }; + let Some(RequestBody::Multipart { parts: filled }) = + with_file(&parts, FileFor::Part(0), path()) + else { + panic!("a part"); + }; + assert!(filled.len() == 1 && filled[0].file && filled[0].value == "a.png"); + for (body, target) in [ + (&parts, FileFor::Part(1)), + (&parts, FileFor::Body), + (&RequestBody::None, FileFor::Body), + ( + &RequestBody::Text { + text: String::new(), + }, + FileFor::Part(0), + ), + ] { + assert_eq!(with_file(body, target, path()), None, "{target:?}"); + } +} + +#[test] +fn each_kind_of_body_starts_empty_and_is_read_back_as_its_kind() { + for kind in BodyKind::ALL { + assert_eq!(BodyKind::of(&body_of_kind(kind, &BodiesLeft::new())), kind); + } +} + +#[test] +fn a_file_is_picked_for_a_body_and_a_dialog_cancelled_leaves_it() { + let mut area = area(); + let key = area.open(&area.users.id.clone()); + area.ask(Http::ChooseBody { + key: key.clone(), + kind: BodyKind::Binary, + }); + let pick = || Http::PickFile { + key: key.clone(), + target: FileFor::Body, + }; + area.held.state.dialog = Arc::new(NoDialog); + area.ask(pick()); + area.held.state.dialog = Arc::new(Fixed("plan.bin".into())); + let body = |area: &Area| { + area.held + .state + .http + .tabs() + .active() + .unwrap() + .draft + .document + .body + .clone() + }; + assert_eq!( + body(&area), + RequestBody::Binary { + path: String::new() + } + ); + + area.ask(pick()); + assert_eq!( + body(&area), + RequestBody::Binary { + path: "plan.bin".to_owned() + } + ); +} + +/// The tab closed while the dialog was open. +#[test] +fn a_file_picked_for_a_tab_closed_since_goes_nowhere() { + let mut area = area(); + let key = area.open(&area.users.id.clone()); + area.held.state.dialog = Arc::new(Fixed("plan.bin".into())); + let pick = Http::PickFile { + key: key.clone(), + target: FileFor::Body, + }; + area.held + .state + .apply(Action::Http(pick), &area.held.ctx, &area.held.backend); + area.ask(Http::Close(key)); + + assert!(area.held.state.http.tabs().tabs().is_empty()); + assert_eq!(area.held.failed(), None); +} + +// Moves with the keys + +#[test] +fn a_move_with_nowhere_to_go_says_why() { + use i18n::keys::http::rail::moved::refused; + let mut area = area(); + let folder = item(HttpItemKind::Folder, &area.auth); + let collection = item(HttpItemKind::Collection, &area.api); + let users = item(HttpItemKind::Request, &area.users.id); + for (moved, key, said) in [ + (&folder, KeyMove::Up, refused::FIRST), + (&users, KeyMove::Down, refused::LAST), + (&folder, KeyMove::Out, refused::AT_ROOT), + (&collection, KeyMove::In, refused::COLLECTION), + ] { + area.ask(Http::KeyMove { + item: moved.clone(), + name: "it".to_owned(), + key, + }); + assert_eq!(area.held.state.http.said().unwrap().1.key, said, "{key:?}"); + } +} + +#[test] +fn a_container_is_found_by_its_id_at_any_depth() { + let area = area(); + let tree = area.held.state.http.tree(); + + let auth = tree::container_of(tree, &area.auth).unwrap(); + assert_eq!( + (auth.name.as_str(), auth.collection_id.as_str()), + ("Auth", area.api.as_str()) + ); + assert_eq!(tree::container_of(tree, &area.api).unwrap().name, "API"); + for id in [area.users.id.as_str(), "gone"] { + assert!(tree::container_of(tree, id).is_none(), "{id}"); + } +} + +// Answers + +#[test] +fn an_answer_is_saved_to_a_file_and_a_dialog_cancelled_saves_none() { + let mut area = area(); + let key = area.sent("/json"); + let sent = area.held.state.http.sends().of(&key).unwrap(); + let id = sent.id.clone(); + let directory = tempfile::tempdir().unwrap(); + let file = directory.path().join("answer.json"); + let save = || Http::SaveResponseFile { + send_id: id.clone(), + name: "answer.json".to_owned(), + }; + area.held.state.dialog = Arc::new(NoDialog); + area.ask(save()); + assert_eq!(area.held.done(), None); + + area.held.state.dialog = Arc::new(Fixed(file.clone())); + area.ask(save()); + assert!(std::fs::read_to_string(&file).unwrap().contains("Ada")); + assert!(area.held.done().unwrap().contains("answer.json")); +} + +#[test] +fn an_answer_let_go_cannot_be_saved_and_says_so() { + let mut area = area(); + let directory = tempfile::tempdir().unwrap(); + area.held.state.dialog = Arc::new(Fixed(directory.path().join("answer.json"))); + area.ask(Http::SaveResponseFile { + send_id: "gone".to_owned(), + name: "a".to_owned(), + }); + + assert_eq!( + area.held.state.status.latest().unwrap().1.key, + i18n::keys::http::response::SAVE_FAILED + ); +} + +#[test] +fn an_answer_copied_is_on_the_clipboard_and_said() { + let mut area = area(); + area.ask(Http::Copy("text".to_owned())); + + assert_eq!( + area.held.state.status.latest().unwrap().1.key, + i18n::keys::settings::COPIED + ); +} + +// The history + +#[test] +fn an_entry_deleted_is_selected_no_more_and_comes_back_by_undo() { + let mut area = area(); + area.sent("/json"); + area.ask(Http::ShowPage(super::Page::History)); + let entry = area.held.state.http.history().days()[0].items[0].id.clone(); + area.ask(Http::History(Hist::Select(entry.clone()))); + assert_eq!( + area.held.state.http.history().selected(), + Some(entry.as_str()) + ); + area.ask(Http::History(Hist::Delete(entry))); + assert!(area.held.state.http.history().days().is_empty()); + assert_eq!(area.held.state.http.history().selected(), None); + + area.ask(Http::History(Hist::Undo)); + assert_eq!(area.held.state.http.history().days().len(), 1); +} + +#[test] +fn an_undo_put_away_is_offered_no_more() { + let mut area = area(); + area.sent("/json"); + area.ask(Http::ShowPage(super::Page::History)); + let entry = area.held.state.http.history().days()[0].items[0].id.clone(); + area.ask(Http::History(Hist::Delete(entry))); + assert!(area.held.state.http.history().removed().is_some()); + + area.ask(Http::History(Hist::DismissUndo)); + assert!(area.held.state.http.history().removed().is_none()); + area.ask(Http::History(Hist::Undo)); + assert!(area.held.state.http.history().days().is_empty()); +} + +#[test] +fn the_history_is_emptied_once_its_count_was_agreed_to() { + let mut area = area(); + area.sent("/json"); + area.ask(Http::ShowPage(super::Page::History)); + area.ask(Http::History(Hist::AskClear)); + assert_eq!(area.held.state.http.history().confirming(), Some(1)); + area.ask(Http::History(Hist::CancelClear)); + assert_eq!(area.held.state.http.history().days().len(), 1); + + area.ask(Http::History(Hist::AskClear)); + area.ask(Http::History(Hist::Clear)); + assert!(area.held.state.http.history().days().is_empty()); + assert!(area.held.done().is_some()); +} + +// The cookies + +#[test] +fn the_cookies_of_a_domain_go_together_and_the_jar_once_agreed_to() { + let mut area = area(); + area.sent("/json"); + area.ask(Http::Cookies(cookies::Asked::Open)); + let domains = |area: &Area| { + area.held + .state + .http + .cookies() + .domains() + .map_or(0, <[_]>::len) + }; + assert_eq!(domains(&area), 1); + area.ask(Http::Cookies(cookies::Asked::RemoveDomain( + "127.0.0.1".to_owned(), + ))); + assert_eq!(domains(&area), 0); + + area.ask(Http::Cookies(cookies::Asked::AskClear)); + assert_eq!(area.held.state.http.cookies().confirming(), Some(0)); + area.ask(Http::Cookies(cookies::Asked::CancelClear)); + assert_eq!(area.held.state.http.cookies().confirming(), None); + area.ask(Http::Cookies(cookies::Asked::Close)); + assert!(!area.held.state.http.cookies().is_open()); +} + +// The runner + +fn collection_run(area: &mut Area) { + let target = RunTarget { + item: item(HttpItemKind::Collection, &area.api), + name: "API".to_owned(), + }; + area.ask(Http::Runner(Run::Open(target))); +} + +#[test] +fn a_run_is_set_up_and_keeps_its_options() { + let mut area = area(); + collection_run(&mut area); + for asked in [ + Run::Iterations(3), + Run::Delay(250), + Run::StopOnFailure(true), + Run::KeepVariables(true), + Run::KeepResponses(true), + ] { + area.ask(Http::Runner(asked)); + } + + let runner = area.held.state.http.runner(); + assert_eq!((runner.runs(), runner.delay_ms()), (3, 250)); + assert!(runner.stop_on_failure() && runner.keep_variables() && runner.keep_responses()); +} + +#[test] +fn a_run_of_nothing_never_starts() { + let mut area = area(); + collection_run(&mut area); + let rows = area.held.state.http.runner().rows().len(); + assert_eq!(rows, 2); + for at in 0..rows { + area.ask(Http::Runner(Run::Toggle(at))); + } + assert_eq!(area.held.state.http.runner().enabled_count(), 0); + + area.ask(Http::Runner(Run::Start)); + assert!(!area.held.state.http.runner().is_running()); + assert_eq!(area.held.state.http.runner().phase(), Phase::Idle); +} + +#[test] +fn a_data_file_not_chosen_leaves_the_run_without_one() { + let mut area = area(); + collection_run(&mut area); + area.held.state.dialog = Arc::new(NoDialog); + area.ask(Http::Runner(Run::ChooseData)); + assert!(area.held.state.http.runner().data().is_none()); + + area.held.state.dialog = Arc::new(Fixed("no-such-file.csv".into())); + area.ask(Http::Runner(Run::ChooseData)); + assert!(area.held.state.http.runner().data().is_none()); + assert!(area.held.failed().is_some()); +} + +// What the core refuses + +#[test] +fn what_is_refused_in_the_area_is_said() { + type Asks = fn(&mut Area); + let gestures: [(&str, Asks); 11] = [ + ("open", |a| a.ask(Http::OpenRequest(a.login.id.clone()))), + ("ask a deletion", |a| { + a.ask(Http::AskDelete(item(HttpItemKind::Collection, &a.api))); + }), + ("settings", |a| { + let container = tree::container_of(a.held.state.http.tree(), &a.auth).unwrap(); + a.ask(Http::OpenSettings(container)); + }), + ("move", |a| { + let moved = item(HttpItemKind::Request, &a.users.id); + a.ask(Http::KeyMove { + item: moved, + name: "Users".to_owned(), + key: KeyMove::Up, + }); + }), + ("create an environment", |a| { + a.env(Env::Create("Prod".to_owned())); + }), + ("rename an environment", |a| { + a.env(Env::Rename { + id: "a".to_owned(), + name: "b".to_owned(), + }); + }), + ("the cookies", |a| { + a.ask(Http::Cookies(cookies::Asked::Open)); + }), + ("the history", |a| { + a.ask(Http::ShowPage(super::Page::History)); + }), + ("empty the history", |a| { + a.ask(Http::History(Hist::AskClear)); + }), + ("delete from the history", |a| { + a.ask(Http::History(Hist::Delete("a".to_owned()))); + }), + ("a run", collection_run), + ]; + for (name, asks) in gestures { + let mut area = area(); + assert_eq!(area.held.failed(), None, "{name}: before"); + area.held.close_library(); + asks(&mut area); + assert!( + area.held.failed().is_some(), + "{name} is refused and nothing says it" + ); + } +} + +#[test] +fn a_request_that_cannot_be_written_says_so_and_stays_modified() { + let mut area = area(); + let key = area.open(&area.users.id.clone()); + area.edit(&key, DraftEdit::Method(HttpMethod::Delete)); + area.held.close_library(); + area.ask(Http::SaveAndClose(key)); + + assert!(area.held.failed().is_some()); + assert!(area.held.state.http.tabs().active().unwrap().is_dirty()); +} + +// The sockets + +/// A tab's socket, on its way to an address nothing answers. +fn connecting() -> (Area, Sockets, String) { + let mut area = area(); + let key = area.open(&area.users.id.clone()); + let tab = area.held.state.http.tabs().tab(&key).unwrap().clone(); + let mut sockets = Sockets::default(); + sockets.connect(&area.held.backend, &tab, None); + (area, sockets, key) +} + +fn event( + sockets: &Sockets, + key: &str, + event: engine::http::websocket::SocketEvent, +) -> engine::http::websocket::WebsocketEvent { + engine::http::websocket::WebsocketEvent { + id: sockets.of(key).unwrap().socket_id().to_owned(), + at: chrono::Utc::now(), + event, + } +} + +#[test] +fn a_socket_follows_its_events_to_its_end() { + use engine::http::websocket::SocketEvent; + let (_area, mut sockets, key) = connecting(); + assert!(sockets.is_live(&key) && !sockets.is_open(&key)); + + let opened = event( + &sockets, + &key, + SocketEvent::Opened { + url: String::new(), + protocol: Some("chat".to_owned()), + }, + ); + sockets.receive(opened); + assert!(sockets.is_open(&key)); + assert_eq!(sockets.of(&key).unwrap().protocol.as_deref(), Some("chat")); + + let failed = event( + &sockets, + &key, + SocketEvent::Failed { + code: engine::error::ErrorCode::HttpNetwork, + params: std::collections::BTreeMap::new(), + detail: "reset".to_owned(), + }, + ); + sockets.receive(failed); + let state = sockets.of(&key).unwrap(); + assert_eq!(state.phase, SocketPhase::Closed); + assert_eq!( + state.notice.as_ref().unwrap().code, + engine::error::ErrorCode::HttpNetwork + ); + assert!(!sockets.is_live(&key)); +} + +#[test] +fn an_event_of_another_connection_changes_nothing() { + use engine::http::websocket::SocketEvent; + let (_area, mut sockets, key) = connecting(); + let mut other = event( + &sockets, + &key, + SocketEvent::Opened { + url: String::new(), + protocol: None, + }, + ); + "another".clone_into(&mut other.id); + sockets.receive(other); + + assert!(!sockets.is_open(&key)); +} + +#[test] +fn one_socket_a_tab_while_it_lives_and_its_log_kept_for_the_next() { + use engine::http::websocket::SocketEvent; + let (area, mut sockets, key) = connecting(); + let tab = area.held.state.http.tabs().tab(&key).unwrap().clone(); + let first = sockets.of(&key).unwrap().socket_id().to_owned(); + sockets.connect(&area.held.backend, &tab, None); + assert_eq!(sockets.of(&key).unwrap().socket_id(), first); + + let closed = event( + &sockets, + &key, + SocketEvent::Closed { + code: Some(1000), + reason: String::new(), + }, + ); + sockets.receive(closed); + let logged = sockets.of(&key).unwrap().log.len(); + assert!(logged > 0); + sockets.connect(&area.held.backend, &tab, None); + assert_ne!(sockets.of(&key).unwrap().socket_id(), first); + assert_eq!(sockets.of(&key).unwrap().log.len(), logged); + sockets.clear_log(&key); + assert!(sockets.of(&key).unwrap().log.is_empty()); +} + +#[test] +fn a_socket_closed_by_the_person_is_closing_until_it_is_closed() { + let (area, mut sockets, key) = connecting(); + sockets.close(&area.held.backend, &key); + assert_eq!(sockets.of(&key).unwrap().phase, SocketPhase::Closing); + let before = area.held.backend.launched(); + sockets.close(&area.held.backend, &key); + sockets.send(&area.held.backend, &key, "late".to_owned()); + assert_eq!( + area.held.backend.launched(), + before, + "nothing more is asked of it" + ); +} + +#[test] +fn a_tab_saved_keeps_its_socket_and_a_tab_closed_lets_it_go() { + let (area, mut sockets, key) = connecting(); + sockets.rekey(&key, "saved"); + assert!(sockets.of(&key).is_none() && sockets.is_live("saved")); + sockets.rekey("gone", "elsewhere"); + assert!(sockets.of("elsewhere").is_none()); + + sockets.forget(&area.held.backend, "saved"); + assert_eq!(sockets.keys().count(), 0); +} diff --git a/crates/ui/src/state/http/mod.rs b/crates/ui/src/state/http/mod.rs index 5210b7113..968c87d78 100644 --- a/crates/ui/src/state/http/mod.rs +++ b/crates/ui/src/state/http/mod.rs @@ -2,6 +2,8 @@ //! the tree read again: the core renumbers what a move or a copy touched, and the interface never //! guesses the result. +#[cfg(test)] +mod area_tests; pub mod bodies; pub mod code; pub mod console; diff --git a/crates/ui/src/state/mod.rs b/crates/ui/src/state/mod.rs index ba01436e2..8d28922b2 100644 --- a/crates/ui/src/state/mod.rs +++ b/crates/ui/src/state/mod.rs @@ -33,6 +33,14 @@ mod apply_http; mod apply_notes; mod apply_tools; mod apply_window; +#[cfg(test)] +pub(crate) mod held; +#[cfg(test)] +mod notes_tests; +#[cfg(test)] +mod refused_tests; +#[cfg(test)] +mod window_tests; pub use query::QueryCell; use engine::folders::board::PreviewLines; diff --git a/crates/ui/src/state/notes_tests.rs b/crates/ui/src/state/notes_tests.rs new file mode 100644 index 000000000..b8f631dea --- /dev/null +++ b/crates/ui/src/state/notes_tests.rs @@ -0,0 +1,592 @@ +//! The notes' state as the actions change it, without a window. + +use engine::folders::board::BoardFrame; +use engine::folders::model::Folder; +use engine::notes::kind::NoteKind; +use engine::notes::priority::Priority; + +use super::held::{Held, held}; +use crate::notes::canvas::grid::Direction; +use crate::notes::canvas::shortcuts::CanvasKey; +use crate::notes::{Action as Notes, Batch, BoardGesture, Tags, Trash, bench}; +use crate::state::board::Mode; +use crate::state::notes_query::Facet; +use crate::testing; + +/// Notes of those titles in one space. +fn with_notes(titles: &[&str]) -> (Held, Vec) { + let (backend, profile) = testing::unlocked(); + let ids = titles + .iter() + .map(|title| testing::note(&backend, title).id.clone()) + .collect(); + (held((backend, profile)), ids) +} + +/// A folder `a` holding `b` holding `c`. +fn nested() -> (Held, [Folder; 3]) { + let (backend, profile) = testing::unlocked(); + let space = bench::space(&backend, "Home"); + let a = bench::folder(&backend, &space, None, "a"); + let b = bench::folder(&backend, &space, Some(&a), "b"); + let c = bench::folder(&backend, &space, Some(&b), "c"); + (held((backend, profile)), [a, b, c]) +} + +fn focus(held: &mut Held, id: &str) { + held.state.notes_view.canvas.focused = Some(id.to_owned()); +} + +// The keys of the canvas + +#[test] +fn a_key_of_the_canvas_acts_on_the_card_with_the_focus() { + let (mut held, ids) = with_notes(&["psql", "curl"]); + focus(&mut held, &ids[0]); + + held.key(CanvasKey::Pin); + assert!(held.note(&ids[0]).pinned && !held.note(&ids[1]).pinned); + held.key(CanvasKey::Pin); + assert!(!held.note(&ids[0]).pinned); + held.key(CanvasKey::Priority(Priority::High)); + assert_eq!(held.note(&ids[0]).priority, Priority::High); + held.key(CanvasKey::Check); + assert!(held.state.selection.is_checked(&ids[0])); + held.key(CanvasKey::Copy); + assert!(held.done().unwrap().contains("psql"), "{:?}", held.done()); +} + +#[test] +fn without_a_card_in_focus_the_keys_that_need_one_do_nothing() { + let (mut held, ids) = with_notes(&["psql"]); + for key in [ + CanvasKey::Pin, + CanvasKey::Priority(Priority::High), + CanvasKey::Check, + CanvasKey::Copy, + CanvasKey::Trash, + ] { + held.key(key); + } + + let note = held.note(&ids[0]); + assert!(!note.pinned && note.priority == Priority::None); + assert!(!held.state.selection.is_checked(&ids[0])); + assert_eq!(held.done(), None); +} + +/// The focused card can be scrolled out of view: it takes two. +#[test] +fn the_key_of_the_trash_is_pressed_twice() { + let (mut held, ids) = with_notes(&["psql", "curl"]); + focus(&mut held, &ids[0]); + + held.key(CanvasKey::Trash); + assert_eq!(held.shown().len(), 2); + held.key(CanvasKey::Trash); + assert_eq!(held.shown(), ["curl"]); +} + +#[test] +fn the_focus_moves_from_card_to_card_as_they_are_shown() { + let (mut held, _) = with_notes(&["one", "two", "three"]); + let order = held.state.on_screen(); + focus(&mut held, &order[0]); + + held.key(CanvasKey::Move(Direction::Next)); + assert_eq!( + held.state.notes_view.canvas.request.as_ref(), + Some(&order[1]) + ); +} + +#[test] +fn on_the_board_the_focus_walks_the_cards_one_by_one() { + let (mut held, ids) = with_notes(&["one", "two"]); + let space = held.note(&ids[0]).space_id.clone(); + held.notes(Notes::ChooseSpace(Some(space))); + held.notes(Notes::SetView(Mode::Board)); + let order = held.state.on_screen(); + assert_eq!(order.len(), 2); + focus(&mut held, &order[0]); + + held.key(CanvasKey::Move(Direction::Down)); + assert_eq!( + held.state.notes_view.canvas.request.as_ref(), + Some(&order[1]) + ); + held.key(CanvasKey::Pin); + assert!(held.note(&order[0]).pinned, "read from the board's cards"); + held.key(CanvasKey::Pin); + assert!(!held.note(&order[0]).pinned); +} + +#[test] +fn the_key_of_undo_puts_the_last_write_back_once_its_bar_is_gone() { + let (mut held, ids) = with_notes(&["psql"]); + held.notes(Notes::Pin { + id: ids[0].clone(), + pinned: true, + }); + assert!(held.state.undo.banner(1e9).is_none()); + + held.key(CanvasKey::Undo); + assert!(!held.note(&ids[0]).pinned); +} + +// Escape + +#[test] +fn escape_goes_down_one_rung_at_a_time() { + let (mut held, ids) = with_notes(&["psql", "curl"]); + focus(&mut held, &ids[0]); + held.notes(Notes::SetFilter(engine::notes::view::NoteFilter::Pinned)); + held.notes(Notes::SetFilter(engine::notes::view::NoteFilter::All)); + held.notes(Notes::Facet(Facet::Kind(NoteKind::Snippet))); + held.notes(Notes::Check(ids[1].clone())); + held.key(CanvasKey::Trash); + + held.key(CanvasKey::StepBack); + assert!( + held.state.selection.is_checked(&ids[1]), + "what is armed first" + ); + held.key(CanvasKey::StepBack); + assert!( + !held.state.selection.is_checked(&ids[1]), + "then the selection" + ); + assert!(held.state.notes_query.has_user_filters()); + held.key(CanvasKey::StepBack); + assert!( + !held.state.notes_query.has_user_filters(), + "then the search" + ); +} + +#[test] +fn escape_climbs_the_folders_to_their_space_and_no_further() { + let (mut held, [a, b, c]) = nested(); + held.notes(Notes::ChooseFolder(c.id.clone())); + + for shown in [Some(&b.id), Some(&a.id), None, None] { + held.key(CanvasKey::StepBack); + assert_eq!(held.state.active_folder(), shown.map(String::as_str)); + } + assert_eq!(held.state.spaces.active_space(), Some(a.space_id.as_str())); +} + +#[test] +fn escape_takes_back_what_the_bar_offers_while_it_is_there() { + let (mut held, ids) = with_notes(&["psql"]); + held.notes(Notes::Pin { + id: ids[0].clone(), + pinned: true, + }); + + held.key(CanvasKey::StepBack); + assert!(!held.note(&ids[0]).pinned); +} + +// The selection + +#[test] +fn each_batch_acts_on_the_notes_ticked_and_on_no_other() { + let (mut held, ids) = with_notes(&["one", "two", "three"]); + held.notes(Notes::Check(ids[0].clone())); + held.notes(Notes::Check(ids[1].clone())); + + held.notes(Notes::Batch(Batch::Prioritise(Priority::Urgent))); + held.notes(Notes::Batch(Batch::Tag("ops".to_owned()))); + held.notes(Notes::Batch(Batch::Pin(true))); + for (id, ticked) in [(&ids[0], true), (&ids[1], true), (&ids[2], false)] { + let note = held.note(id); + assert_eq!(note.priority == Priority::Urgent, ticked); + assert_eq!(note.tags == ["ops"], ticked); + assert_eq!(note.pinned, ticked); + } + held.notes(Notes::Batch(Batch::Untag("ops".to_owned()))); + assert!(held.note(&ids[0]).tags.is_empty()); +} + +#[test] +fn a_batch_on_nothing_asks_nothing() { + let (mut held, ids) = with_notes(&["one"]); + held.notes(Notes::Batch(Batch::Delete)); + + assert_eq!(held.shown(), ["one"]); + assert!(!held.note(&ids[0]).pinned); + assert!(held.state.undo.last().is_none()); +} + +#[test] +fn the_notes_deleted_together_are_ticked_no_more() { + let (mut held, ids) = with_notes(&["one", "two"]); + held.notes(Notes::Check(ids[0].clone())); + held.notes(Notes::Batch(Batch::Delete)); + + assert_eq!(held.shown(), ["two"]); + assert!(!held.state.selection.is_checked(&ids[0])); +} + +// Where a note goes + +#[test] +fn a_new_note_goes_where_the_person_is_looking() { + let (mut held, [a, ..]) = nested(); + held.notes(Notes::ChooseFolder(a.id.clone())); + held.notes(Notes::NewNote(None)); + + let draft = held.state.editor.opened().unwrap().note().unwrap(); + assert_eq!( + (&draft.space_id, draft.folder_id.as_ref()), + (&a.space_id, Some(&a.id)) + ); + assert_eq!(draft.kind, held.state.settings.default_note_kind); +} + +#[test] +fn over_all_the_spaces_a_new_note_goes_to_the_first() { + let (mut held, [a, ..]) = nested(); + held.notes(Notes::ChooseSpace(None)); + held.notes(Notes::NewNote(Some(NoteKind::Calc))); + + let draft = held.state.editor.opened().unwrap().note().unwrap(); + assert_eq!((&draft.space_id, &draft.folder_id), (&a.space_id, &None)); + assert_eq!(draft.kind, NoteKind::Calc); +} + +#[test] +fn without_a_space_a_new_note_is_refused_and_said() { + let mut held = held(testing::unlocked()); + for action in [ + Notes::NewNote(None), + Notes::Canvas(CanvasKey::New(NoteKind::Note)), + ] { + held.notes(action); + assert!(!held.state.editor.is_open()); + } + + let said = held.state.errors.notice().unwrap().key; + assert_eq!(said, i18n::keys::errors::SPACE_REQUIRED); +} + +// Folders + +#[test] +fn a_folder_is_nudged_out_a_level_and_into_the_one_above_it() { + let (backend, profile) = testing::unlocked(); + let space = bench::space(&backend, "Home"); + let first = bench::folder(&backend, &space, None, "First"); + let second = bench::folder(&backend, &space, None, "Second"); + let mut held = held((backend, profile)); + let parent = |held: &Held| { + held.state + .folders + .find(&second.id) + .unwrap() + .parent_id + .clone() + }; + + held.notes(Notes::NudgeFolder { + id: second.id.clone(), + outwards: false, + }); + assert_eq!(parent(&held), Some(first.id.clone())); + held.notes(Notes::NudgeFolder { + id: second.id.clone(), + outwards: true, + }); + assert_eq!(parent(&held), None); +} + +#[test] +fn a_nudge_with_nowhere_to_go_is_said() { + use i18n::keys::sidebar::moved::refused; + let (mut held, [a, ..]) = nested(); + + held.notes(Notes::NudgeFolder { + id: a.id.clone(), + outwards: true, + }); + assert_eq!(held.state.status.latest().unwrap().1.key, refused::AT_TOP); + held.notes(Notes::NudgeFolder { + id: a.id.clone(), + outwards: false, + }); + assert_eq!( + held.state.status.latest().unwrap().1.key, + refused::NO_FOLDER_ABOVE + ); +} + +#[test] +fn a_folder_that_cannot_go_there_is_refused_and_said() { + use i18n::keys::sidebar::moved; + let (mut held, [a, b, c]) = nested(); + for (id, parent, said) in [ + (&b.id, Some(a.id.clone()), moved::ALREADY), + (&a.id, None, moved::ALREADY), + (&a.id, Some(c.id.clone()), moved::refused::THERE), + (&a.id, Some(a.id.clone()), moved::refused::THERE), + ] { + held.notes(Notes::MoveFolder { + id: id.clone(), + parent, + space: a.space_id.clone(), + }); + assert_eq!(held.state.status.latest().unwrap().1.key, said); + assert_eq!(held.failed(), None); + } +} + +#[test] +fn what_is_asked_of_a_folder_that_is_gone_does_nothing() { + let (mut held, [a, ..]) = nested(); + let gone = "gone".to_owned(); + held.notes(Notes::MoveFolder { + id: gone.clone(), + parent: None, + space: a.space_id.clone(), + }); + held.notes(Notes::NudgeFolder { + id: gone.clone(), + outwards: true, + }); + held.notes(Notes::ChooseFolder(gone)); + + assert_eq!((held.done(), held.failed()), (None, None)); + assert_eq!(held.state.active_folder(), None); +} + +// The board + +/// There is no board across every space. +#[test] +fn over_all_the_spaces_there_is_no_board() { + let (mut held, _) = with_notes(&["one"]); + held.notes(Notes::ChooseSpace(None)); + held.notes(Notes::SetView(Mode::Board)); + held.notes(Notes::Board(BoardGesture::DrawZone(BoardFrame { + x: 0, + y: 0, + width: 200, + height: 200, + }))); + + assert!(held.state.board_place().is_none()); + assert!(held.state.board.drawn_zone().is_none()); +} + +#[test] +fn a_zone_is_made_once_it_is_named() { + let (mut held, ids) = with_notes(&["one"]); + let space = held.note(&ids[0]).space_id.clone(); + held.notes(Notes::ChooseSpace(Some(space))); + held.notes(Notes::SetView(Mode::Board)); + let frame = BoardFrame { + x: 0, + y: 0, + width: 240, + height: 200, + }; + + held.notes(Notes::Board(BoardGesture::DrawZone(frame))); + assert_eq!(held.state.board.drawn_zone(), Some(frame)); + held.notes(Notes::NameZone(" ".to_owned())); + assert!( + held.state.folders.list().is_empty(), + "a name of spaces is none" + ); + held.notes(Notes::Board(BoardGesture::DrawZone(frame))); + held.notes(Notes::NameZone(" Scripts ".to_owned())); + let names: Vec<&str> = held + .state + .folders + .list() + .iter() + .map(|folder| folder.name.as_str()) + .collect(); + assert_eq!(names, ["Scripts"]); +} + +// The tags + +fn tagged() -> (Held, Vec) { + let (mut held, ids) = with_notes(&["one", "two"]); + held.notes(Notes::Check(ids[0].clone())); + held.notes(Notes::Batch(Batch::Tag("db".to_owned()))); + held.notes(Notes::ClearSelection); + held.notes(Notes::Check(ids[1].clone())); + held.notes(Notes::Batch(Batch::Tag("ops".to_owned()))); + held.notes(Notes::Tags(Tags::Open)); + (held, ids) +} + +fn tick(held: &mut Held, tag: &str) { + held.notes(Notes::Tags(Tags::Toggle(tag.to_owned()))); +} + +/// One ticked is renamed, several are merged, and nothing is done before it is confirmed. +#[test] +fn a_change_of_tags_is_proposed_with_its_count_then_confirmed() { + use crate::state::tags::ChangeKind; + let (mut held, ids) = tagged(); + tick(&mut held, "db"); + held.notes(Notes::Tags(Tags::Rename(" base ".to_owned()))); + let pending = held.state.tags.pending().unwrap(); + assert_eq!( + (pending.kind, pending.notes, pending.into.as_str()), + (ChangeKind::Rename, 1, "base") + ); + assert_eq!(held.note(&ids[0]).tags, ["db"]); + + tick(&mut held, "ops"); + assert!( + held.state.tags.pending().is_none(), + "another selection withdraws it" + ); + held.notes(Notes::Tags(Tags::Rename("base".to_owned()))); + let pending = held.state.tags.pending().unwrap(); + assert_eq!((pending.kind, pending.notes), (ChangeKind::Merge, 2)); + held.notes(Notes::Tags(Tags::Confirm)); + assert_eq!( + [ + held.note(&ids[0]).tags.clone(), + held.note(&ids[1]).tags.clone() + ], + [["base"], ["base"]] + ); +} + +#[test] +fn tags_are_deleted_from_their_notes_once_confirmed() { + let (mut held, ids) = tagged(); + tick(&mut held, "db"); + held.notes(Notes::Tags(Tags::Delete)); + held.notes(Notes::Tags(Tags::Cancel)); + held.notes(Notes::Tags(Tags::Confirm)); + assert_eq!(held.note(&ids[0]).tags, ["db"], "cancelled"); + + held.notes(Notes::Tags(Tags::Delete)); + held.notes(Notes::Tags(Tags::Confirm)); + assert!(held.note(&ids[0]).tags.is_empty()); + assert_eq!(held.note(&ids[1]).tags, ["ops"]); +} + +#[test] +fn with_nothing_ticked_or_no_name_nothing_is_proposed() { + let (mut held, _) = tagged(); + held.notes(Notes::Tags(Tags::Delete)); + held.notes(Notes::Tags(Tags::Rename("x".to_owned()))); + tick(&mut held, "db"); + held.notes(Notes::Tags(Tags::Rename(" ".to_owned()))); + + assert!(held.state.tags.pending().is_none()); +} + +#[test] +fn the_tags_opened_again_have_nothing_ticked() { + let (mut held, _) = tagged(); + tick(&mut held, "db"); + tick(&mut held, "ops"); + tick(&mut held, "ops"); + assert_eq!(held.state.tags.selected(), 1); + held.notes(Notes::Tags(Tags::Close)); + assert!(!held.state.tags.is_open()); + + held.notes(Notes::Tags(Tags::Open)); + assert_eq!(held.state.tags.selected(), 0); + assert_eq!(held.state.tags.tags().len(), 2); +} + +// The trash + +#[test] +fn the_trash_gives_back_what_was_asked_and_for_good_takes_the_rest() { + let (mut held, ids) = with_notes(&["one", "two", "three"]); + for id in &ids { + held.notes(Notes::Delete(id.clone())); + } + held.notes(Notes::Trash(Trash::Open)); + assert_eq!(held.state.trash.notes().len(), 3); + + held.notes(Notes::Trash(Trash::Restore(ids[0].clone()))); + held.notes(Notes::Trash(Trash::Purge(ids[1].clone()))); + assert_eq!(held.shown(), ["one"]); + assert_eq!(held.state.trash.notes().len(), 1); + held.notes(Notes::Trash(Trash::Empty)); + assert!(held.state.trash.notes().is_empty()); +} + +#[test] +fn everything_found_is_given_back_together() { + let (mut held, ids) = with_notes(&["psql one", "psql two", "curl"]); + for id in &ids { + held.notes(Notes::Delete(id.clone())); + } + held.notes(Notes::Trash(Trash::Open)); + held.notes(Notes::Trash(Trash::Search(" psql ".to_owned()))); + assert!(held.state.trash.searching()); + held.notes(Notes::Trash(Trash::RestoreAll)); + + let mut shown = held.shown(); + shown.sort(); + assert_eq!(shown, ["psql one", "psql two"]); +} + +#[test] +fn the_trash_opened_again_searches_nothing() { + let (mut held, _) = with_notes(&["one"]); + held.notes(Notes::Trash(Trash::Open)); + held.notes(Notes::Trash(Trash::Search("psql".to_owned()))); + held.notes(Notes::Trash(Trash::Close)); + assert!(!held.state.trash.is_open()); + + held.notes(Notes::Trash(Trash::Open)); + assert_eq!(held.state.trash.search(), ""); +} + +// The facets + +#[test] +fn each_facet_is_pressed_then_let_go_and_all_of_a_kind_at_once() { + use engine::notes::language::Language; + let (mut held, _) = with_notes(&["one"]); + let pressed = |held: &Held| held.state.notes_query.facets().count(); + for (each, all) in [ + ( + vec![Facet::Tag("db".to_owned()), Facet::Tag("ops".to_owned())], + Facet::AllTags, + ), + ( + vec![ + Facet::Language(Language::Sql), + Facet::Language(Language::Rs), + ], + Facet::AllLanguages, + ), + ( + vec![Facet::Kind(NoteKind::Note), Facet::Kind(NoteKind::Calc)], + Facet::AllKinds, + ), + ( + vec![ + Facet::Priority(Priority::Low), + Facet::Priority(Priority::High), + ], + Facet::AllPriorities, + ), + ] { + for facet in &each { + held.notes(Notes::Facet(facet.clone())); + } + assert_eq!(pressed(&held), 2, "{all:?}"); + held.notes(Notes::Facet(each[0].clone())); + assert_eq!(pressed(&held), 1, "{all:?}: pressed again, let go"); + held.notes(Notes::Facet(all)); + assert_eq!(pressed(&held), 0); + } + assert!(!held.state.notes_query.has_user_filters()); +} diff --git a/crates/ui/src/state/refused_tests.rs b/crates/ui/src/state/refused_tests.rs new file mode 100644 index 000000000..cc4cb507d --- /dev/null +++ b/crates/ui/src/state/refused_tests.rs @@ -0,0 +1,418 @@ +//! What the core refuses is said, never swallowed, and the window goes on: each gesture asked of +//! a library that closed under it. + +use engine::folders::board::{BoardFrame, BoardPoint, BoardScope}; +use engine::folders::model::FolderColour; +use engine::notes::checklist::ChecklistItem; +use engine::notes::model::HeldNotes; +use engine::notes::priority::Priority; + +use super::held::{Held, held}; +use crate::action::Action; +use crate::notes::destinations::Destination; +use crate::notes::{Action as Notes, Batch, BoardGesture, Editing, Fill, Revisions, Tags, Trash}; +use crate::state::board::Mode; +use crate::testing; + +/// A library of a space, a folder in it and two notes, one with a field and a kept body. +struct Library { + held: Held, + space: String, + folder: String, + note: String, +} + +fn library() -> Library { + let (backend, profile) = testing::unlocked(); + let first = testing::note(&backend, "psql"); + testing::note(&backend, "curl"); + let folder = crate::notes::bench::spaces_of_backend(&backend) + .first() + .map(|space| crate::notes::bench::folder(&backend, space, None, "Scripts")) + .unwrap(); + let mut held = held((backend, profile)); + let patch = engine::notes::model::NotePatch { + content: Some("psql -h {{host}}".to_owned()), + tags: Some(vec!["db".to_owned()]), + ..Default::default() + }; + let id = first.id.clone(); + engine::db::run_here(held.backend.engine(), move |engine| { + engine::notes::update_note(engine, &id, &patch) + }) + .unwrap(); + held.notes(Notes::Reload); + Library { + space: first.space_id.clone(), + folder: folder.id, + note: first.id.clone(), + held, + } +} + +type Before = fn(&mut Library); +type Asks = fn(&mut Library); +type MakesBatch = fn(&Library) -> Batch; +type MakesEditing = fn(&Library) -> Editing; + +fn nothing(_: &mut Library) {} + +fn open_note(library: &mut Library) { + library.held.notes(Notes::OpenNote(library.note.clone())); +} + +fn check(library: &mut Library) { + library.held.notes(Notes::Check(library.note.clone())); +} + +fn on_the_board(library: &mut Library) { + library + .held + .notes(Notes::ChooseSpace(Some(library.space.clone()))); + library.held.notes(Notes::SetView(Mode::Board)); +} + +#[track_caller] +fn said(name: &str, before: Before, asks: Asks) { + let mut library = library(); + before(&mut library); + assert_eq!(library.held.failed(), None, "{name}: before"); + library.held.close_library(); + + asks(&mut library); + library.held.settle(); + + assert!( + library.held.failed().is_some(), + "{name} is refused and nothing says it" + ); +} + +#[test] +fn a_gesture_on_notes_that_is_refused_is_said() { + let gestures: [(&str, Asks); 10] = [ + ("open", open_note), + ("pin", |l| { + l.held.notes(Notes::Pin { + id: l.note.clone(), + pinned: true, + }); + }), + ("prioritise", |l| { + l.held.notes(Notes::Prioritise { + id: l.note.clone(), + priority: Priority::Urgent, + }); + }), + ("move to a folder", |l| { + l.held.notes(Notes::MoveTo { + id: l.note.clone(), + to: Destination::Folder(l.folder.clone()), + }); + }), + ("move to a space", |l| { + l.held.notes(Notes::MoveTo { + id: l.note.clone(), + to: Destination::Space(l.space.clone()), + }); + }), + ("move out of a folder", |l| { + l.held.notes(Notes::MoveTo { + id: l.note.clone(), + to: Destination::NoFolder, + }); + }), + ("delete", |l| l.held.notes(Notes::Delete(l.note.clone()))), + ("duplicate", |l| { + l.held.notes(Notes::Duplicate { + id: l.note.clone(), + title: "copy".to_owned(), + }); + }), + ("copy", |l| l.held.notes(Notes::Copy(l.note.clone()))), + ("tick", |l| { + let item = ChecklistItem { + text: "a".to_owned(), + done: true, + }; + l.held.notes(Notes::SetItems { + id: l.note.clone(), + items: vec![item], + }); + }), + ]; + for (name, asks) in gestures { + said(name, nothing, asks); + } +} + +#[test] +fn a_gesture_on_the_selection_that_is_refused_is_said() { + let batches: [(&str, MakesBatch); 6] = [ + ("move", |l| { + Batch::MoveTo(Destination::Folder(l.folder.clone())) + }), + ("prioritise", |_| Batch::Prioritise(Priority::High)), + ("tag", |_| Batch::Tag("ops".to_owned())), + ("untag", |_| Batch::Untag("db".to_owned())), + ("pin", |_| Batch::Pin(true)), + ("delete", |_| Batch::Delete), + ]; + for (name, batch) in batches { + let mut library = library(); + check(&mut library); + library.held.close_library(); + let batch = batch(&library); + library.held.notes(Notes::Batch(batch)); + assert!(library.held.failed().is_some(), "{name}"); + } +} + +#[test] +fn a_gesture_on_spaces_that_is_refused_is_said() { + let gestures: [(&str, Asks); 4] = [ + ("create", |l| { + l.held.notes(Notes::CreateSpace("Work".to_owned())); + }), + ("rename", |l| { + l.held.notes(Notes::RenameSpace { + id: l.space.clone(), + name: "Work".to_owned(), + }); + }), + ("pin", |l| { + l.held.notes(Notes::PinSpace { + id: l.space.clone(), + pinned: true, + }); + }), + ("delete", |l| { + let refuge = "another".to_owned(); + l.held.notes(Notes::DeleteSpace { + id: l.space.clone(), + refuge, + held: HeldNotes::Keep, + }); + }), + ]; + for (name, asks) in gestures { + said(name, nothing, asks); + } +} + +#[test] +fn a_gesture_on_folders_that_is_refused_is_said() { + let gestures: [(&str, Asks); 5] = [ + ("create", |l| { + l.held.notes(Notes::CreateFolder { + space_id: l.space.clone(), + parent_id: None, + name: "New".to_owned(), + }); + }), + ("rename", |l| { + l.held.notes(Notes::RenameFolder { + id: l.folder.clone(), + name: "New".to_owned(), + }); + }), + ("recolour", |l| { + l.held.notes(Notes::RecolourFolder { + id: l.folder.clone(), + colour: FolderColour::Purple, + }); + }), + ("delete", |l| { + l.held.notes(Notes::DeleteFolder { + id: l.folder.clone(), + held: HeldNotes::Keep, + }); + }), + ("move", |l| { + let space = "another".to_owned(); + l.held.notes(Notes::MoveFolder { + id: l.folder.clone(), + parent: None, + space, + }); + }), + ]; + for (name, asks) in gestures { + said(name, nothing, asks); + } +} + +#[test] +fn a_gesture_on_the_board_that_is_refused_is_said() { + let gestures: [(&str, Asks); 4] = [ + ("tidy", |l| { + l.held.notes(Notes::Tidy(BoardScope::LooseCards)); + }), + ("drop a card", |l| { + let (note_id, folder) = (l.note.clone(), Some(l.folder.clone())); + l.held.notes(Notes::Board(BoardGesture::DropCard { + note_id, + folder, + at: BoardPoint { x: 10, y: 10 }, + })); + }), + ("file on the rail", |l| { + let (note_id, folder) = (l.note.clone(), Some(l.folder.clone())); + l.held + .notes(Notes::Board(BoardGesture::FileOnRail { note_id, folder })); + }), + ("name a zone", |l| { + l.held + .notes(Notes::Board(BoardGesture::DrawZone(BoardFrame { + x: 0, + y: 0, + width: 200, + height: 200, + }))); + l.held.notes(Notes::NameZone("Zone".to_owned())); + }), + ]; + for (name, asks) in gestures { + said(name, on_the_board, asks); + } +} + +#[test] +fn a_gesture_on_the_trash_that_is_refused_is_said() { + let trashed: Before = |l| { + l.held.notes(Notes::Delete(l.note.clone())); + l.held.notes(Notes::DismissUndo); + l.held.notes(Notes::Trash(Trash::Open)); + }; + let gestures: [(&str, Asks); 4] = [ + ("restore", |l| { + l.held.notes(Notes::Trash(Trash::Restore(l.note.clone()))); + }), + ("purge", |l| { + l.held.notes(Notes::Trash(Trash::Purge(l.note.clone()))); + }), + ("restore all", |l| { + l.held.notes(Notes::Trash(Trash::RestoreAll)); + }), + ("empty", |l| l.held.notes(Notes::Trash(Trash::Empty))), + ]; + for (name, asks) in gestures { + said(name, trashed, asks); + } + said("open", nothing, |l| l.held.notes(Notes::Trash(Trash::Open))); +} + +#[test] +fn a_gesture_on_the_tags_that_is_refused_is_said() { + let ticked: Before = |l| { + l.held.notes(Notes::Tags(Tags::Open)); + l.held.notes(Notes::Tags(Tags::Toggle("db".to_owned()))); + }; + let proposed: Before = |l| { + l.held.notes(Notes::Tags(Tags::Open)); + l.held.notes(Notes::Tags(Tags::Toggle("db".to_owned()))); + l.held.notes(Notes::Tags(Tags::Delete)); + }; + said("open", nothing, |l| l.held.notes(Notes::Tags(Tags::Open))); + said("rename", ticked, |l| { + l.held.notes(Notes::Tags(Tags::Rename("base".to_owned()))); + }); + said("delete", ticked, |l| { + l.held.notes(Notes::Tags(Tags::Delete)); + }); + said("confirm", proposed, |l| { + l.held.notes(Notes::Tags(Tags::Confirm)); + }); +} + +#[test] +fn an_undo_that_is_refused_is_said() { + said( + "undo", + |l| { + l.held.notes(Notes::Pin { + id: l.note.clone(), + pinned: true, + }); + }, + |l| l.held.notes(Notes::Undo), + ); +} + +#[test] +fn a_write_of_the_editor_that_is_refused_is_said() { + let editing: [(&str, MakesEditing); 6] = [ + ("save", |l| Editing::Save { + session: l.held.state.editor.opened().unwrap().session, + edit: crate::state::editor::Edit { + title: Some("other".to_owned()), + ..Default::default() + }, + }), + ("pin", |_| Editing::Pin(true)), + ("prioritise", |_| Editing::Prioritise(Priority::Low)), + ("move", |_| Editing::MoveTo("another".to_owned())), + ("file", |l| Editing::File(Some(l.folder.clone()))), + ("delete", |_| Editing::Delete), + ]; + for (name, asked) in editing { + let mut library = library(); + open_note(&mut library); + library.held.close_library(); + let asked = asked(&library); + library.held.notes(Notes::Editor(asked)); + assert!(library.held.failed().is_some(), "{name}"); + } +} + +fn kept(library: &Library) -> String { + library.held.state.revisions.kept()[0].id.clone() +} + +#[test] +fn a_kept_body_that_cannot_be_read_or_put_back_is_said() { + let listed: Before = |l| { + open_note(l); + l.held + .notes(Notes::Editor(Editing::Revisions(Revisions::Toggle))); + }; + let looked: Before = |l| { + open_note(l); + l.held + .notes(Notes::Editor(Editing::Revisions(Revisions::Toggle))); + l.held + .notes(Notes::Editor(Editing::Revisions(Revisions::Look(kept(l))))); + }; + said("look", listed, |l| { + l.held + .notes(Notes::Editor(Editing::Revisions(Revisions::Look(kept(l))))); + }); + said("restore", looked, |l| { + l.held + .notes(Notes::Editor(Editing::Revisions(Revisions::Restore))); + }); +} + +#[test] +fn fields_that_cannot_be_filled_are_said() { + said( + "fill", + |l| l.held.notes(Notes::Copy(l.note.clone())), + |l| { + let values = [("host".to_owned(), "prod".to_owned())].into(); + l.held.notes(Notes::Fill(Fill::Submit(values))); + }, + ); +} + +#[test] +fn a_menu_that_is_refused_is_said() { + use crate::titlebar::Action as Menu; + + said("export", nothing, |l| { + l.held.apply(Action::Menu(Menu::ExportAll)); + }); + said("the backups", nothing, |l| { + l.held.apply(Action::Menu(Menu::OpenPreferences)); + }); +} diff --git a/crates/ui/src/state/transfer.rs b/crates/ui/src/state/transfer.rs index b5e2cf812..8e5737a1c 100644 --- a/crates/ui/src/state/transfer.rs +++ b/crates/ui/src/state/transfer.rs @@ -635,4 +635,157 @@ mod tests { "2 notes exported to notes.devnotes. ⚠️ 1 attachment could not be read and was left out." ); } + + fn import_report() -> ImportReport { + ImportReport { + notes_imported: 3, + ..ImportReport::default() + } + } + + /// The first that applies: a preview that will never load before everything else. + #[test] + fn an_import_says_what_most_deserves_saying() { + type Set = fn(&mut ImportReport); + let rungs: [(Set, Key); 6] = [ + (|r| r.notes_imported = 0, keys::file::IMPORTED_NOTHING), + ( + |r| r.attachments_missing = 1, + keys::file::IMPORTED_WITHOUT_SOME_ATTACHMENTS, + ), + ( + |r| r.notes_degraded = 1, + keys::file::IMPORTED_FROM_NEWER_VERSION, + ), + (|r| r.folders_created = 1, keys::file::IMPORTED_INTO_FOLDERS), + ( + |r| r.attachments_imported = 1, + keys::file::IMPORTED_WITH_ATTACHMENTS, + ), + (|_| {}, keys::file::IMPORTED), + ]; + for at in 0..rungs.len() { + let mut report = import_report(); + for (set, _) in &rungs[at..] { + set(&mut report); + } + let said = imported(&report, "/tmp/notes.devnotes"); + assert_eq!(said.key, rungs[at].1); + for language in i18n::Language::ALL { + assert!(!said.text(language).contains("{{"), "{at}"); + } + } + } + + #[test] + fn an_export_says_whether_it_is_protected_and_carries_files() { + for (protected, attachments, key) in [ + (true, 2, keys::file::EXPORTED_PROTECTED_WITH_ATTACHMENTS), + (true, 0, keys::file::EXPORTED_PROTECTED), + (false, 2, keys::file::EXPORTED_WITH_ATTACHMENTS), + (false, 0, keys::file::EXPORTED), + ] { + let report = ExportReport { + notes: 2, + attachments, + ..ExportReport::nothing(protected) + }; + let said = exported(&report, &ExportScope::Library, "a/b/notes.devnotes"); + assert_eq!(said.key, key); + assert!(said.text(i18n::Language::En).contains("notes.devnotes")); + assert!(!said.text(i18n::Language::En).contains("a/b")); + } + } + + #[test] + fn an_export_emptied_meanwhile_says_there_was_nothing() { + let nothing = ExportReport::nothing(true); + let space = ExportScope::Space { + space_id: "a".to_owned(), + }; + + assert_eq!(exported(¬hing, &space, "a").key, keys::file::EMPTY_SPACE); + assert_eq!( + exported(¬hing, &ExportScope::Library, "a").key, + keys::file::EMPTY_LIBRARY + ); + } + + #[test] + fn an_empty_space_is_said_before_a_place_is_asked() { + let mut bench = Bench::new(); + let space = crate::notes::bench::space(&bench.backend, "Empty"); + + bench + .transfer + .export(&bench.backend, ExportScope::Space { space_id: space.id }); + bench.run(); + assert_eq!(bench.said(), Some(keys::file::EMPTY_SPACE)); + } + + #[test] + fn a_dialog_cancelled_ends_the_operation_without_a_word() { + let mut bench = Bench::new(); + testing::note(&bench.backend, "Worth exporting"); + bench.dialog = Arc::new(platform::dialog::NoDialog); + + bench.export(); + assert!(!bench.transfer.is_busy()); + bench.import(); + assert!(!bench.transfer.is_busy()); + assert!(bench.status.latest().is_none() && bench.errors.notice().is_none()); + } + + #[test] + fn an_export_that_cannot_be_written_is_said() { + let mut bench = Bench::new(); + testing::note(&bench.backend, "Worth exporting"); + bench.dialog = Arc::new(Fixed(bench.file.join("no-such-folder").join("a.devnotes"))); + std::fs::write(&bench.file, "a file, not a folder").unwrap(); + + bench.export(); + bench.answer(Answer::Plain); + assert!(bench.errors.notice().is_some()); + assert!(!bench.transfer.is_busy()); + } + + /// The same file into another library: its notes are new there. + #[test] + fn an_import_that_brought_notes_is_said_and_shows_them() { + let mut from = Bench::new(); + testing::note(&from.backend, "Worth exporting"); + from.export(); + from.answer(Answer::Plain); + let mut into = Bench::new(); + into.dialog = Arc::new(Fixed(from.file.clone())); + let before = into.revision; + + into.import(); + assert_eq!(into.said(), Some(keys::file::IMPORTED)); + assert_ne!(into.revision, before); + } + + #[test] + fn an_answer_with_nothing_asked_changes_nothing() { + let mut bench = Bench::new(); + + for answer in [Answer::Plain, Answer::Cancel, phrase(PHRASE)] { + bench.answer(answer); + assert!(!bench.transfer.is_busy()); + } + assert!(!bench.file.exists()); + } + + #[test] + fn a_share_of_what_is_gone_is_said() { + let mut bench = Bench::new(); + testing::close_library(&bench.backend); + + bench + .transfer + .share(&bench.backend, vec!["gone".to_owned()]); + bench.run(); + assert!(bench.errors.notice().is_some()); + assert!(!bench.transfer.is_busy()); + } } diff --git a/crates/ui/src/state/window_tests.rs b/crates/ui/src/state/window_tests.rs new file mode 100644 index 000000000..b5c858ef5 --- /dev/null +++ b/crates/ui/src/state/window_tests.rs @@ -0,0 +1,550 @@ +//! What the palette, the menus and the editor's files change, without a window. + +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; + +use engine::notes::kind::NoteKind; +use platform::desktop::Opener; +use platform::dialog::{Fixed, NoDialog}; + +use super::Area; +use super::attachments::Asked as Attach; +use super::held::{Held, held}; +use crate::action::{Action, AppAction, GlobalAction}; +use crate::notes::{Action as Notes, Editing, bench}; +use crate::palette::Asked; +use crate::palette::commands::Command; +use crate::palette::options::Chosen; +use crate::testing; +use crate::titlebar::Action as Menu; + +fn with_a_note() -> (Held, String) { + let (backend, profile) = testing::unlocked(); + let id = testing::note(&backend, "psql").id.clone(); + (held((backend, profile)), id) +} + +// The palette + +fn choose(held: &mut Held, chosen: Chosen) { + held.state.palette.open(&held.backend, false); + held.settle(); + held.apply(Action::Palette(Asked::Choose(chosen))); + assert!(!held.state.palette.is_open(), "chosen, it closes"); +} + +#[test] +fn what_is_chosen_in_the_palette_shows_its_area() { + for (chosen, from, shown) in [ + ( + Chosen::Command(Command::Area(Area::Tools)), + Area::Notes, + Area::Tools, + ), + ( + Chosen::Command(Command::Area(Area::Notes)), + Area::Http, + Area::Notes, + ), + (Chosen::Command(Command::Request), Area::Notes, Area::Http), + (Chosen::Tool("uuid"), Area::Notes, Area::Tools), + (Chosen::Command(Command::Folder), Area::Tools, Area::Notes), + (Chosen::Create("psql".to_owned()), Area::Http, Area::Notes), + ( + Chosen::Command(Command::Preferences), + Area::Http, + Area::Http, + ), + ( + Chosen::Command(Command::Shortcuts), + Area::Tools, + Area::Tools, + ), + ] { + let (mut held, _) = with_a_note(); + held.state.settings.area = from; + choose(&mut held, chosen.clone()); + assert_eq!(held.state.settings.area, shown, "{chosen:?}"); + } +} + +#[test] +fn a_note_chosen_in_the_palette_opens() { + let (mut held, id) = with_a_note(); + choose(&mut held, Chosen::Note(id.clone())); + + assert_eq!(held.state.editor.open_id(), Some(id.as_str())); +} + +#[test] +fn a_kind_chosen_in_the_palette_is_a_draft_of_it() { + for kind in [ + NoteKind::Snippet, + NoteKind::Note, + NoteKind::Checklist, + NoteKind::Calc, + ] { + let (mut held, _) = with_a_note(); + choose(&mut held, Chosen::Command(Command::Create(kind))); + let opened = held.state.editor.opened().unwrap(); + assert!(opened.is_draft()); + assert_eq!(opened.note().unwrap().kind, kind); + } +} + +#[test] +fn what_was_typed_in_the_palette_is_the_title_of_the_note_made_of_it() { + let (mut held, _) = with_a_note(); + choose(&mut held, Chosen::Create("pg_dump".to_owned())); + + assert_eq!( + held.state.editor.opened().unwrap().note().unwrap().title, + "pg_dump" + ); +} + +#[test] +fn a_space_chosen_in_the_palette_is_the_one_shown() { + let (mut held, id) = with_a_note(); + let space = held.note(&id).space_id.clone(); + held.notes(Notes::ChooseSpace(None)); + choose(&mut held, Chosen::Space(space.clone())); + + assert_eq!(held.state.spaces.active_space(), Some(space.as_str())); +} + +#[test] +fn a_request_asked_of_the_palette_is_a_draft_in_its_tab() { + let (mut held, _) = with_a_note(); + choose(&mut held, Chosen::Command(Command::Request)); + + assert!(held.state.http.tabs().active().is_some()); +} + +#[test] +fn a_copy_asked_of_the_palette_closes_it_and_is_said() { + let (mut held, id) = with_a_note(); + held.state.palette.open(&held.backend, false); + held.settle(); + held.apply(Action::Palette(Asked::Copy(id))); + + assert!(!held.state.palette.is_open()); + assert!(held.done().unwrap().contains("psql")); +} + +#[test] +fn a_copy_is_not_said_to_a_person_who_asked_not_to_be_told() { + let (mut held, id) = with_a_note(); + held.state.settings.copy_confirmation = false; + held.notes(Notes::Copy(id)); + + assert_eq!(held.done(), None); + assert_eq!(held.failed(), None); +} + +#[test] +fn a_drawing_cannot_be_copied_as_text_and_says_so() { + let (backend, profile) = testing::unlocked(); + let space = bench::space(&backend, "Home"); + let mut draft = testing::snippet(space.id, "plan".to_owned()); + draft.kind = NoteKind::Drawing; + draft.content = r#"{"version":1,"scene":{"objects":[]}}"#.to_owned(); + let id = engine::db::run_here(backend.engine(), move |engine| { + engine::notes::create_note(engine, draft) + }) + .unwrap() + .id + .clone(); + let mut held = held((backend, profile)); + held.notes(Notes::Copy(id)); + + assert_eq!( + held.state.status.latest().unwrap().1.key, + i18n::keys::notes::DRAWING_NOT_COPIED + ); +} + +// The menus + +#[test] +fn an_export_of_a_space_or_of_a_selection_needs_one() { + let (mut held, _) = with_a_note(); + held.notes(Notes::ChooseSpace(None)); + for menu in [Menu::ExportSpace, Menu::ExportSelection, Menu::CopyMarkdown] { + held.apply(Action::Menu(menu)); + assert!(!held.state.transfer.is_busy()); + assert_eq!(held.done(), None); + } +} + +#[test] +fn the_notes_ticked_are_shared_as_markdown() { + let (mut held, id) = with_a_note(); + held.notes(Notes::Check(id)); + held.apply(Action::Menu(Menu::CopyMarkdown)); + + assert_eq!( + held.state.status.latest().unwrap().1.key, + i18n::keys::file::COPIED + ); +} + +#[test] +fn a_panel_of_the_menus_opens_once_and_closes() { + use crate::titlebar::about_menu::{self, Panel}; + let (mut held, _) = with_a_note(); + held.apply(Action::Menu(Menu::OpenHelp(Panel::Sheet))); + assert!(held.state.dialogs.is_open(about_menu::id())); + held.apply(Action::Menu(Menu::CloseHelp)); + assert!(!held.state.dialogs.is_open(about_menu::id())); + + held.apply(Action::Menu(Menu::OpenLibraries)); + assert!(held.state.dialogs.is_open(crate::titlebar::libraries::id())); + held.apply(Action::Menu(Menu::Libraries( + crate::titlebar::libraries::Ask::Close, + ))); + assert_eq!(held.state.dialogs.top(), None); +} + +/// The draft is dropped, whatever it held. +#[test] +fn the_preferences_discarded_change_nothing() { + use crate::titlebar::preferences::{self, Ask}; + let (mut held, _) = with_a_note(); + let before = held.state.settings.clone(); + held.apply(Action::Menu(Menu::OpenPreferences)); + assert!(held.state.dialogs.is_open(preferences::id())); + + held.apply(Action::Menu(Menu::Preferences(Ask::Discard))); + assert_eq!(held.state.settings, before); + assert!(!held.state.dialogs.is_open(preferences::id())); + assert_eq!(held.state.titlebar_view.previewed(), None); +} + +#[test] +fn a_look_chosen_and_the_rail_put_away_are_kept_for_the_next_launch() { + let (mut held, _) = with_a_note(); + let shown = held.state.settings.rail_shown; + held.apply(Action::App(AppAction::ToggleRail)); + held.apply(Action::App(AppAction::SetRailWidth(300))); + held.apply(Action::App(AppAction::SetHistoryWidth(420))); + held.apply(Action::App(AppAction::SetEditorPanelWidth(600))); + + let settings = &held.state.settings; + assert_eq!(settings.rail_shown, !shown); + assert_eq!( + ( + settings.rail_width, + settings.history_list_width, + settings.editor_panel_width + ), + (300, 420, 600) + ); + let written = crate::services::preferences::Preferences::read( + &held.profile.path().join(engine::layout::PREFERENCES), + ); + assert_eq!( + &crate::services::settings::Settings::read(&written), + settings + ); +} + +#[test] +fn what_is_said_is_dismissed_by_its_number() { + let (mut held, id) = with_a_note(); + held.notes(Notes::Copy(id)); + let (number, _) = held.state.status.latest().unwrap(); + held.apply(Action::App(AppAction::DismissStatus(number + 1))); + assert!(held.done().is_some()); + + held.apply(Action::App(AppAction::DismissStatus(number))); + assert_eq!(held.done(), None); +} + +// From outside the window + +#[derive(Clone)] +struct Clip(String); + +impl platform::clipboard::Clipboard for Clip { + fn html(&self) -> Option { + None + } + + fn text(&self) -> Option { + Some(self.0.clone()) + } +} + +/// Code makes a snippet, prose a Note, and either is written at once. +#[test] +fn a_capture_is_a_note_of_what_the_clipboard_holds() { + for (text, kind) in [ + ( + "SELECT id, title FROM notes WHERE pinned = 1 ORDER BY id;", + NoteKind::Snippet, + ), + ("Penser à rappeler le support demain matin.", NoteKind::Note), + ] { + let (mut held, _) = with_a_note(); + held.state.clipboard = Arc::new(Clip(text.to_owned())); + held.apply(Action::Global(GlobalAction::Capture)); + + let opened = held.state.editor.opened().unwrap(); + assert!(!opened.is_draft()); + assert_eq!( + ( + opened.note().unwrap().kind, + opened.note().unwrap().content.as_str() + ), + (kind, text) + ); + } +} + +#[test] +fn a_capture_of_nothing_opens_nothing() { + let (mut held, _) = with_a_note(); + held.apply(Action::Global(GlobalAction::Capture)); + held.state.clipboard = Arc::new(Clip(" \n".to_owned())); + held.apply(Action::Global(GlobalAction::Capture)); + + assert!(!held.state.editor.is_open()); + assert_eq!(held.shown(), ["psql"]); +} + +#[test] +fn a_capture_before_the_library_is_open_is_left_alone() { + let (backend, profile) = testing::backend(); + let mut held = held((backend, profile)); + held.state.clipboard = Arc::new(Clip("words".to_owned())); + held.apply(Action::Global(GlobalAction::Capture)); + + assert!(!held.state.editor.is_open()); +} + +// The files of a note + +#[derive(Clone, Default)] +struct Opened(Arc>>); + +impl Opener for Opened { + fn open(&self, path: &Path) -> std::io::Result<()> { + self.0.lock().unwrap().push(path.to_owned()); + Ok(()) + } +} + +/// A note open with `plan.txt` attached, and where the test writes. +fn with_a_file() -> (Held, String, tempfile::TempDir) { + let (mut held, id) = with_a_note(); + let directory = tempfile::tempdir().unwrap(); + let file = directory.path().join("plan.txt"); + std::fs::write(&file, "the plan").unwrap(); + held.notes(Notes::OpenNote(id)); + attach(&mut held, Attach::Dropped(vec![file])); + let attached = held.state.attachments.list()[0].id.clone(); + (held, attached, directory) +} + +fn attach(held: &mut Held, asked: Attach) { + held.notes(Notes::Editor(Editing::Attachment(asked))); +} + +#[test] +fn a_file_dropped_on_a_note_is_attached_to_it() { + let (held, _, _directory) = with_a_file(); + let names: Vec<&str> = held + .state + .attachments + .list() + .iter() + .map(|file| file.file_name.as_str()) + .collect(); + + assert_eq!(names, ["plan.txt"]); + assert!(!held.state.attachments.is_busy()); +} + +#[test] +fn a_file_picked_is_attached_and_a_dialog_cancelled_attaches_none() { + let (mut held, _, directory) = with_a_file(); + let other = directory.path().join("other.txt"); + std::fs::write(&other, "other").unwrap(); + held.state.dialog = Arc::new(NoDialog); + attach(&mut held, Attach::Pick); + assert_eq!(held.state.attachments.list().len(), 1); + + held.state.dialog = Arc::new(Fixed(other)); + attach(&mut held, Attach::Pick); + assert_eq!(held.state.attachments.list().len(), 2); +} + +#[test] +fn a_file_that_is_not_there_is_not_attached_and_says_so() { + let (mut held, _, directory) = with_a_file(); + attach( + &mut held, + Attach::Dropped(vec![directory.path().join("gone.txt")]), + ); + + assert_eq!(held.state.attachments.list().len(), 1); + assert!(held.failed().is_some()); +} + +#[test] +fn an_attachment_is_saved_where_the_dialog_says() { + let (mut held, id, directory) = with_a_file(); + let copy = directory.path().join("copy.txt"); + held.state.dialog = Arc::new(Fixed(copy.clone())); + attach(&mut held, Attach::Save(id)); + + assert_eq!(std::fs::read_to_string(copy).unwrap(), "the plan"); + assert!(held.done().is_some()); +} + +#[test] +fn a_save_cancelled_or_of_no_attachment_says_nothing() { + let (mut held, id, directory) = with_a_file(); + held.state.dialog = Arc::new(NoDialog); + attach(&mut held, Attach::Save(id)); + held.state.dialog = Arc::new(Fixed(directory.path().join("copy.txt"))); + attach(&mut held, Attach::Save("gone".to_owned())); + + assert!(!directory.path().join("copy.txt").exists()); + assert_eq!(held.failed(), None); +} + +#[test] +fn a_save_that_cannot_be_written_is_said() { + let (mut held, id, directory) = with_a_file(); + held.state.dialog = Arc::new(Fixed(directory.path().join("plan.txt").join("copy.txt"))); + attach(&mut held, Attach::Save(id)); + + assert!(held.failed().is_some()); +} + +#[test] +fn an_attachment_is_handed_to_the_desktop_and_a_refusal_is_said() { + let (mut held, id, _directory) = with_a_file(); + attach(&mut held, Attach::Open(id.clone())); + assert_eq!( + held.state.errors.notice().unwrap().key, + i18n::keys::errors::ATTACHMENT_OPEN_FAILED + ); + + let opened = Opened::default(); + held.state.opener = Arc::new(opened.clone()); + attach(&mut held, Attach::Open(id)); + let paths = opened.0.lock().unwrap(); + assert_eq!(paths.len(), 1); + assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "the plan"); +} + +#[test] +fn a_picture_attached_is_shown_at_once_until_it_is_removed() { + let (mut held, _, directory) = with_a_file(); + let picture = directory.path().join("plan.png"); + image::RgbaImage::from_pixel(4, 4, image::Rgba([240, 160, 40, 255])) + .save(&picture) + .unwrap(); + attach(&mut held, Attach::Dropped(vec![picture])); + let mut listed = held.state.attachments.list().iter(); + let id = listed + .find(|file| file.file_name == "plan.png") + .unwrap() + .id + .clone(); + assert_eq!(held.state.attachments.preview_id(), Some(id.as_str())); + attach(&mut held, Attach::Zoom(true)); + assert_eq!(held.state.attachments.zoomed().unwrap().0, "plan.png"); + + attach(&mut held, Attach::Remove(id)); + assert_eq!(held.state.attachments.list().len(), 1); + assert_eq!(held.state.attachments.preview_id(), None); + assert!(held.state.attachments.zoomed().is_none()); +} + +/// Anything else is opened, not shown. +#[test] +fn a_text_has_no_preview() { + let (mut held, id, _directory) = with_a_file(); + attach(&mut held, Attach::TogglePreview(id)); + + assert_eq!(held.state.attachments.preview_id(), None); +} + +#[test] +fn what_is_refused_about_a_file_is_said() { + let asked: [fn(String) -> Attach; 3] = [Attach::Open, Attach::Save, Attach::Remove]; + for asked in asked { + let (mut held, id, directory) = with_a_file(); + held.state.dialog = Arc::new(Fixed(directory.path().join("copy.txt"))); + held.close_library(); + attach(&mut held, asked(id.clone())); + assert!(held.failed().is_some(), "{:?}", asked(id)); + } +} + +// The editor + +#[test] +fn a_note_that_cannot_be_read_closes_the_editor_and_says_so() { + let (mut held, _) = with_a_note(); + held.notes(Notes::OpenNote("gone".to_owned())); + + assert!(!held.state.editor.is_open()); + assert!(held.failed().is_some()); +} + +/// What was typed stays on screen: nothing says it is written. +#[test] +fn a_draft_that_cannot_be_written_says_so_and_stays_a_draft() { + let (mut held, _) = with_a_note(); + held.notes(Notes::NewNote(Some(NoteKind::Snippet))); + held.close_library(); + let session = held.state.editor.opened().unwrap().session; + let edit = super::editor::Edit { + title: Some("typed".to_owned()), + ..Default::default() + }; + held.notes(Notes::Editor(Editing::Save { session, edit })); + + assert!(held.failed().is_some()); + assert!(held.state.editor.opened().unwrap().is_draft()); +} + +#[test] +fn an_edit_of_a_note_closed_since_or_of_nothing_is_left_alone() { + let (mut held, id) = with_a_note(); + held.notes(Notes::OpenNote(id.clone())); + let session = held.state.editor.opened().unwrap().session; + let save = + |held: &mut Held, session, edit| held.notes(Notes::Editor(Editing::Save { session, edit })); + + let launched = held.backend.launched(); + save(&mut held, session, super::editor::Edit::default()); + assert_eq!( + held.backend.launched(), + launched, + "nothing left, nothing asked" + ); + let edit = super::editor::Edit { + title: Some("late".to_owned()), + ..Default::default() + }; + save(&mut held, session + 7, edit); + assert_eq!(held.note(&id).title, "psql"); +} + +#[test] +fn a_step_past_the_first_or_the_last_card_stays_where_it_is() { + let (mut held, id) = with_a_note(); + held.notes(Notes::Editor(Editing::Step(1))); + assert!(!held.state.editor.is_open()); + held.notes(Notes::OpenNote(id.clone())); + for by in [1, -1] { + held.notes(Notes::Editor(Editing::Step(by))); + assert_eq!(held.state.editor.open_id(), Some(id.as_str())); + } +} From 509bfc5511039588bcf01bfd4d7473a25865c953 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:09:04 +0100 Subject: [PATCH 71/95] Code editor: a double click selects the word under the pointer (#1807) Co-authored-by: Claude Opus 5.5 --- crates/ui/src/widgets/editor/geometry.rs | 10 +++ crates/ui/src/widgets/editor/input.rs | 10 +-- crates/ui/src/widgets/editor/tests.rs | 77 ++++++++++++++++++++++++ 3 files changed, 93 insertions(+), 4 deletions(-) diff --git a/crates/ui/src/widgets/editor/geometry.rs b/crates/ui/src/widgets/editor/geometry.rs index 6959a733f..f20f46fa2 100644 --- a/crates/ui/src/widgets/editor/geometry.rs +++ b/crates/ui/src/widgets/editor/geometry.rs @@ -271,6 +271,16 @@ pub(crate) fn caret_rect( local.translate(origin(lines, line, frame).to_vec2()) } +/// The character under `pos`: the caret goes to the nearer side of it. +pub(crate) fn char_at(ui: &Ui, buffer: &Buffer, lines: &Lines, pos: Pos2, frame: &Frame) -> usize { + let line = lines.line_at(pos.y - frame.top); + let galley = galley(ui, buffer, line, frame, None); + let local = pos - origin(lines, line, frame); + let cursor = galley.cursor_from_pos(local); + let before = local.x < galley.pos_from_cursor(cursor).center().x; + buffer.line_start(line) + cursor.index.0.saturating_sub(usize::from(before)) +} + /// The position under `pos`, on screen. pub(crate) fn hit(ui: &Ui, buffer: &Buffer, lines: &Lines, pos: Pos2, frame: &Frame) -> usize { if pos.y < frame.top { diff --git a/crates/ui/src/widgets/editor/input.rs b/crates/ui/src/widgets/editor/input.rs index 5bab65430..c63adc333 100644 --- a/crates/ui/src/widgets/editor/input.rs +++ b/crates/ui/src/widgets/editor/input.rs @@ -36,11 +36,13 @@ pub(crate) fn pointer(ui: &Ui, response: &Response, editor: &mut Editor, frame: head: end, }); } else if response.double_clicked() { - let start = editor.buffer.step(at, Direction::Backward, Unit::Word); - let end = editor.buffer.step(start, Direction::Forward, Unit::Word); + let under = geometry::char_at(ui, &editor.buffer, &editor.lines, pos, frame); + let line = editor.buffer.line_of(under); + let start = editor.buffer.line_start(line); + let word = text::word_around(&editor.buffer.line(line), under - start); editor.buffer.select(Selection { - anchor: start, - head: end.max(at), + anchor: start + word.start, + head: start + word.end, }); } else if ui.input(|input| input.pointer.primary_pressed()) && response.is_pointer_button_down_on() diff --git a/crates/ui/src/widgets/editor/tests.rs b/crates/ui/src/widgets/editor/tests.rs index 3fe3210c4..5846c4c12 100644 --- a/crates/ui/src/widgets/editor/tests.rs +++ b/crates/ui/src/widgets/editor/tests.rs @@ -331,3 +331,80 @@ fn a_wrapped_line_selected_whole_is_lit_on_each_of_its_rows() { assert!((rect.center().y - row.rect().center().y).abs() < 0.5); } } + +/// Where the character at `at` of a line is drawn, `part` of its width along. +fn point(harness: &Harness<'_, Screen>, line: &str, at: usize, part: f32) -> egui::Pos2 { + let found = harness + .output() + .shapes + .iter() + .find_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) if text.galley.text() == line => { + let side = |at| text.galley.pos_from_cursor(CCursor::new(at)).center(); + let across = side(at).lerp(side(at + 1), part); + Some(text.pos + across.to_vec2()) + } + _ => None, + }); + found.unwrap_or_else(|| panic!("{line:?} is painted")) +} + +/// The bench gives each release a frame of its own, a quarter of a second: egui's delay between +/// two clicks is stretched to count them as one gesture. +fn clicks(harness: &mut Harness<'_, Screen>, at: egui::Pos2, count: usize) { + harness + .ctx + .options_mut(|options| options.input_options.max_double_click_delay = 0.7); + // A second of frames first: no click before this gesture counts in it. + for _ in 0..4 { + harness.step(); + } + harness.event(Event::PointerMoved(at)); + harness.step(); + for _ in 0..count { + for pressed in [true, false] { + harness.event(Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed, + modifiers: Modifiers::NONE, + }); + } + } + harness.run(); +} + +#[test] +fn a_double_click_takes_the_word_under_the_pointer() { + for (at, part, word) in [ + (5, 0.5, "beta"), + (4, 0.2, "beta"), + (4, 0.8, "beta"), + (7, 0.8, "beta"), + (0, 0.2, "foo"), + (3, 0.5, " "), + (8, 0.5, "+="), + (10, 0.8, "1"), + ] { + let mut harness = screen("line\nfoo beta+=1"); + harness.run(); + let pointed = point(&harness, "foo beta+=1", at, part); + clicks(&mut harness, pointed, 2); + assert_eq!( + harness.state().editor.buffer.selected_text(), + word, + "{at} {part}" + ); + } +} + +#[test] +fn a_triple_click_takes_the_line() { + for (line, taken) in [("one", "one\n"), ("two", "two")] { + let mut harness = screen("one\ntwo"); + harness.run(); + let pointed = point(&harness, line, 1, 0.5); + clicks(&mut harness, pointed, 3); + assert_eq!(harness.state().editor.buffer.selected_text(), taken); + } +} From 5456eb727342da27d39c141806c436e9f7f8bf9f Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:09:17 +0100 Subject: [PATCH 72/95] Code editor: Ctrl+/ keeps the caret on its text (#1810) Co-authored-by: Claude Opus 5.5 --- crates/text/src/buffer.rs | 14 +++++++-- crates/text/src/buffer/tests.rs | 53 ++++++++++++++++++++++++++------- 2 files changed, 55 insertions(+), 12 deletions(-) diff --git a/crates/text/src/buffer.rs b/crates/text/src/buffer.rs index ed38e678c..88befdc42 100644 --- a/crates/text/src/buffer.rs +++ b/crates/text/src/buffer.rs @@ -271,8 +271,7 @@ impl Buffer { let end = span.start + grown - usize::from(body.len() < text.len()); let selection = if range.is_empty() { let column = self.selection.head - self.line_start(first); - let line_now = changed.first().map_or(0, |line| line.chars().count()); - Selection::caret(span.start + column.min(line_now)) + Selection::caret(span.start + followed(column, lines[0], &changed[0])) } else { Selection { anchor: span.start, @@ -537,5 +536,16 @@ impl Buffer { } } +/// Where `column` of `before` is in `after`, the same line with its indentation followed by +/// more or by less. +fn followed(column: usize, before: &str, after: &str) -> usize { + let indent = before.chars().take_while(|c| c.is_whitespace()).count(); + if column <= indent { + return column; + } + let (was, now) = (before.chars().count(), after.chars().count()); + (column + now).saturating_sub(was).max(indent) +} + #[cfg(test)] mod tests; diff --git a/crates/text/src/buffer/tests.rs b/crates/text/src/buffer/tests.rs index 7c55cba5e..fc87253f4 100644 --- a/crates/text/src/buffer/tests.rs +++ b/crates/text/src/buffer/tests.rs @@ -456,16 +456,49 @@ fn a_comment_comes_off_only_when_every_line_has_it() { } #[test] -fn a_comment_at_a_caret_takes_its_line_and_keeps_its_column() { - assert_eq!( - commented("a\nbc\nd", 3, 3), - ("a\n// bc\nd".to_string(), (3, 3)) - ); - assert_eq!( - commented("a\n// bc\nd", 7, 7), - ("a\nbc\nd".to_string(), (4, 4)) - ); - assert_eq!(commented("// a", 4, 4), ("a".to_string(), (1, 1))); +fn a_comment_at_a_caret_takes_its_line_and_the_caret_follows_its_text() { + for (before, at, after, then) in [ + ( + "a +bc +d", + 3, + "a +// bc +d", + 6, + ), + ( + "a +// bc +d", + 6, + "a +bc +d", + 3, + ), + ( + "a +// bc +d", + 7, + "a +bc +d", + 4, + ), + ("// a", 4, "a", 1), + ("//a", 3, "a", 1), + (" ab", 2, " // ab", 2), + (" ab", 1, " // ab", 1), + (" ab", 4, " // ab", 7), + (" // ab", 4, " ab", 2), + (" ", 2, " ", 2), + ] { + let expected = (after.to_string(), (then, then)); + assert_eq!(commented(before, at, at), expected, "{before:?} at {at}"); + } } #[test] From 0d490af072a7b339c4bba2462fbcb023425c9b55 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:09:32 +0100 Subject: [PATCH 73/95] Interface: unit tests rewritten for the gate, preferences and palette (#1808) Co-authored-by: Claude Opus 5.5 --- crates/ui/src/app.rs | 2 + crates/ui/src/app/preferences_tests.rs | 318 +++++++++++++++++++++++++ crates/ui/src/app/prompt_tests.rs | 38 +++ crates/ui/src/app/titlebar_tests.rs | 4 +- crates/ui/src/gate/tests.rs | 142 +++++++++-- crates/ui/src/palette/list_tests.rs | 273 +++++++++++++++++++++ crates/ui/src/palette/mod.rs | 2 + 7 files changed, 763 insertions(+), 16 deletions(-) create mode 100644 crates/ui/src/app/preferences_tests.rs create mode 100644 crates/ui/src/palette/list_tests.rs diff --git a/crates/ui/src/app.rs b/crates/ui/src/app.rs index be911dd42..58bc68e17 100644 --- a/crates/ui/src/app.rs +++ b/crates/ui/src/app.rs @@ -503,6 +503,8 @@ mod global_key_tests; #[cfg(test)] mod palette_copy_tests; +#[cfg(test)] +mod preferences_tests; #[cfg(test)] mod tests { diff --git a/crates/ui/src/app/preferences_tests.rs b/crates/ui/src/app/preferences_tests.rs new file mode 100644 index 000000000..ba4b1285a --- /dev/null +++ b/crates/ui/src/app/preferences_tests.rs @@ -0,0 +1,318 @@ +//! The preferences over the whole window: what waits for « Apply », what is shown at once, and +//! the pages that ask something of the core. + +use egui::{Event, Key, Modifiers}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; + +use super::DevNotesApp; +use super::tests::{click as click_at, count, open_library, present, settle, type_into}; +use crate::services::settings::Settings; +use crate::testing::PASSPHRASE; + +const NEXT: &str = "another horse battery staple"; + +fn preferences(directory: &std::path::Path) -> Harness<'static, DevNotesApp> { + let mut harness = open_library(directory); + open(&mut harness); + harness +} + +fn open(harness: &mut Harness<'_, DevNotesApp>) { + click(harness, "file-menu"); + click(harness, "file-preferences"); +} + +fn page(directory: &std::path::Path, id: &str) -> Harness<'static, DevNotesApp> { + let mut harness = preferences(directory); + click(&mut harness, &format!("settings-page-{id}")); + harness +} + +/// Brought in view first: a click below the page is one on what is behind it. +fn click(harness: &mut Harness<'_, DevNotesApp>, author_id: &str) { + harness + .get_by(|node| node.author_id() == Some(author_id)) + .scroll_to_me(); + settle(harness); + click_at(harness, author_id); +} + +fn settings<'a>(harness: &'a Harness<'_, DevNotesApp>) -> &'a Settings { + &harness.state().state().settings +} + +fn said(harness: &Harness<'_, DevNotesApp>, author_id: &str) -> String { + let node = harness.get_by(|node| node.author_id() == Some(author_id)); + let node = node.accesskit_node(); + node.value().or_else(|| node.label()).unwrap_or_default() +} + +// What waits + +#[test] +fn what_is_changed_waits_for_apply() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = preferences(directory.path()); + let before = settings(&harness).clone(); + click(&mut harness, "setting-code-wrap"); + click(&mut harness, "setting-copy-confirmation"); + assert_eq!(settings(&harness), &before); + + click(&mut harness, "settings-apply"); + assert!(settings(&harness).code_wrap && !settings(&harness).copy_confirmation); + assert!(present(&harness, "settings-dialog"), "it stays open"); + harness.key_press(Key::Escape); + settle(&mut harness); + assert!( + !present(&harness, "settings-dialog"), + "nothing is left to ask about" + ); +} + +#[test] +fn applied_and_closed_they_are_kept_for_the_next_launch() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = preferences(directory.path()); + click(&mut harness, "setting-code-wrap"); + click(&mut harness, "settings-close"); + assert!(!present(&harness, "settings-dialog")); + + let written = crate::services::preferences::Preferences::read( + &directory.path().join(engine::layout::PREFERENCES), + ); + assert!(Settings::read(&written).code_wrap); +} + +#[test] +fn cancelled_they_change_nothing() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = preferences(directory.path()); + let before = settings(&harness).clone(); + click(&mut harness, "setting-code-wrap"); + click(&mut harness, "settings-cancel"); + if present(&harness, "settings-discard") { + click(&mut harness, "settings-discard"); + } + + assert!(!present(&harness, "settings-dialog")); + assert_eq!(settings(&harness), &before); + open(&mut harness); + assert!(!present(&harness, "settings-unapplied")); +} + +/// Escape makes no click: with work in hand it asks before it drops it. +#[test] +fn escape_asks_before_it_drops_what_was_changed() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = preferences(directory.path()); + click(&mut harness, "setting-code-wrap"); + harness.key_press(Key::Escape); + settle(&mut harness); + assert!(present(&harness, "settings-dialog") && present(&harness, "settings-discard")); + + click(&mut harness, "settings-discard"); + assert!(!present(&harness, "settings-dialog")); + assert!(!settings(&harness).code_wrap); +} + +#[test] +fn escape_closes_them_with_nothing_changed() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = preferences(directory.path()); + harness.key_press(Key::Escape); + settle(&mut harness); + + assert!(!present(&harness, "settings-dialog")); +} + +#[test] +fn a_version_skipped_can_be_told_again() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = open_library(directory.path()); + "9.9.9".clone_into(&mut harness.state_mut().state.settings.skipped_update); + open(&mut harness); + assert!(said(&harness, "setting-skipped-update").contains("9.9.9")); + + click(&mut harness, "setting-forget-skipped"); + click(&mut harness, "settings-close"); + assert_eq!(settings(&harness).skipped_update, ""); +} + +// The keys + +fn listening(directory: &std::path::Path, action: &str) -> Harness<'static, DevNotesApp> { + let mut harness = page(directory, "shortcuts"); + click(&mut harness, &format!("shortcut-field-{action}")); + harness +} + +fn press(harness: &mut Harness<'_, DevNotesApp>, modifiers: Modifiers, key: Key) { + harness.event(Event::Key { + key, + physical_key: Some(key), + pressed: true, + repeat: false, + modifiers, + }); + settle(harness); +} + +#[test] +fn a_key_pressed_in_its_field_is_the_action_s_once_applied() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = listening(directory.path(), "canvas.pin"); + press(&mut harness, Modifiers::COMMAND, Key::J); + click(&mut harness, "settings-apply"); + + let pin = crate::services::shortcuts::ACTIONS[9]; + assert_eq!(settings(&harness).bindings.of(pin), "Ctrl+J"); + click(&mut harness, "shortcut-reset-canvas.pin"); + click(&mut harness, "settings-apply"); + assert!(settings(&harness).bindings.is_default(pin)); +} + +#[test] +fn a_key_another_action_has_is_refused_and_says_so() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = listening(directory.path(), "canvas.pin"); + press(&mut harness, Modifiers::NONE, Key::C); + + assert!(present(&harness, "shortcut-error-canvas.pin")); + assert!(!present(&harness, "settings-unapplied")); +} + +#[test] +fn a_key_the_navigation_keeps_is_refused_and_says_so() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = listening(directory.path(), "canvas.pin"); + press(&mut harness, Modifiers::NONE, Key::ArrowDown); + + assert!(present(&harness, "shortcut-error-canvas.pin")); +} + +#[test] +fn a_global_key_without_a_modifier_is_refused_and_says_so() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = listening(directory.path(), "palette"); + press(&mut harness, Modifiers::NONE, Key::J); + + assert!(present(&harness, "shortcut-error-palette")); +} + +/// A file edited by hand: no field could have refused it. +#[test] +fn two_actions_on_one_key_are_said() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = open_library(directory.path()); + let pin = crate::services::shortcuts::ACTIONS[9]; + harness + .state_mut() + .state + .settings + .bindings + .set(pin, "C".to_owned()); + open(&mut harness); + click(&mut harness, "settings-page-shortcuts"); + + assert!(present(&harness, "shortcut-conflict")); +} + +// The passphrase + +fn change(directory: &std::path::Path) -> Harness<'static, DevNotesApp> { + let mut harness = page(directory, "security"); + click(&mut harness, "setting-change-passphrase"); + harness +} + +fn fields(harness: &mut Harness<'_, DevNotesApp>, current: &str, next: &str, confirmation: &str) { + for (id, words) in [ + ("change-passphrase-current", current), + ("change-passphrase-next", next), + ("change-passphrase-confirmation", confirmation), + ] { + type_into(harness, id, words); + } +} + +#[test] +fn the_passphrase_is_changed_and_the_dialog_closes() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = change(directory.path()); + fields(&mut harness, PASSPHRASE, NEXT, NEXT); + click(&mut harness, "change-passphrase-submit"); + + assert!(!present(&harness, "change-passphrase-current")); + assert!(harness.state().state().status.latest().is_some()); + assert!(harness.state().state().errors.notice().is_none()); +} + +#[test] +fn a_wrong_passphrase_is_refused_there_and_typing_withdraws_it() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = change(directory.path()); + fields(&mut harness, "not the phrase", NEXT, NEXT); + click(&mut harness, "change-passphrase-submit"); + assert!(present(&harness, "change-passphrase-current")); + assert!(harness.state().state().security.refused()); + + type_into(&mut harness, "change-passphrase-current", "x"); + assert!(!harness.state().state().security.refused()); +} + +#[test] +fn a_new_phrase_too_short_or_mistyped_cannot_be_sent() { + for (next, confirmation) in [("too short", "too short"), (NEXT, "another horse battery")] { + let directory = tempfile::tempdir().unwrap(); + let mut harness = change(directory.path()); + fields(&mut harness, PASSPHRASE, next, confirmation); + click(&mut harness, "change-passphrase-submit"); + assert!(present(&harness, "change-passphrase-current"), "{next}"); + assert!(!harness.state().state().security.is_changing()); + assert!(harness.state().state().status.latest().is_none()); + } +} + +// The copies + +#[test] +fn a_library_just_made_has_no_copy_yet_or_lists_them() { + let directory = tempfile::tempdir().unwrap(); + let harness = page(directory.path(), "backups"); + let copies = harness.state().state().backups.copies().len(); + + assert_eq!(present(&harness, "backup-empty"), copies == 0); + assert_eq!(count(&harness, "backup-row"), copies); +} + +// The variables + +#[test] +fn a_variable_added_is_proposed_once_applied() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = page(directory.path(), "variables"); + click(&mut harness, "variable-add"); + assert_eq!(count(&harness, "variable-row"), 1); + type_into(&mut harness, "variable-name", "host"); + type_into(&mut harness, "variable-value", "prod"); + click(&mut harness, "settings-apply"); + + let kept = harness.state().state().security.variables().unwrap(); + assert_eq!( + (kept[0].name.as_str(), kept[0].value.as_str()), + ("host", "prod") + ); + click(&mut harness, "variable-remove"); + assert_eq!(count(&harness, "variable-row"), 0); + click(&mut harness, "settings-apply"); + assert!( + harness + .state() + .state() + .security + .variables() + .unwrap() + .is_empty() + ); +} diff --git a/crates/ui/src/app/prompt_tests.rs b/crates/ui/src/app/prompt_tests.rs index 2bda35701..606716dfe 100644 --- a/crates/ui/src/app/prompt_tests.rs +++ b/crates/ui/src/app/prompt_tests.rs @@ -57,3 +57,41 @@ fn a_phrase_typed_does_not_outlive_an_export_in_the_clear() { export(&mut harness); assert!(!can_submit(&harness), "the fields start empty"); } + +/// Nothing is written with a phrase typed two ways, and the prompt says why. +#[test] +fn two_phrases_that_differ_cannot_be_sent() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = asking(directory.path()); + type_into(&mut harness, "passphrase-prompt-confirmation", "x"); + + assert!(!can_submit(&harness)); + assert!(present(&harness, "passphrase-prompt-problem")); +} + +#[test] +fn escape_cancels_the_prompt_and_writes_nothing() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = asking(directory.path()); + harness.key_press(egui::Key::Escape); + settle(&mut harness); + + assert!(!present(&harness, "passphrase-prompt")); + assert!(!directory.path().join("library.devnotes").exists()); +} + +#[test] +fn an_export_is_written_under_the_phrase_and_said() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = asking(directory.path()); + click(&mut harness, "passphrase-prompt-submit"); + settle(&mut harness); + + let said = harness.state().state.status.latest().unwrap().1.key; + assert!( + said.path().starts_with("file.exportedProtected"), + "{}", + said.path() + ); + assert!(directory.path().join("library.devnotes").exists()); +} diff --git a/crates/ui/src/app/titlebar_tests.rs b/crates/ui/src/app/titlebar_tests.rs index 2ebee84c7..fdd67b1e8 100644 --- a/crates/ui/src/app/titlebar_tests.rs +++ b/crates/ui/src/app/titlebar_tests.rs @@ -14,7 +14,9 @@ const SIZE: egui::Vec2 = egui::vec2(1100.0, 720.0); const EMPTY: Pos2 = pos2(700.0, 19.0); fn window(directory: &std::path::Path) -> Harness<'static, DevNotesApp> { - let startup = startup(directory); + let mut startup = startup(directory); + // Its controls are named in the language on screen, the machine's otherwise. + startup.preferences.set("devnotes.locale", "en"); // A frame a sixtieth of a second, as on screen: two clicks a step apart are one double click. let mut harness = Harness::builder() .with_size(SIZE) diff --git a/crates/ui/src/gate/tests.rs b/crates/ui/src/gate/tests.rs index 2c0b75099..0b8099a3b 100644 --- a/crates/ui/src/gate/tests.rs +++ b/crates/ui/src/gate/tests.rs @@ -133,26 +133,37 @@ fn the_pointer_over_the_phrase_is_the_i_beam() { ); } -#[test] -fn an_unlock_takes_any_length_and_says_when_the_phrase_is_wrong() { +/// A library locked on the profile, and the gate over it. +fn locked() -> Harness<'static, Screen> { let profile = testing::locked(); let backend = testing::backend_on(profile.path()); let mut harness = screen(backend, profile); harness.run(); + harness +} + +fn unlock(harness: &mut Harness<'_, Screen>, phrase: &str) { + type_into(harness, "vault-passphrase", phrase); + harness.key_press(Key::Enter); + harness.run(); + settle(harness); +} +/// The floor is for a phrase being chosen. +#[test] +fn an_unlock_takes_a_phrase_of_any_length() { + let mut harness = locked(); assert!(!present(&harness, "vault-confirmation")); - assert!(present(&harness, "vault-forgotten")); type_into(&mut harness, "vault-passphrase", "short"); - assert!( - !node(&harness, "vault-submit") - .accesskit_node() - .is_disabled(), - "no floor to unlock" - ); - harness.key_press(Key::Enter); - harness.run(); - settle(&mut harness); + let submit = node(&harness, "vault-submit"); + assert!(!submit.accesskit_node().is_disabled()); +} + +#[test] +fn a_wrong_phrase_is_said_and_the_right_one_opens() { + let mut harness = locked(); + unlock(&mut harness, "short"); assert!(harness.state().gate.refused); let problem = node(&harness, "vault-problem").accesskit_node(); let said = problem @@ -161,11 +172,112 @@ fn an_unlock_takes_any_length_and_says_when_the_phrase_is_wrong() { .unwrap_or_default(); assert!(said.contains("passphrase"), "{said:?}"); - type_into(&mut harness, "vault-passphrase", testing::PASSPHRASE); - harness.key_press(Key::Enter); + unlock(&mut harness, testing::PASSPHRASE); + assert!(harness.state().gate.is_open()); +} + +#[test] +fn the_phrase_is_shown_while_it_is_asked_and_hidden_again() { + let mut harness = locked(); + type_into(&mut harness, "vault-passphrase", "short"); + let shown = |harness: &Harness<'_, Screen>| { + testing::painted(harness) + .iter() + .any(|text| text.contains("short")) + }; + assert!(!shown(&harness)); + + node(&harness, "vault-reveal").click(); + harness.run(); + assert!(shown(&harness)); + node(&harness, "vault-reveal").click(); + harness.run(); + assert!(!shown(&harness)); +} + +/// The library's folder, as the core made it. +fn library_files(profile: &std::path::Path) -> Vec { + let mut folders = vec![profile.to_owned()]; + let mut files = Vec::new(); + while let Some(folder) = folders.pop() { + for entry in std::fs::read_dir(folder).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + folders.push(path); + } else { + files.push(path); + } + } + } + files +} + +fn file_named(profile: &std::path::Path, ending: &str) -> std::path::PathBuf { + let files = library_files(profile); + let found = files + .iter() + .find(|file| file.to_string_lossy().ends_with(ending)); + found + .unwrap_or_else(|| panic!("no {ending} in {files:?}")) + .clone() +} + +/// Nothing can be typed that would open it: it is set aside, and a new one begun. +#[test] +fn a_library_whose_key_is_missing_is_set_aside() { + let profile = testing::locked(); + std::fs::remove_file(file_named(profile.path(), "vault.json")).unwrap(); + let backend = testing::backend_on(profile.path()); + let mut harness = screen(backend, profile); + settle(&mut harness); + assert!(present(&harness, "vault-key-missing")); + assert!(!present(&harness, "vault-passphrase")); + + node(&harness, "vault-set-aside").click(); + settle(&mut harness); + assert!( + present(&harness, "vault-confirmation"), + "a new library begins" + ); + assert!( + harness.state().status.latest().is_some(), + "where the old one is" + ); + assert!(harness.state().errors.notice().is_none()); +} + +#[test] +fn a_damaged_library_is_set_aside_and_its_phrase_opens_a_new_one() { + let profile = testing::locked(); + let file = file_named(profile.path(), "devnotes.sqlite3"); + let mut bytes = std::fs::read(&file).unwrap(); + for byte in bytes.iter_mut().skip(100) { + *byte = 0x5a; + } + std::fs::write(&file, bytes).unwrap(); + let backend = testing::backend_on(profile.path()); + let mut harness = screen(backend, profile); + settle(&mut harness); + unlock(&mut harness, testing::PASSPHRASE); + assert!(present(&harness, "vault-damaged")); + assert!(!present(&harness, "vault-passphrase")); harness.run(); + + node(&harness, "vault-set-aside").click(); settle(&mut harness); - assert!(harness.state().gate.is_open()); + assert!(harness.state().status.latest().is_some(), "where it is"); + unlock(&mut harness, testing::PASSPHRASE); + assert!( + harness.state().gate.is_open(), + "its phrase opens the new one" + ); +} + +#[test] +fn one_library_offers_no_other_to_open() { + let harness = locked(); + + assert!(!present(&harness, "vault-library-switch")); } #[test] diff --git a/crates/ui/src/palette/list_tests.rs b/crates/ui/src/palette/list_tests.rs new file mode 100644 index 000000000..e6f0f3320 --- /dev/null +++ b/crates/ui/src/palette/list_tests.rs @@ -0,0 +1,273 @@ +//! What the palette lists, narrows to and runs. + +use egui::{Key, Modifiers}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use engine::http::model::{HttpMethod, RequestKind}; +use engine::notes::kind::NoteKind; + +use super::commands::{COMMANDS, Command}; +use crate::notes::bench::{Bench, area, settle, space, until}; +use crate::services::shortcuts::Bindings; +use crate::state::Area; +use crate::testing; + +/// A library of two spaces, a note tagged `db` and a request. +fn palette() -> Harness<'static, Bench> { + let (backend, profile) = testing::unlocked(); + let home = space(&backend, "Home"); + space(&backend, "Work"); + let mut draft = testing::snippet(home.id, "psql prod".to_owned()); + draft.tags = vec!["db".to_owned()]; + engine::db::run_here(backend.engine(), move |engine| { + engine::notes::create_note(engine, draft) + }) + .unwrap(); + let api = crate::http::tests::collection(&backend, "API"); + let socket = (RequestKind::Websocket, HttpMethod::Get); + crate::http::tests::request(&backend, (&api, None), "Events", socket); + let mut harness = area(backend, profile); + harness.key_press_modifiers(Modifiers::COMMAND | Modifiers::ALT, Key::P); + settle(&mut harness); + harness +} + +fn options(harness: &Harness<'_, Bench>) -> Vec { + harness + .query_all_by(|node| node.author_id() == Some("palette-option")) + .map(|node| node.accesskit_node().label().unwrap_or_default()) + .collect() +} + +fn typed(harness: &mut Harness<'_, Bench>, words: &str) { + harness + .get_by(|node| node.author_id() == Some("palette-input")) + .type_text(words); + for _ in 0..20 { + harness.step(); + } + settle(harness); +} + +fn press(harness: &mut Harness<'_, Bench>, key: Key) { + harness.key_press(key); + settle(harness); +} + +fn lists(harness: &mut Harness<'_, Bench>, what: &str, holds: impl Fn(&[String]) -> bool) { + until(harness, what, |harness| holds(&options(harness))); +} + +fn chips(harness: &Harness<'_, Bench>) -> usize { + harness.state().state.palette.chips().len() +} + +// What it offers + +#[test] +fn a_space_is_found_by_its_name_and_shown() { + let mut harness = palette(); + typed(&mut harness, "Work"); + lists(&mut harness, "the space is found", |names| { + names.iter().any(|name| name == "Work") + }); + let at = options(&harness) + .iter() + .position(|name| name == "Work") + .unwrap(); + for _ in 0..at { + press(&mut harness, Key::ArrowDown); + } + press(&mut harness, Key::Enter); + + let state = &harness.state().state; + let shown = state.spaces.active_space().unwrap(); + assert_eq!( + state + .spaces + .spaces() + .iter() + .find(|space| space.id == shown) + .unwrap() + .name, + "Work" + ); +} + +#[test] +fn what_is_found_nowhere_is_offered_as_a_note() { + let mut harness = palette(); + typed(&mut harness, "pg_dump nightly"); + until(&mut harness, "the creation is offered", |harness| { + harness + .query_by(|node| node.author_id() == Some("palette-create")) + .is_some() + }); + press(&mut harness, Key::Enter); + + let opened = harness.state().state.editor.opened().unwrap(); + assert_eq!(opened.note().unwrap().title, "pg_dump nightly"); +} + +#[test] +fn what_matches_no_chip_and_no_command_says_so() { + for words in ["@zzzz", "#zzzz", "> zzzz"] { + let mut harness = palette(); + typed(&mut harness, words); + lists(&mut harness, words, <[String]>::is_empty); + assert!( + harness + .query_by(|node| node.author_id() == Some("palette-empty")) + .is_some(), + "{words}" + ); + } +} + +// The chips + +#[test] +fn a_tag_narrows_to_the_notes_that_carry_it() { + let mut harness = palette(); + typed(&mut harness, "#d"); + lists(&mut harness, "the tag is offered", |names| names.len() == 1); + press(&mut harness, Key::Tab); + assert_eq!(chips(&harness), 1); + + lists(&mut harness, "its note alone", |names| { + names == ["psql prod"] + }); +} + +#[test] +fn a_space_narrows_to_its_notes() { + let mut harness = palette(); + typed(&mut harness, "@Work"); + lists(&mut harness, "the space is offered", |names| { + names.len() == 1 + }); + press(&mut harness, Key::Enter); + + assert_eq!(chips(&harness), 1); + lists(&mut harness, "no note there", |names| { + !names.iter().any(|name| name == "psql prod") + }); +} + +#[test] +fn each_scope_lists_its_own() { + for (scope, holds) in [ + ("@notes", "psql prod"), + ("@requests", "Events"), + ("@spaces", "Work"), + ] { + let mut harness = palette(); + typed(&mut harness, scope); + press(&mut harness, Key::Tab); + assert_eq!(chips(&harness), 1, "{scope}"); + lists(&mut harness, scope, |names| { + names.iter().any(|name| name == holds) + }); + } +} + +#[test] +fn a_chip_is_taken_off_by_the_key_before_it_or_by_its_cross() { + let mut harness = palette(); + typed(&mut harness, "@notes"); + press(&mut harness, Key::Tab); + typed(&mut harness, "#db"); + press(&mut harness, Key::Tab); + assert_eq!(chips(&harness), 2); + + press(&mut harness, Key::Backspace); + assert_eq!(chips(&harness), 1); + harness + .get_by(|node| node.author_id() == Some("palette-chip-remove")) + .click(); + settle(&mut harness); + assert_eq!(chips(&harness), 0); +} + +// The keys + +#[test] +fn the_arrows_and_tab_walk_the_options_and_stay_on_them() { + let mut harness = palette(); + lists(&mut harness, "they are listed", |names| names.len() >= 2); + let last = options(&harness).len(); + let on = |harness: &Harness<'_, Bench>| harness.state().state.palette_view.highlighted; + assert_eq!(on(&harness), 0); + press(&mut harness, Key::ArrowUp); + assert_eq!(on(&harness), 0); + press(&mut harness, Key::Tab); + assert_eq!(on(&harness), 1); + harness.key_press_modifiers(Modifiers::SHIFT, Key::Tab); + settle(&mut harness); + assert_eq!(on(&harness), 0); + for _ in 0..last + 3 { + press(&mut harness, Key::ArrowDown); + } + assert_eq!(on(&harness), last - 1); +} + +#[test] +fn ctrl_c_copies_the_note_in_hand_and_closes() { + let mut harness = palette(); + typed(&mut harness, "psql prod"); + lists(&mut harness, "the note is found", |names| { + names.first().is_some_and(|name| name == "psql prod") + }); + harness.key_press_modifiers(Modifiers::COMMAND, Key::C); + settle(&mut harness); + until(&mut harness, "it is copied", |harness| { + harness.state().state.status.latest().is_some() + }); + + assert!(!harness.state().state.palette.is_open()); +} + +#[test] +fn escape_closes_it() { + let mut harness = palette(); + press(&mut harness, Key::Escape); + + assert!(!harness.state().state.palette.is_open()); +} + +// The commands + +#[test] +fn every_command_is_listed_by_its_prefix_and_found_by_its_words() { + let mut harness = palette(); + typed(&mut harness, ">"); + lists(&mut harness, "all of them", |names| { + names.len() >= COMMANDS.len() - 1 + }); + + let mut harness = palette(); + typed(&mut harness, "> http"); + lists(&mut harness, "the area", |names| names.len() == 1); + press(&mut harness, Key::Enter); + assert_eq!(harness.state().state.settings.area, Area::Http); +} + +#[test] +fn each_command_has_its_own_name_and_the_key_it_answers_to() { + let bindings = Bindings::default(); + let mut ids: Vec = COMMANDS.iter().map(|command| command.id()).collect(); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), COMMANDS.len()); + for (command, keys) in [ + (Command::Create(NoteKind::Snippet), vec!["Ctrl", "N"]), + (Command::Create(NoteKind::Note), vec!["Ctrl", "Shift", "N"]), + (Command::Area(Area::Notes), vec!["Ctrl", "1"]), + (Command::Area(Area::Tools), vec!["Ctrl", "2"]), + (Command::Area(Area::Http), vec!["Ctrl", "3"]), + (Command::Request, vec![]), + (Command::Preferences, vec![]), + ] { + assert_eq!(command.keys(&bindings), keys, "{command:?}"); + } +} diff --git a/crates/ui/src/palette/mod.rs b/crates/ui/src/palette/mod.rs index 97a2581b7..13a895cf9 100644 --- a/crates/ui/src/palette/mod.rs +++ b/crates/ui/src/palette/mod.rs @@ -3,6 +3,8 @@ //! one current row, and Enter or a click opens it, as everywhere else in the application. pub mod commands; +#[cfg(test)] +mod list_tests; pub mod options; use crate::theme::tokens::{font, gap, radius}; From 11d6925d5e3526fa4d202ab1b77c50a1330bf06e Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:32:03 +0100 Subject: [PATCH 74/95] JSON explorer: Escape empties the search, the count follows the text (#1812) * JSON explorer: Escape empties the search, the count follows the text Co-Authored-By: Claude Opus 5.5 * JSON explorer: an import of its test Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/ui/src/widgets/json_explorer/mod.rs | 11 +++- crates/ui/src/widgets/json_explorer/tests.rs | 64 +++++++++++++++++++- 2 files changed, 71 insertions(+), 4 deletions(-) diff --git a/crates/ui/src/widgets/json_explorer/mod.rs b/crates/ui/src/widgets/json_explorer/mod.rs index d48d2b0ae..a9f2186f6 100644 --- a/crates/ui/src/widgets/json_explorer/mod.rs +++ b/crates/ui/src/widgets/json_explorer/mod.rs @@ -147,7 +147,9 @@ impl Explorer { if count == 0 { return None; } - let index = match (self.match_index, forward) { + // Past the matches once the document lost some: from the start again. + let current = self.match_index.filter(|at| *at < count); + let index = match (current, forward) { (None, true) => 0, (None, false) => count - 1, (Some(at), true) => (at + 1) % count, @@ -513,7 +515,8 @@ impl<'a> ExplorerView<'a> { let name = self.tr(keys::json::SEARCH); let hint = self.tr(keys::json::SEARCH_PLACEHOLDER); let count = self.view.match_count; - let matched = match self.explorer.match_index { + let found = self.view.matches.len(); + let matched = match self.explorer.match_index.filter(|at| *at < found) { None => count.to_string(), Some(at) => format!("{} / {count}", at + 1), }; @@ -537,12 +540,14 @@ impl<'a> ExplorerView<'a> { .or(output.chosen.take()); field.request_focus(); } - if field.has_focus() + // egui lets go on Escape before it is read. + if field.lost_focus() && searching && row.input_mut(|input| input.consume_key(Modifiers::NONE, Key::Escape)) { self.explorer.search.clear(); self.explorer.search_due = Some(row.input(|input| input.time)); + field.request_focus(); } if searching { if IconButton::new( diff --git a/crates/ui/src/widgets/json_explorer/tests.rs b/crates/ui/src/widgets/json_explorer/tests.rs index a59646853..5513f7b9e 100644 --- a/crates/ui/src/widgets/json_explorer/tests.rs +++ b/crates/ui/src/widgets/json_explorer/tests.rs @@ -1,11 +1,12 @@ //! The explorer's reads over views the core answered, as the reference's model specs had them. +use egui_kittest::kittest::Queryable; use engine::json::model::{JsonOpening, JsonQuery, JsonView, explore}; use engine::json::parse::Span; use engine::json::read::StructureFormat; use super::reads::{find, preview, trail_of}; -use super::{Explorer, entry_at, span_of, utf16_slice}; +use super::{Explorer, ExplorerView, entry_at, span_of, utf16_slice}; const EVENT: &str = r#"{"id":"evt_1","data":{"object":{"amount":4900,"lines":[{"description":"Pro · mensuel"}]}}}"#; @@ -112,3 +113,64 @@ fn stepping_to_a_match_reveals_it_and_wraps_around() { JsonOpening::Paths { reveal: Some(path), .. } if path == "$.a" )); } + +/// Escape is the window's once there is nothing to empty. +#[test] +fn escape_empties_the_search_and_stays_in_it() { + let state = (Explorer::default(), 0); + let mut harness = crate::testing::harness() + .with_size(egui::vec2(1_100.0, 800.0)) + .build_ui_state( + |ui, (explorer, escapes): &mut (Explorer, usize)| { + let view = view(EVENT, JsonOpening::All); + ExplorerView::new(explorer, &view, EVENT).show(ui); + *escapes += usize::from(ui.input(|input| input.key_pressed(egui::Key::Escape))); + }, + state, + ); + harness.run(); + harness + .get_by(|node| node.author_id() == Some("json-search")) + .click(); + harness.run(); + harness + .get_by(|node| node.author_id() == Some("json-search")) + .type_text("pro"); + harness.run(); + assert_eq!(harness.state().0.search, "pro"); + + harness.key_press(egui::Key::Escape); + harness.run(); + assert_eq!( + (harness.state().0.search.as_str(), harness.state().1), + ("", 0) + ); + assert!( + harness + .get_by(|node| node.author_id() == Some("json-search")) + .is_focused() + ); + harness.key_press(egui::Key::Escape); + harness.run(); + assert_eq!(harness.state().1, 1); +} + +#[test] +fn the_count_starts_over_when_the_document_lost_the_match_it_was_on() { + let found = |text: &str| { + explore(&JsonQuery { + text: text.to_owned(), + format: StructureFormat::Json, + search: "x".to_owned(), + opening: JsonOpening::All, + }) + }; + let mut explorer = Explorer::default(); + let before = found(r#"{"a":"x","b":"x","c":"x"}"#); + for path in ["$.a", "$.b", "$.c"] { + assert_eq!(explorer.step(&before, true).as_deref(), Some(path)); + } + let after = found(r#"{"a":"x","b":"x"}"#); + + assert_eq!(explorer.step(&after, true).as_deref(), Some("$.a")); +} From 5d53940aeb283031ec0fdf0646b4f3d428cb56ce Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:51:28 +0100 Subject: [PATCH 75/95] Menus: a filter starts over when its menu opens again (#1816) Co-authored-by: Claude Opus 5.5 --- crates/ui/src/widgets/menu.rs | 65 +++++++++++++++++++++++++++++---- crates/ui/src/widgets/picker.rs | 1 - 2 files changed, 58 insertions(+), 8 deletions(-) diff --git a/crates/ui/src/widgets/menu.rs b/crates/ui/src/widgets/menu.rs index 4043a3026..851b91820 100644 --- a/crates/ui/src/widgets/menu.rs +++ b/crates/ui/src/widgets/menu.rs @@ -402,6 +402,7 @@ pub(super) fn filter_field( query_id: Id, (label, author_id, placeholder): (&str, &str, &str), ) -> Filter { + start_over_once_opened(ui, query_id); let mut query: String = ui.data(|data| data.get_temp(query_id)).unwrap_or_default(); let emptied = !query.is_empty() && ui.input_mut(|input| input.consume_key(Modifiers::NONE, Key::Escape)); @@ -431,6 +432,19 @@ pub(super) fn filter_field( } } +/// What was typed and walked to is of one opening: not drawn at the pass before, it starts over. +fn start_over_once_opened(ui: &Ui, query_id: Id) { + let now = ui.ctx().cumulative_pass_nr(); + ui.data_mut(|data| { + let drawn: Option = data.get_temp(query_id.with("drawn")); + if drawn.is_none_or(|last| last + 1 < now) { + data.remove::(query_id); + data.remove::(query_id.with("walked")); + } + data.insert_temp(query_id.with("drawn"), now); + }); +} + /// The entry the arrows stand on: the one they left, or the current one, or the first. pub(super) fn walk( ui: &Ui, @@ -582,12 +596,11 @@ impl<'a, T: PartialEq + Copy> ChoiceMenu<'a, T> { } }) .and_then(|shown| shown.inner); - if let Some(value) = picked { - ui.data_mut(|data| data.remove::(query_id)); - if value != *selected { - *selected = value; - response.mark_changed(); - } + if let Some(value) = picked + && value != *selected + { + *selected = value; + response.mark_changed(); } response } @@ -713,7 +726,7 @@ pub(super) fn walked_ring(ui: &Ui, row: egui::Rect) { #[cfg(test)] mod tests { - use egui_kittest::kittest::Queryable; + use egui_kittest::kittest::{NodeT, Queryable}; use super::*; use crate::widgets::Button; @@ -1178,4 +1191,42 @@ mod tests { .is_none() ); } + + /// Opened again, it is the whole list, at what is selected. + #[test] + fn what_was_typed_and_walked_to_does_not_outlive_the_menu() { + let mut harness = opened(); + harness + .get_by(|node| node.author_id() == Some("format-filter")) + .type_text("rus"); + harness.run(); + harness.key_press(Key::Escape); + harness.run(); + harness.key_press(Key::ArrowDown); + harness.run(); + harness + .get_by(|node| node.author_id() == Some("format-filter")) + .type_text("s"); + harness.run(); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { + pos: egui::pos2(700.0, 700.0), + button: egui::PointerButton::Primary, + pressed, + modifiers: Modifiers::NONE, + }); + } + harness.run(); + harness + .get_by(|node| node.author_id() == Some("format")) + .click(); + harness.run(); + harness.run(); + + let filter = harness.get_by(|node| node.author_id() == Some("format-filter")); + assert_eq!(filter.accesskit_node().value().unwrap_or_default(), ""); + harness.key_press(Key::Enter); + harness.run(); + assert_eq!(*harness.state(), 0); + } } diff --git a/crates/ui/src/widgets/picker.rs b/crates/ui/src/widgets/picker.rs index afe59c7d4..9c71c0ea5 100644 --- a/crates/ui/src/widgets/picker.rs +++ b/crates/ui/src/widgets/picker.rs @@ -89,7 +89,6 @@ pub fn place_picker( ); let picked = picked.or(walked.filter(|_| filter.entered)); if picked.is_some() { - ui.data_mut(|data| data.remove::(query_id)); ui.close(); } picked From b46adab2faaa40c6b86f442c5f3fb2b69dc709b4 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 13:03:00 +0100 Subject: [PATCH 76/95] HTTP: rows of a long answer fill the pane, as in the JSON tree (#1814) * HTTP: rows of a long answer fill the pane, as in the JSON tree Co-Authored-By: Claude Opus 5.5 * HTTP: the rows of its test Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/ui/src/http/response/body.rs | 44 +++++++++++++++++++- crates/ui/src/widgets/json_explorer/tests.rs | 26 +++++++++++- crates/ui/src/widgets/json_explorer/tree.rs | 3 +- 3 files changed, 70 insertions(+), 3 deletions(-) diff --git a/crates/ui/src/http/response/body.rs b/crates/ui/src/http/response/body.rs index c657342d6..53e164cdd 100644 --- a/crates/ui/src/http/response/body.rs +++ b/crates/ui/src/http/response/body.rs @@ -221,6 +221,8 @@ impl TextLines { ) .size() .x + 16.0; + // The rows are counted with the spacing around the list, and drawn with the one inside it. + let spacing = std::mem::take(&mut ui.spacing_mut().item_spacing.y); let shown = egui::ScrollArea::both() .id_salt(("http-response-lines", author_id)) .auto_shrink([false, false]) @@ -228,7 +230,7 @@ impl TextLines { if coloured && let Some(colouring) = self.colouring.as_mut() { colouring.window(&self.rope, range.clone()); } - ui.spacing_mut().item_spacing.y = 0.0; + ui.spacing_mut().interact_size.y = LINE; for at in range { let line = &self.text[self.lines[at].clone()]; ui.horizontal(|ui| { @@ -266,6 +268,7 @@ impl TextLines { }); } }); + ui.spacing_mut().item_spacing.y = spacing; let region = widgets::region(ui, shown.inner_rect, author_id, egui::Sense::hover()); let label = self.text.chars().take(LABEL_UP_TO).collect::(); region.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Document, true, &label)); @@ -377,3 +380,42 @@ fn image( )); widgets::address(ui, &said, "http-response-binary"); } + +#[cfg(test)] +mod row_tests { + use super::TextLines; + use crate::testing; + use crate::theme::tokens::gap; + + /// Drawn closer than they are counted, the rows in view left the end of the pane empty. + #[test] + fn the_rows_in_view_fill_the_pane() { + let rows: Vec = (0..300).map(|n| format!("row {n}")).collect(); + let text = rows.join("\n"); + let harness = testing::harness() + .with_size(egui::vec2(600.0, 400.0)) + .build_ui(move |ui| { + ui.spacing_mut().item_spacing.y = gap::INSET; + TextLines::new(ui, &text, None).show(ui, "lines", false); + }); + let mut tops: Vec = harness + .output() + .shapes + .iter() + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) if text.galley.text().starts_with("row") => { + Some(text.pos.y) + } + _ => None, + }) + .collect(); + tops.sort_by(f32::total_cmp); + + let gaps: Vec = tops.windows(2).map(|pair| pair[1] - pair[0]).collect(); + assert!( + gaps.iter().all(|gap| (gap - super::LINE).abs() < 0.01), + "{gaps:?}" + ); + assert!(tops[tops.len() - 1] + super::LINE >= 390.0, "{tops:?}"); + } +} diff --git a/crates/ui/src/widgets/json_explorer/tests.rs b/crates/ui/src/widgets/json_explorer/tests.rs index 5513f7b9e..ecb4c1128 100644 --- a/crates/ui/src/widgets/json_explorer/tests.rs +++ b/crates/ui/src/widgets/json_explorer/tests.rs @@ -6,7 +6,7 @@ use engine::json::parse::Span; use engine::json::read::StructureFormat; use super::reads::{find, preview, trail_of}; -use super::{Explorer, ExplorerView, entry_at, span_of, utf16_slice}; +use super::{Explorer, ExplorerView, Mode, entry_at, span_of, utf16_slice}; const EVENT: &str = r#"{"id":"evt_1","data":{"object":{"amount":4900,"lines":[{"description":"Pro · mensuel"}]}}}"#; @@ -114,6 +114,30 @@ fn stepping_to_a_match_reveals_it_and_wraps_around() { )); } +#[test] +fn the_line_the_search_goes_to_is_scrolled_into_view() { + let rows: Vec = (0..300).map(|n| format!(r#""k{n}":{n}"#)).collect(); + let text = format!("{{{}}}", rows.join(",")); + let mut harness = crate::testing::harness() + .with_size(egui::vec2(1_100.0, 800.0)) + .build_ui_state( + |ui, (explorer, view, text): &mut (Explorer, JsonView, String)| { + ExplorerView::new(explorer, view, text) + .mode(Mode::Tree) + .show(ui); + }, + (Explorer::default(), view(&text, JsonOpening::All), text), + ); + harness.run(); + let explorer = &mut harness.state_mut().0; + explorer.select("$.k250"); + explorer.tree.reveal = true; + harness.run(); + + let line = harness.get_by(|node| node.description().as_deref() == Some("$.k250")); + assert!(line.rect().bottom() <= 801.0, "{:?}", line.rect()); +} + /// Escape is the window's once there is nothing to empty. #[test] fn escape_empties_the_search_and_stays_in_it() { diff --git a/crates/ui/src/widgets/json_explorer/tree.rs b/crates/ui/src/widgets/json_explorer/tree.rs index a177f4b7a..685f7542b 100644 --- a/crates/ui/src/widgets/json_explorer/tree.rs +++ b/crates/ui/src/widgets/json_explorer/tree.rs @@ -75,12 +75,13 @@ pub(super) fn show( .id_salt("json-tree-rows") .max_rect(rect.with_min_y(rect.top() + TOOLS_ROOM)), ); + // The rows are counted with the spacing around the list, and drawn with the one inside it. + inner.spacing_mut().item_spacing = Vec2::ZERO; let shown = area.show_rows( &mut inner, LINE, lines.len() + usize::from(view.tree_truncated), |ui, range| { - ui.spacing_mut().item_spacing = Vec2::ZERO; for index in range { let Some(line) = lines.get(index) else { let note = i18n::translate(language, keys::json::TREE_TRUNCATED, &[]); From 2daa42d5393871785faba9b5536f85e54eb107ec Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 13:14:19 +0100 Subject: [PATCH 77/95] Keyboard: arrows keep moving in the JSON explorer, edges and cards (#1818) * JSON explorer: the arrows stay in the graph and the tree Co-Authored-By: Claude Opus 5.5 * Keyboard: the arrows keep moving a split edge Co-Authored-By: Claude Opus 5.5 * Keyboard: the arrows of a card held at every frame Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/ui/src/http/mod.rs | 1 + crates/ui/src/http/tests.rs | 19 +++++++ crates/ui/src/notes/canvas/board/zone.rs | 7 +-- crates/ui/src/notes/canvas/card/mod.rs | 3 +- crates/ui/src/notes/canvas/shortcuts.rs | 36 +++++++++++++ crates/ui/src/widgets/date.rs | 7 +-- crates/ui/src/widgets/json_explorer/graph.rs | 1 + crates/ui/src/widgets/json_explorer/tests.rs | 53 ++++++++++++++++++++ crates/ui/src/widgets/json_explorer/tree.rs | 1 + crates/ui/src/widgets/layout.rs | 34 +++++++++++++ crates/ui/src/widgets/mod.rs | 8 +++ 11 files changed, 156 insertions(+), 14 deletions(-) diff --git a/crates/ui/src/http/mod.rs b/crates/ui/src/http/mod.rs index 6687b645b..67e7b0109 100644 --- a/crates/ui/src/http/mod.rs +++ b/crates/ui/src/http/mod.rs @@ -346,6 +346,7 @@ fn split( actions.push(Asked::Http(Action::SetShare(0))); } if widgets::takes_keys(ui, &handle) { + widgets::keep_arrows(ui, &handle); for (key, step) in [(egui::Key::ArrowUp, -16.0), (egui::Key::ArrowDown, 16.0)] { if ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, key)) { actions.push(Asked::Http(Action::SetShare(share_at(upper + step, total)))); diff --git a/crates/ui/src/http/tests.rs b/crates/ui/src/http/tests.rs index 124dfef83..f4c11d315 100644 --- a/crates/ui/src/http/tests.rs +++ b/crates/ui/src/http/tests.rs @@ -1273,6 +1273,25 @@ fn a_status_says_its_family_and_a_failure_says_why() { }); } +#[test] +fn every_arrow_moves_the_edge_between_the_request_and_its_answer() { + let mut harness = sending_to("/json"); + harness.state_mut().state.settings.http_request_share = 300; + settle(&mut harness); + harness + .get_by(|node| node.author_id() == Some("http-split-handle")) + .focus(); + settle(&mut harness); + let mut shares = Vec::new(); + for _ in 0..3 { + harness.key_press(egui::Key::ArrowDown); + settle(&mut harness); + shares.push(harness.state().state.settings.http_request_share); + } + + assert!(shares.is_sorted_by(|a, b| a < b), "{shares:?}"); +} + #[test] fn the_line_between_request_and_answer_is_left_automatic_on_a_double_click() { let mut harness = sending_to("/json"); diff --git a/crates/ui/src/notes/canvas/board/zone.rs b/crates/ui/src/notes/canvas/board/zone.rs index 01df03364..84ea83278 100644 --- a/crates/ui/src/notes/canvas/board/zone.rs +++ b/crates/ui/src/notes/canvas/board/zone.rs @@ -326,12 +326,7 @@ fn nudge( if !widgets::takes_keys(ui, response) { return; } - let kept = egui::EventFilter { - horizontal_arrows: true, - vertical_arrows: true, - ..egui::EventFilter::default() - }; - ui.memory_mut(|memory| memory.set_focus_lock_filter(response.id, kept)); + crate::widgets::keep_arrows(ui, response); let steps = [ (Key::ArrowLeft, (-1, 0)), (Key::ArrowRight, (1, 0)), diff --git a/crates/ui/src/notes/canvas/card/mod.rs b/crates/ui/src/notes/canvas/card/mod.rs index eb88adcfd..1a07163cb 100644 --- a/crates/ui/src/notes/canvas/card/mod.rs +++ b/crates/ui/src/notes/canvas/card/mod.rs @@ -115,9 +115,8 @@ pub(super) fn show( if crate::widgets::takes_keys(ui, &open) { canvas_view.focused = Some(note.id.clone()); // The arrows and Escape are the canvas's table's: egui would move the focus itself. + crate::widgets::keep_arrows(ui, &open); let kept = egui::EventFilter { - horizontal_arrows: true, - vertical_arrows: true, escape: true, ..egui::EventFilter::default() }; diff --git a/crates/ui/src/notes/canvas/shortcuts.rs b/crates/ui/src/notes/canvas/shortcuts.rs index 43b009ab4..4bca1fab3 100644 --- a/crates/ui/src/notes/canvas/shortcuts.rs +++ b/crates/ui/src/notes/canvas/shortcuts.rs @@ -323,4 +323,40 @@ mod tests { engine::notes::kind::NoteKind::Snippet ); } + + /// Held, the key comes back at every frame: egui would walk the focus off the cards between + /// two, onto the edge of the rail. + #[test] + fn an_arrow_held_stays_on_the_cards() { + let (backend, profile) = notes(2); + let mut harness = area(backend, profile); + press(&mut harness, Key::ArrowDown); + let on_a_card = |harness: &Harness<'_, Bench>| { + harness + .query_all_by(|node| node.author_id() == Some("note-card-open")) + .any(|node| node.is_focused()) + }; + for pauses in 0..4 { + for key in [ + Key::ArrowRight, + Key::ArrowLeft, + Key::ArrowLeft, + Key::ArrowLeft, + ] { + harness.event(egui::Event::Key { + key, + physical_key: Some(key), + pressed: true, + repeat: false, + modifiers: Modifiers::NONE, + }); + harness.step(); + for _ in 0..pauses { + harness.step(); + } + } + settle(&mut harness); + assert!(on_a_card(&harness), "{pauses} frames between two keys"); + } + } } diff --git a/crates/ui/src/widgets/date.rs b/crates/ui/src/widgets/date.rs index e3b08be71..6de7c524c 100644 --- a/crates/ui/src/widgets/date.rs +++ b/crates/ui/src/widgets/date.rs @@ -98,12 +98,7 @@ impl<'a> DateField<'a> { ); icons::paint(ui, glyph, Icon::Calendar, p.text_2); if open { - let arrows = egui::EventFilter { - horizontal_arrows: true, - vertical_arrows: true, - ..Default::default() - }; - ui.memory_mut(|memory| memory.set_focus_lock_filter(response.id, arrows)); + super::keep_arrows(ui, &response); } if takes_delete(ui, &response) { return Some(Picked::Cleared); diff --git a/crates/ui/src/widgets/json_explorer/graph.rs b/crates/ui/src/widgets/json_explorer/graph.rs index 89341cd1b..d8afdc91f 100644 --- a/crates/ui/src/widgets/json_explorer/graph.rs +++ b/crates/ui/src/widgets/json_explorer/graph.rs @@ -231,6 +231,7 @@ pub(super) fn show( ground.request_focus(); explorer.ground.reveal = true; } + widgets::keep_arrows(ui, &ground); if std::mem::take(&mut explorer.ground.reveal) && let Some(target) = cursor_rect(explorer, graph, &plane) { diff --git a/crates/ui/src/widgets/json_explorer/tests.rs b/crates/ui/src/widgets/json_explorer/tests.rs index ecb4c1128..bde4aa012 100644 --- a/crates/ui/src/widgets/json_explorer/tests.rs +++ b/crates/ui/src/widgets/json_explorer/tests.rs @@ -198,3 +198,56 @@ fn the_count_starts_over_when_the_document_lost_the_match_it_was_on() { assert_eq!(explorer.step(&after, true).as_deref(), Some("$.a")); } + +/// Beside the tree and the graph are a panel and a breadcrumb, where egui would take the focus. +#[test] +fn the_arrows_stay_in_the_tree_and_in_the_graph() { + use egui::Key; + for (mode, entry, steps) in [ + ( + Mode::Tree, + "json-line", + [ + (Key::ArrowRight, "$.id"), + (Key::ArrowDown, "$.data"), + (Key::ArrowDown, "$.data.object"), + (Key::ArrowUp, "$.data"), + ], + ), + ( + Mode::Graph, + "json-row", + [ + (Key::ArrowRight, "$.id"), + (Key::ArrowDown, "$.data"), + (Key::ArrowUp, "$.id"), + (Key::ArrowLeft, "$"), + ], + ), + ] { + let mut harness = crate::testing::harness() + .with_size(egui::vec2(1_100.0, 800.0)) + .build_ui_state( + move |ui, explorer: &mut Explorer| { + let view = view(EVENT, JsonOpening::All); + ExplorerView::new(explorer, &view, EVENT) + .mode(mode) + .show(ui); + }, + Explorer::default(), + ); + harness.run(); + harness + .get_by(|node| { + node.author_id() == Some(entry) && node.description().as_deref() == Some("$.id") + }) + .click(); + harness.run(); + for (at, (key, path)) in steps.into_iter().enumerate() { + harness.key_press(key); + harness.run(); + let selected = harness.state().selected.as_deref(); + assert_eq!(selected, Some(path), "{mode:?}, step {at}"); + } + } +} diff --git a/crates/ui/src/widgets/json_explorer/tree.rs b/crates/ui/src/widgets/json_explorer/tree.rs index 685f7542b..fb3cf2d20 100644 --- a/crates/ui/src/widgets/json_explorer/tree.rs +++ b/crates/ui/src/widgets/json_explorer/tree.rs @@ -114,6 +114,7 @@ pub(super) fn show( list.request_focus(); explorer.tree.reveal = true; } + widgets::keep_arrows(ui, &list); picked } diff --git a/crates/ui/src/widgets/layout.rs b/crates/ui/src/widgets/layout.rs index cb57f5c0a..c99214c8b 100644 --- a/crates/ui/src/widgets/layout.rs +++ b/crates/ui/src/widgets/layout.rs @@ -119,6 +119,7 @@ pub fn split_handle(ui: &mut Ui, author_id: &str) -> f32 { } let mut moved = response.drag_delta().x; if super::takes_keys(ui, &response) { + super::keep_arrows(ui, &response); ui.input_mut(|input| { if input.consume_key(Modifiers::NONE, Key::ArrowLeft) { moved -= STEP; @@ -193,6 +194,39 @@ mod tests { assert_eq!(harness.state().0, Some((160, 520.0))); } + /// Beside it, what it resizes: egui would take the focus there. + #[test] + fn a_handle_focused_is_moved_by_every_arrow() { + let mut harness = crate::testing::harness() + .with_size(egui::vec2(800.0, 400.0)) + .build_ui_state( + |ui, moved: &mut f32| { + ui.horizontal(|ui| { + crate::widgets::Button::new("Avant", "before").show(ui); + *moved += split_handle(ui, "edge"); + crate::widgets::Button::new("Après", "after").show(ui); + }); + }, + 0.0, + ); + harness.run(); + harness + .get_by(|node| node.author_id() == Some("edge")) + .focus(); + harness.run(); + for (key, then) in [ + (Key::ArrowRight, 16.0), + (Key::ArrowRight, 32.0), + (Key::ArrowLeft, 16.0), + (Key::ArrowLeft, 0.0), + ] { + harness.key_press(key); + harness.run(); + let moved = *harness.state(); + assert!((moved - then).abs() < 0.01, "{key:?}: {moved}"); + } + } + #[test] fn the_default_rail_fits_a_narrow_window_and_a_chosen_width_stays() { let narrow = Rect::from_min_size(egui::Pos2::ZERO, Vec2::new(640.0, 400.0)); diff --git a/crates/ui/src/widgets/mod.rs b/crates/ui/src/widgets/mod.rs index 1e2e6ad31..7d25910c5 100644 --- a/crates/ui/src/widgets/mod.rs +++ b/crates/ui/src/widgets/mod.rs @@ -115,6 +115,14 @@ pub fn takes_keys(ui: &Ui, response: &Response) -> bool { ui.memory(|memory| memory.has_focus(response.id)) } +/// The arrows of the frame are the focused `response`'s: egui would move the focus itself. Not its +/// event filter, which a focus just asked for does not have until the frame after. +pub fn keep_arrows(ui: &Ui, response: &Response) { + if takes_keys(ui, response) { + ui.memory_mut(|memory| memory.move_focus(egui::FocusDirection::None)); + } +} + /// Room at a place already decided — a node on a ground, a pane — under an id that `salt` /// keeps whatever is drawn before it. pub fn region(ui: &mut Ui, rect: egui::Rect, salt: impl egui::AsIdSalt, sense: Sense) -> Response { From 707c73d59a97c7e09ddd629f8dac61cc4daaa307 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 13:21:18 +0100 Subject: [PATCH 78/95] Notes: a link in a table cell can be followed (#1820) Co-authored-by: Claude Opus 5.5 --- crates/ui/src/widgets/rich.rs | 155 +++++++++++++++++++++++++++------- 1 file changed, 124 insertions(+), 31 deletions(-) diff --git a/crates/ui/src/widgets/rich.rs b/crates/ui/src/widgets/rich.rs index 1a7a63ca1..c53bb3599 100644 --- a/crates/ui/src/widgets/rich.rs +++ b/crates/ui/src/widgets/rich.rs @@ -338,35 +338,60 @@ fn paragraph(ui: &mut Ui, content: &[Inline], style: Style, path: &[usize], fram let widest = frame.slide.map_or(f32::INFINITY, |slide| slide.widest); let (job, links) = job(p, content, style, ui.available_width().min(widest)); let galley = ui.fonts_mut(|fonts| fonts.layout_job(job)); - let reading = frame.selection.is_none(); - let sense = if reading && !links.is_empty() { + let (rect, response) = ui.allocate_exact_size(galley.size(), sense_of(&links, frame)); + if frame.selection.is_none() { + let plain = richtext::inlines::plain(content); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, &plain)); + } + follow(ui, &response, (&galley, rect.min), &links, frame); + paint_leaf(ui, path, rect.min, galley, style.colour, frame); +} + +/// Read, a leaf that holds a link takes the click; edited, the surface under it does. +fn sense_of(links: &Links, frame: &Frame<'_>) -> Sense { + if frame.selection.is_none() && !links.is_empty() { Sense::click() } else { Sense::hover() + } +} + +/// The link under the pointer, followed by a click; edited, by Ctrl and a click. +fn follow( + ui: &Ui, + response: &egui::Response, + (galley, origin): (&Galley, Pos2), + links: &Links, + frame: &mut Frame<'_>, +) { + let within = Rect::from_min_size(origin, galley.size()); + let Some(pointer) = ui + .ctx() + .pointer_hover_pos() + .filter(|at| within.contains(*at)) + else { + return; }; - let (rect, response) = ui.allocate_exact_size(galley.size(), sense); - if reading { - let plain = richtext::inlines::plain(content); - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, &plain)); + let local = pointer - origin; + let cursor = galley.cursor_from_pos(local); + let before = local.x < galley.pos_from_cursor(cursor).center().x; + let under = cursor.index.0.saturating_sub(usize::from(before)); + let Some((_, href)) = links.iter().find(|(range, _)| range.contains(&under)) else { + return; + }; + let reading = frame.selection.is_none(); + let ctrl = ui.input(|input| input.modifiers.command); + if reading || ctrl { + ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand); } - if let Some(pointer) = ui.ctx().pointer_hover_pos().filter(|at| rect.contains(*at)) { - let at = galley.cursor_from_pos(pointer - rect.min).index.0; - if let Some((_, href)) = links.iter().find(|(range, _)| range.contains(&at)) { - let ctrl = ui.input(|input| input.modifiers.command); - if reading || ctrl { - ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand); - } - let clicked = if reading { - response.clicked() - } else { - ctrl && ui.input(|input| input.pointer.primary_clicked()) - }; - if clicked && is_web(href) { - frame.painted.link = Some(href.clone()); - } - } + let clicked = if reading { + response.clicked() + } else { + ctrl && ui.input(|input| input.pointer.primary_clicked()) + }; + if clicked && is_web(href) { + frame.painted.link = Some(href.clone()); } - paint_leaf(ui, path, rect.min, galley, style.colour, frame); } /// The selection under the text, then the text; the leaf kept for the editor. @@ -700,20 +725,21 @@ fn table(ui: &mut Ui, rows: &[Vec], path: &[usize], frame: &mut weight: if header { 600.0 } else { 400.0 }, ..Style::body(p, size) }; - let galleys: Vec<_> = (0..columns) + let cells: Vec<_> = (0..columns) .map(|index| { - let cell = row.get(index).map_or(&[][..], Vec::as_slice); - let (job, _) = job(p, cell, style, column - 2.0 * padding.x); - ui.fonts_mut(|fonts| fonts.layout_job(job)) + let content = row.get(index).map_or(&[][..], Vec::as_slice); + let (job, links) = job(p, content, style, column - 2.0 * padding.x); + let galley = ui.fonts_mut(|fonts| fonts.layout_job(job)); + (content, galley, links) }) .collect(); - let height = galleys + let height = cells .iter() - .map(|galley| galley.size().y) + .map(|(_, galley, _)| galley.size().y) .fold(size * LINE_HEIGHT, f32::max) + 2.0 * padding.y; let (rect, _) = ui.allocate_exact_size(vec2(width, height), Sense::hover()); - for (index, galley) in galleys.into_iter().enumerate() { + for (index, (content, galley, links)) in cells.into_iter().enumerate() { let left = rect.left() + column * f32::from(u16::try_from(index).unwrap_or(0)); let cell = Rect::from_min_size(pos2(left, rect.top()), vec2(column, height)); if header { @@ -726,7 +752,15 @@ fn table(ui: &mut Ui, rows: &[Vec], path: &[usize], frame: &mut StrokeKind::Middle, ); let cell_path = [path, &[at, index]].concat(); - paint_leaf(ui, &cell_path, cell.min + padding, galley, p.text_0, frame); + let sense = sense_of(&links, frame); + let response = crate::widgets::region(ui, cell, &cell_path, sense); + if frame.selection.is_none() { + let plain = richtext::inlines::plain(content); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Cell, true, &plain)); + } + let origin = cell.min + padding; + follow(ui, &response, (&galley, origin), &links, frame); + paint_leaf(ui, &cell_path, origin, galley, p.text_0, frame); } } } @@ -921,4 +955,63 @@ mod tests { harness.run(); assert!(harness.state().is_none(), "never a file"); } + + #[test] + fn a_link_in_a_table_is_read_and_answered() { + let mut harness = shown("| a | b |\n| --- | --- |\n| un | [le site](https://exemple.fr) |"); + assert!(says(&harness, "un")); + let at = harness.get_by_label("le site").rect().left_top() + vec2(16.0, 14.0); + harness.hover_at(at); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed, + modifiers: egui::Modifiers::NONE, + }); + } + harness.run(); + assert_eq!(harness.state().as_deref(), Some("https://exemple.fr")); + } + + /// Edited, the click is the caret's: the link wants Ctrl, in a table as elsewhere. + #[test] + fn edited_a_link_is_followed_with_ctrl_alone() { + for markdown in [ + "[site](https://exemple.fr)", + "| [site](https://exemple.fr) |\n| --- |\n| b |", + ] { + for (modifiers, link) in [ + (egui::Modifiers::NONE, None), + (egui::Modifiers::COMMAND, Some("https://exemple.fr")), + ] { + let document = richtext::read(markdown); + let selection = Selection::default(); + let mut harness = crate::testing::harness() + .with_size(vec2(700.0, 300.0)) + .build_ui_state( + move |ui, painted: &mut Painted| { + let now = RichView::new(&document).editing(&selection).show(ui); + painted.link = now.link.or(painted.link.take()); + painted.leaves = now.leaves; + }, + Painted::default(), + ); + harness.run(); + let at = harness.state().leaves[0].origin + vec2(12.0, 10.0); + harness.event(egui::Event::ModifiersChanged(modifiers)); + harness.event(egui::Event::PointerMoved(at)); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed, + modifiers, + }); + } + harness.run(); + assert_eq!(harness.state().link.as_deref(), link, "{markdown}"); + } + } + } } From 5306c1a0299fd62f70e764d3fea7f3d9c9ada9ab Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 13:34:32 +0100 Subject: [PATCH 79/95] Notes: Ctrl moves and deletes by word, an emoji goes whole (#1824) Co-authored-by: Claude Opus 5.5 --- crates/ui/src/notes/overlays/editor/rich.rs | 85 ++++++++++---- .../src/notes/overlays/editor/rich/tests.rs | 110 ++++++++++++++++++ 2 files changed, 172 insertions(+), 23 deletions(-) diff --git a/crates/ui/src/notes/overlays/editor/rich.rs b/crates/ui/src/notes/overlays/editor/rich.rs index 01bdcbf45..ca60f0a3e 100644 --- a/crates/ui/src/notes/overlays/editor/rich.rs +++ b/crates/ui/src/notes/overlays/editor/rich.rs @@ -11,6 +11,7 @@ use richtext::edit::{self, ordered}; use richtext::inlines::{self, Mark}; use richtext::picture::{self, Beside}; use richtext::{Document, History, ListKind, Marks, Position, Selection, tree}; +use text::{Direction, Unit}; use crate::state::AppState; use crate::theme::palette; @@ -206,21 +207,36 @@ impl RichEditor { }; } - /// The caret one `char` along, across leaves; `extend` keeps the anchor. - fn step(&mut self, forward: bool, extend: bool) { + /// The text of the leaf at `path`, as its offsets count it. + fn leaf_text(&self, path: &[usize]) -> Option { + match tree::leaf(&self.document, path)? { + tree::Leaf::Inlines(content) => Some(inlines::plain(content)), + tree::Leaf::Code(text) => Some(text.clone()), + } + } + + /// The offset one `unit` along in the caret's leaf; `None` at its edge. + fn along(&self, forward: bool, unit: Unit) -> Option { + let head = &self.selection.head; + let direction = if forward { + Direction::Forward + } else { + Direction::Backward + }; + let buffer = text::Buffer::new(&self.leaf_text(&head.path)?); + let offset = buffer.step(head.offset, direction, unit); + (offset != head.offset).then_some(offset) + } + + /// The caret one `unit` along, across leaves; `extend` keeps the anchor. + fn step(&mut self, forward: bool, extend: bool, unit: Unit) { let head = self.selection.head.clone(); - if !extend && !self.selection.is_empty() { + if !extend && unit == Unit::Grapheme && !self.selection.is_empty() { let (start, end) = ordered(&self.selection); self.selection = Selection::caret(if forward { end } else { start }); return; } - let length = tree::leaf(&self.document, &head.path).map_or(0, |leaf| leaf.len()); - let inside = if forward { - (head.offset < length).then_some(head.offset + 1) - } else { - head.offset.checked_sub(1) - }; - if let Some(offset) = inside { + if let Some(offset) = self.along(forward, unit) { self.move_head(Position { offset, ..head }, extend); } else { self.step_past(head.path, forward, extend); @@ -228,6 +244,29 @@ impl RichEditor { self.goal_x = None; } + /// The selection, or one `unit` from the caret; at a leaf's edge, what the document makes of it. + fn delete(&mut self, forward: bool, unit: Unit) { + let within = self.selection.is_empty().then(|| self.along(forward, unit)); + let Some(offset) = within.flatten() else { + let delete = if forward { + edit::delete_forward + } else { + edit::delete_backward + }; + self.change(Step::Other, delete); + return; + }; + let anchor = self.selection.head.clone(); + let head = Position { + offset, + ..anchor.clone() + }; + let taken = Selection { anchor, head }; + self.change(Step::Other, |document, _| { + edit::delete_selection(document, &taken) + }); + } + /// Off a leaf or an image: onto the image beside it, which a selection goes over. fn step_past(&mut self, mut path: Vec, forward: bool, extend: bool) { loop { @@ -243,10 +282,8 @@ impl RichEditor { /// The word holding the `char` at `at`, as the code editor reads a word; `extend`, the /// selection stretched to it. fn select_word(&mut self, at: Position, extend: bool) { - let text = match tree::leaf(&self.document, &at.path) { - Some(tree::Leaf::Inlines(content)) => inlines::plain(content), - Some(tree::Leaf::Code(text)) => text.clone(), - None => return, + let Some(text) = self.leaf_text(&at.path) else { + return; }; let word = text::word_around(&text, at.offset); let start = Position { @@ -557,11 +594,7 @@ fn describe(ui: &Ui, surface: &egui::Response, view: &RichEditor, language: Lang let label = i18n::translate(language, keys::editor::CONTENT_LABEL, &[]); let value: String = tree::leaves(&view.document) .iter() - .filter_map(|path| match tree::leaf(&view.document, path) { - Some(tree::Leaf::Inlines(content)) => Some(inlines::plain(content)), - Some(tree::Leaf::Code(text)) => Some(text.clone()), - None => None, - }) + .filter_map(|path| view.leaf_text(path)) .collect::>() .join("\n"); surface.widget_info(|| egui::WidgetInfo::labeled(egui::Role::MultilineTextInput, true, &label)); @@ -743,12 +776,17 @@ fn key_pressed( if let Some(shortcut) = images::key_pressed(view, key, modifiers) { return shortcut; } + let unit = if modifiers.command { + Unit::Word + } else { + Unit::Grapheme + }; match key { Key::Enter => view.change(Step::Other, edit::split), - Key::Backspace => view.change(Step::Other, edit::delete_backward), - Key::Delete => view.change(Step::Other, edit::delete_forward), - Key::ArrowLeft => view.step(false, modifiers.shift), - Key::ArrowRight => view.step(true, modifiers.shift), + Key::Backspace => view.delete(false, unit), + Key::Delete => view.delete(true, unit), + Key::ArrowLeft => view.step(false, modifiers.shift, unit), + Key::ArrowRight => view.step(true, modifiers.shift, unit), Key::ArrowUp => view.vertical(false, modifiers.shift), Key::ArrowDown => view.vertical(true, modifiers.shift), Key::Home | Key::End => line_edge(view, key == Key::End, modifiers), @@ -789,6 +827,7 @@ fn run_command(ui: &Ui, view: &mut RichEditor, command: shortcuts::Command) { /// Home and End: the line's edges; with Ctrl, the document's. fn line_edge(view: &mut RichEditor, end: bool, modifiers: Modifiers) { + view.goal_x = None; if modifiers.command { let leaves = tree::leaves(&view.document); let target = if end { leaves.last() } else { leaves.first() }; diff --git a/crates/ui/src/notes/overlays/editor/rich/tests.rs b/crates/ui/src/notes/overlays/editor/rich/tests.rs index f8e8c8c3d..fc32c64cb 100644 --- a/crates/ui/src/notes/overlays/editor/rich/tests.rs +++ b/crates/ui/src/notes/overlays/editor/rich/tests.rs @@ -865,3 +865,113 @@ fn shift_tab_takes_a_nested_item_back_from_the_middle_of_its_line() { click_id(&mut harness, "editor-close"); assert_eq!(stored(&harness, &id), "- one\n- tw-o"); } + +/// The text with `|` where the keys leave the caret. +fn after(content: &str, keys: &[(Modifiers, Key)]) -> String { + let (mut harness, _) = note(content); + at_end(&mut harness); + for (modifiers, key) in keys { + press(&mut harness, *modifiers, *key); + } + type_in(&mut harness, "|"); + surface_text(&harness) +} + +#[test] +fn ctrl_moves_and_deletes_by_word() { + let word = Modifiers::COMMAND; + let select = Modifiers::COMMAND | Modifiers::SHIFT; + for (keys, text) in [ + ( + vec![(word, Key::ArrowLeft)], + "Un mot ici +|fin" + .to_owned(), + ), + ( + vec![(word, Key::ArrowLeft), (word, Key::ArrowLeft)], + "Un mot ici| +fin" + .to_owned(), + ), + ( + vec![(word, Key::Home), (word, Key::ArrowRight)], + "Un| mot ici +fin" + .to_owned(), + ), + ( + vec![(word, Key::Backspace)], + "Un mot ici +|" + .to_owned(), + ), + ( + vec![(word, Key::Home), (word, Key::Delete)], + "| mot ici +fin" + .to_owned(), + ), + ( + vec![(select, Key::ArrowLeft)], + "Un mot ici +|" + .to_owned(), + ), + ] { + assert_eq!( + after( + "Un mot ici + +fin", + &keys + ), + text, + "{keys:?}" + ); + } +} + +/// A family is one character to whoever reads it, three and their joiners to the text. +#[test] +fn a_character_of_several_is_walked_and_deleted_whole() { + let family = "\u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}"; + let content = format!("a{family}b"); + let left = (Modifiers::NONE, Key::ArrowLeft); + + assert_eq!(after(&content, &[left, left]), format!("a|{family}b")); + assert_eq!( + after(&content, &[left, (Modifiers::NONE, Key::Backspace)]), + "a|b" + ); + assert_eq!( + after(&content, &[left, left, (Modifiers::NONE, Key::Delete)]), + "a|b" + ); +} + +/// From where End put it, not from where the caret once was. +#[test] +fn the_column_is_the_one_home_or_end_left() { + let down = (Modifiers::NONE, Key::ArrowDown); + let keys = [ + (Modifiers::COMMAND, Key::Home), + down, + (Modifiers::NONE, Key::End), + down, + ]; + + assert_eq!( + after( + "ab + +abcd + +abcdef", + &keys + ), + "ab +abcd +abcd|ef" + ); +} From 80addd4eed182d236d16dfefe37da85449849b65 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 13:37:29 +0100 Subject: [PATCH 80/95] Editor: the tag field keeps the focus after Enter (#1822) Co-authored-by: Claude Opus 5.5 --- crates/ui/src/notes/overlays/editor/header.rs | 2 ++ crates/ui/src/notes/overlays/editor/tests.rs | 23 +++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/crates/ui/src/notes/overlays/editor/header.rs b/crates/ui/src/notes/overlays/editor/header.rs index 7c002acaa..8c7fb4e58 100644 --- a/crates/ui/src/notes/overlays/editor/header.rs +++ b/crates/ui/src/notes/overlays/editor/header.rs @@ -149,6 +149,8 @@ fn tags( let hint = i18n::translate(language, keys::editor::ADD_TAG_PLACEHOLDER, &[]); let response = ui.add( egui::TextEdit::singleline(&mut editing.tag) + // Not its place, which the tag just added moves. + .id_salt("editor-tag-add") .hint_text(hint) .text_color(p.text_1) .font(egui::FontId::new(font::CONTROL, FontFamily::Proportional)) diff --git a/crates/ui/src/notes/overlays/editor/tests.rs b/crates/ui/src/notes/overlays/editor/tests.rs index 7b0cc4e83..04a5c64bc 100644 --- a/crates/ui/src/notes/overlays/editor/tests.rs +++ b/crates/ui/src/notes/overlays/editor/tests.rs @@ -911,3 +911,26 @@ fn expanded_without_room_for_the_details_the_header_holds_them() { assert!(rect_of(&harness, "editor-space").bottom() < rect_of(&harness, "editor-body").top()); } + +/// Enter keeps the field for the next one. +#[test] +fn tags_are_added_one_after_the_other() { + for expanded in [false, true] { + let (backend, profile) = testing::unlocked(); + let id = testing::note(&backend, "psql").id.clone(); + let mut harness = if expanded { + crate::notes::bench::expanded_area(backend, profile) + } else { + area(backend, profile) + }; + click_id(&mut harness, "note-card-open"); + click_id(&mut harness, "editor-tag-add"); + for tag in ["db", "ops", "api"] { + crate::notes::bench::type_and_enter(&mut harness, "editor-tag-add", tag); + } + + let mut tags = stored(&harness, &id).tags.clone(); + tags.sort(); + assert_eq!(tags, ["api", "db", "ops"], "expanded: {expanded}"); + } +} From b989c5ca4354e9ec85f72b643887ea356d1b3aec Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 13:48:10 +0100 Subject: [PATCH 81/95] Calc: an error that starts with a unit keeps its case (#1840) Co-authored-by: Claude Opus 5.5 --- crates/ui/src/notes/calc.rs | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/crates/ui/src/notes/calc.rs b/crates/ui/src/notes/calc.rs index 318829965..317e13cb2 100644 --- a/crates/ui/src/notes/calc.rs +++ b/crates/ui/src/notes/calc.rs @@ -295,7 +295,11 @@ pub fn error(error: &CalcError, language: Language) -> String { tr(kind.unwrap_or("unsupported"), &[]) } }; - capitalised(&text) + // A unit's case is its meaning: « m » is no « M ». + match error { + CalcError::Mismatch { unit: Some(_), .. } => text, + _ => capitalised(&text), + } } fn name_of(dimension: Dimension) -> String { @@ -612,6 +616,22 @@ mod tests { ); } + /// « m » is no « M ». + #[test] + fn an_error_that_starts_with_a_unit_keeps_its_case() { + let metre = CalcUnit { + unit: UnitId::Metre, + per: None, + }; + let wrong = CalcError::Mismatch { + expected: Dimension::Time, + found: Dimension::Length, + unit: Some(metre), + }; + + assert_eq!(error(&wrong, Language::En), "m is not a duration"); + } + #[test] fn the_word_typed_is_the_letters_before_the_caret() { assert_eq!(typed_word("3 + aujourd’h"), "aujourd’h"); From 988c9729d2e3aa1550ee7a6d62a174e7285c1348 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:32:13 +0100 Subject: [PATCH 82/95] Notes: a drag selects from where it was pressed (#1826) * Notes: a drag selects from where it was pressed Co-Authored-By: Claude Opus 5.5 * Notes: the press of a drag Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/ui/src/notes/overlays/editor/rich.rs | 4 ++- .../src/notes/overlays/editor/rich/tests.rs | 28 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/ui/src/notes/overlays/editor/rich.rs b/crates/ui/src/notes/overlays/editor/rich.rs index ca60f0a3e..afc0982be 100644 --- a/crates/ui/src/notes/overlays/editor/rich.rs +++ b/crates/ui/src/notes/overlays/editor/rich.rs @@ -612,6 +612,8 @@ fn pointer(ui: &Ui, view: &mut RichEditor, surface: &egui::Response) { return; }; let shift = ui.input(|input| input.modifiers.shift); + // A drag is known as one once the pointer left where it was pressed. + let pressed = ui.input(|input| input.pointer.press_origin()).unwrap_or(at); // egui reports the click of a double click too, and both of a triple: the longest first. if surface.triple_clicked() && let Some(position) = view.position_at(at) @@ -624,7 +626,7 @@ fn pointer(ui: &Ui, view: &mut RichEditor, surface: &egui::Response) { view.select_word(position, shift); surface.request_focus(); } else if (surface.drag_started() || surface.clicked()) - && let Some(position) = view.position_at(at) + && let Some(position) = view.position_at(pressed) { view.move_head(position, shift); view.goal_x = None; diff --git a/crates/ui/src/notes/overlays/editor/rich/tests.rs b/crates/ui/src/notes/overlays/editor/rich/tests.rs index fc32c64cb..3fc463954 100644 --- a/crates/ui/src/notes/overlays/editor/rich/tests.rs +++ b/crates/ui/src/notes/overlays/editor/rich/tests.rs @@ -866,6 +866,34 @@ fn shift_tab_takes_a_nested_item_back_from_the_middle_of_its_line() { assert_eq!(stored(&harness, &id), "- one\n- tw-o"); } +/// A drag is known as one once the pointer left where it pressed: fast, some words further. +#[test] +fn a_drag_selects_from_where_it_was_pressed() { + let (mut harness, _) = note("hello world"); + let from = point_in(&harness, "hello world", 0); + let to = point_in(&harness, "hello world", 5); + let button = |pos, pressed| egui::Event::PointerButton { + pos, + button: egui::PointerButton::Primary, + pressed, + modifiers: Modifiers::NONE, + }; + harness.event(egui::Event::PointerMoved(from)); + harness.event(button(from, true)); + harness.step(); + for part in 1..=4_u8 { + harness.event(egui::Event::PointerMoved( + from.lerp(to, f32::from(part) / 4.0), + )); + harness.step(); + } + harness.event(button(to, false)); + settle(&mut harness); + type_in(&mut harness, "bye"); + + assert_eq!(surface_text(&harness), "bye world"); +} + /// The text with `|` where the keys leave the caret. fn after(content: &str, keys: &[(Modifiers, Key)]) -> String { let (mut harness, _) = note(content); From 5214cd4fb6426b1ce178319de56cda3722869758 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:32:21 +0100 Subject: [PATCH 83/95] HTTP: an inherited auth set to None says so (#1828) Co-authored-by: Claude Opus 5.5 --- crates/ui/src/http/request/auth.rs | 11 +++- crates/ui/src/http/request/auth/tests.rs | 76 ++++++++++++++++++++++++ 2 files changed, 84 insertions(+), 3 deletions(-) create mode 100644 crates/ui/src/http/request/auth/tests.rs diff --git a/crates/ui/src/http/request/auth.rs b/crates/ui/src/http/request/auth.rs index fac9a2fbc..126d6c667 100644 --- a/crates/ui/src/http/request/auth.rs +++ b/crates/ui/src/http/request/auth.rs @@ -238,7 +238,7 @@ fn secret( } /// « Bearer {{accessToken}} », the secret masked unless it is a variable. -fn summary(auth: &RequestAuth) -> String { +fn summary(auth: &RequestAuth, language: i18n::Language) -> String { let secret = |value: &str| { let whole = api::http::spans(value) .first() @@ -253,7 +253,9 @@ fn summary(auth: &RequestAuth) -> String { RequestAuth::Basic { username, .. } => format!("Basic {username}"), RequestAuth::Bearer { token } => format!("Bearer {}", secret(token)), RequestAuth::ApiKey { name, value, .. } => format!("{name}: {}", secret(value)), - RequestAuth::Inherit | RequestAuth::None => String::new(), + RequestAuth::Inherit | RequestAuth::None => { + i18n::translate(language, keys::http::auth::kinds::NONE, &[]) + } } } @@ -278,7 +280,7 @@ fn inherited_words(above: &Inherited, language: i18n::Language) -> String { _ => keys::http::auth::from::COLLECTION, }; let origin = i18n::translate(language, key, &[("name", from.name.as_str().into())]); - format!("{} {origin}", summary(&above.auth)) + format!("{} {origin}", summary(&above.auth, language)) } fn hint(ui: &mut Ui, words: &str) { @@ -286,3 +288,6 @@ fn hint(ui: &mut Ui, words: &str) { let words = egui::RichText::new(words).size(font::LABEL).color(p.text_2); ui.add(egui::Label::new(words).wrap()); } + +#[cfg(test)] +mod tests; diff --git a/crates/ui/src/http/request/auth/tests.rs b/crates/ui/src/http/request/auth/tests.rs new file mode 100644 index 000000000..22065a74b --- /dev/null +++ b/crates/ui/src/http/request/auth/tests.rs @@ -0,0 +1,76 @@ +//! A request's auth, and what « Inherited » says it takes. + +use engine::http::model::{ContainerSettings, HttpItemKind}; +use engine::http::settings::{HttpOrigin, inherit}; +use i18n::Language; + +use super::*; + +fn above(kind: HttpItemKind, auth: RequestAuth) -> Inherited { + let origin = HttpOrigin { + kind, + id: "id".to_owned(), + name: "API".to_owned(), + }; + let settings = ContainerSettings { + auth, + ..ContainerSettings::default() + }; + inherit(&[(origin, settings)]) +} + +/// The secret masked, a variable named. +#[test] +fn what_is_inherited_is_said_with_where_from() { + let bearer = |token: &str| RequestAuth::Bearer { + token: token.to_owned(), + }; + let key = RequestAuth::ApiKey { + name: "X-Key".to_owned(), + value: "s3cret".to_owned(), + place: KeyPlace::Header, + }; + let basic = RequestAuth::Basic { + username: "ada".to_owned(), + password: "s3cret".to_owned(), + }; + for (kind, auth, words) in [ + ( + HttpItemKind::Collection, + bearer("s3cret"), + "Bearer •••••• inherited from the collection API", + ), + ( + HttpItemKind::Folder, + bearer("{{token}}"), + "Bearer {{token}} inherited from the folder API", + ), + ( + HttpItemKind::Folder, + bearer("x{{token}}"), + "Bearer •••••• inherited from the folder API", + ), + ( + HttpItemKind::Collection, + key, + "X-Key: •••••• inherited from the collection API", + ), + ( + HttpItemKind::Collection, + basic, + "Basic ada inherited from the collection API", + ), + ( + HttpItemKind::Folder, + RequestAuth::None, + "None inherited from the folder API", + ), + ] { + assert_eq!(inherited_words(&above(kind, auth), Language::En), words); + } + let nothing = inherit(&[]); + assert_eq!( + inherited_words(¬hing, Language::En), + "Nothing above sets an auth: none is sent." + ); +} From ae748a62f56064d206ea8da8fa65c6f5d1204803 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:32:30 +0100 Subject: [PATCH 84/95] Interface: unit tests rewritten for the widgets (#1838) Co-authored-by: Claude Opus 5.5 --- crates/ui/src/widgets/date.rs | 168 ++++ crates/ui/src/widgets/editor/tests.rs | 613 ++++++++++-- crates/ui/src/widgets/json_explorer/graph.rs | 6 +- crates/ui/src/widgets/json_explorer/mod.rs | 2 + crates/ui/src/widgets/json_explorer/tests.rs | 121 +-- .../src/widgets/json_explorer/view_tests.rs | 908 ++++++++++++++++++ crates/ui/src/widgets/layout.rs | 20 + crates/ui/src/widgets/menu.rs | 13 + crates/ui/src/widgets/picker.rs | 27 + crates/ui/src/widgets/rich.rs | 145 +-- crates/ui/src/widgets/rich/tests.rs | 625 ++++++++++++ crates/ui/src/widgets/tests.rs | 125 +++ 12 files changed, 2406 insertions(+), 367 deletions(-) create mode 100644 crates/ui/src/widgets/json_explorer/view_tests.rs create mode 100644 crates/ui/src/widgets/rich/tests.rs diff --git a/crates/ui/src/widgets/date.rs b/crates/ui/src/widgets/date.rs index 6de7c524c..7e373f4e9 100644 --- a/crates/ui/src/widgets/date.rs +++ b/crates/ui/src/widgets/date.rs @@ -348,4 +348,172 @@ mod tests { NaiveDate::from_ymd_opt(2026, 3, 8).unwrap() ); } + + use egui_kittest::Harness; + use egui_kittest::kittest::{NodeT, Queryable}; + + struct Screen { + value: Option, + picked: Option, + } + + fn day(month: u32, day: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(2026, month, day).unwrap() + } + + fn field(value: Option) -> Harness<'static, Screen> { + let screen = Screen { + value, + picked: None, + }; + let mut harness = crate::testing::harness() + .with_size(egui::vec2(700.0, 600.0)) + .build_ui_state( + |ui, screen: &mut Screen| { + let field = DateField::new(screen.value, day(3, 10), "Échéance", "date"); + if let Some(picked) = field.show(ui) { + screen.picked = Some(picked); + } + }, + screen, + ); + harness.run(); + harness + } + + fn click(harness: &mut Harness<'_, Screen>, author_id: &str) { + harness + .get_by(|node| node.author_id() == Some(author_id)) + .click(); + harness.run(); + harness.run(); + } + + fn press(harness: &mut Harness<'_, Screen>, key: Key) { + harness.key_press(key); + harness.run(); + } + + fn opened(value: Option) -> Harness<'static, Screen> { + let mut harness = field(value); + click(&mut harness, "date"); + harness + } + + fn days(harness: &Harness<'_, Screen>) -> Vec { + harness + .query_all_by(|node| node.author_id() == Some("date-day")) + .map(|node| node.accesskit_node().label().unwrap_or_default()) + .collect() + } + + #[test] + fn it_shows_its_day_or_that_there_is_none() { + assert!( + crate::testing::painted(&field(Some(day(3, 4)))).contains(&"2026-03-04".to_owned()) + || crate::testing::painted(&field(Some(day(3, 4)))) + .iter() + .any(|words| words.contains("2026")) + ); + assert!( + !crate::testing::painted(&field(None)) + .iter() + .any(|words| words.contains("2026")) + ); + } + + /// Six weeks from Monday, the days around the month drawn too. + #[test] + fn a_month_is_six_weeks_from_the_monday_that_holds_its_first() { + let harness = opened(Some(day(3, 4))); + let days = days(&harness); + + assert_eq!(days.len(), 42); + assert!( + days[0].contains("23") && days[0].contains("February"), + "{}", + days[0] + ); + } + + #[test] + fn it_opens_on_its_day_or_on_today() { + for (value, start) in [(Some(day(7, 14)), day(7, 14)), (None, day(3, 10))] { + let mut harness = opened(value); + press(&mut harness, Key::Enter); + assert_eq!(harness.state().picked, Some(Picked::Day(start))); + } + } + + #[test] + fn the_arrows_move_the_day_enter_takes() { + for (keys, taken) in [ + (vec![Key::ArrowRight], day(3, 11)), + (vec![Key::ArrowLeft, Key::ArrowLeft], day(3, 8)), + (vec![Key::ArrowDown, Key::ArrowDown], day(3, 24)), + (vec![Key::ArrowUp, Key::ArrowUp], day(2, 24)), + ] { + let mut harness = opened(None); + for key in &keys { + press(&mut harness, *key); + } + press(&mut harness, Key::Enter); + assert_eq!(harness.state().picked, Some(Picked::Day(taken)), "{keys:?}"); + } + } + + #[test] + fn a_day_clicked_is_taken_and_closes_the_month() { + let mut harness = opened(Some(day(3, 4))); + let wanted = days(&harness)[10].clone(); + harness + .get_by(|node| { + node.author_id() == Some("date-day") + && node.label().as_deref() == Some(wanted.as_str()) + }) + .click(); + harness.run(); + harness.run(); + + assert_eq!(harness.state().picked, Some(Picked::Day(day(3, 5)))); + assert!(days(&harness).is_empty()); + } + + #[test] + fn the_months_before_and_after_are_one_click_away() { + for (button, taken) in [("date-previous", day(2, 28)), ("date-next", day(4, 30))] { + let mut harness = opened(Some(day(3, 31))); + click(&mut harness, button); + press(&mut harness, Key::Enter); + let picked = harness.state().picked; + assert_eq!(picked, Some(Picked::Day(taken)), "{button}"); + } + } + + #[test] + fn the_day_is_taken_off_by_its_button_and_by_either_key() { + let mut harness = opened(Some(day(3, 4))); + click(&mut harness, "date-clear"); + assert_eq!(harness.state().picked, Some(Picked::Cleared)); + + for key in [Key::Delete, Key::Backspace] { + let mut harness = field(Some(day(3, 4))); + harness + .get_by(|node| node.author_id() == Some("date")) + .focus(); + harness.run(); + press(&mut harness, key); + assert_eq!(harness.state().picked, Some(Picked::Cleared), "{key:?}"); + } + } + + #[test] + fn escape_closes_the_month_and_takes_nothing() { + let mut harness = opened(Some(day(3, 4))); + press(&mut harness, Key::ArrowRight); + press(&mut harness, Key::Escape); + + assert!(days(&harness).is_empty()); + assert_eq!(harness.state().picked, None); + } } diff --git a/crates/ui/src/widgets/editor/tests.rs b/crates/ui/src/widgets/editor/tests.rs index 5846c4c12..6f00b43bd 100644 --- a/crates/ui/src/widgets/editor/tests.rs +++ b/crates/ui/src/widgets/editor/tests.rs @@ -10,6 +10,9 @@ struct Screen { changed: Vec, read_only: bool, wrap: bool, + comment: Option<&'static str>, + /// The keys the text left to the rest of the window. + left: Vec, } fn screen(text: &str) -> Harness<'static, Screen> { @@ -18,6 +21,8 @@ fn screen(text: &str) -> Harness<'static, Screen> { changed: Vec::new(), read_only: false, wrap: false, + comment: Some("#"), + left: Vec::new(), }; crate::testing::harness() .with_size(egui::vec2(600.0, 300.0)) @@ -25,11 +30,20 @@ fn screen(text: &str) -> Harness<'static, Screen> { |ui, screen: &mut Screen| { let output = EditorView::new(&mut screen.editor, "Code", "code") .indent_unit(" ") - .comment(Some("#")) + .comment(screen.comment) .read_only(screen.read_only) .wrap(screen.wrap) .show(ui); screen.changed.extend(output.changed); + let left = ui.input(|input| input.events.clone()); + screen + .left + .extend(left.iter().filter_map(|event| match event { + Event::Key { + key, pressed: true, .. + } => Some(*key), + _ => None, + })); }, state, ) @@ -75,145 +89,544 @@ fn typing_goes_into_the_text_and_says_from_which_line() { assert_eq!(value, "a\nbc"); } -#[test] -fn tab_stays_in_the_text_and_shift_tab_takes_it_back() { - let mut harness = screen("x"); +const NONE: Modifiers = Modifiers::NONE; +const SHIFT: Modifiers = Modifiers::SHIFT; +const ALT: Modifiers = Modifiers::ALT; +const CTRL: Modifiers = Modifiers::COMMAND; + +fn select(harness: &mut Harness<'_, Screen>, anchor: usize, head: usize) { + let selection = text::Selection { anchor, head }; + harness.state_mut().editor.buffer.select(selection); +} + +/// The text of `before` with `|` at the caret, `[` and `]` around what is selected. +fn marked(before: &str) -> (String, usize, usize) { + let mut plain = String::new(); + let (mut anchor, mut head) = (None, None); + for c in before.chars() { + match c { + '[' => anchor = Some(plain.chars().count()), + ']' | '|' => head = Some(plain.chars().count()), + c => plain.push(c), + } + } + let head = head.unwrap_or_default(); + (plain, anchor.unwrap_or(head), head) +} + +fn opened_at(before: &str) -> Harness<'static, Screen> { + let (plain, anchor, head) = marked(before); + let mut harness = screen(&plain); focus(&mut harness); - harness.state_mut().editor.buffer.move_to(0, false); - press(&mut harness, Modifiers::NONE, Key::Tab); - assert_eq!(text(&harness), " x"); - assert!( - harness - .get_by(|node| node.author_id() == Some("code")) - .is_focused(), - "the focus did not move on" - ); - press(&mut harness, Modifiers::SHIFT, Key::Tab); - assert_eq!(text(&harness), "x"); + select(&mut harness, anchor, head); + harness } +fn assert_shows(harness: &Harness<'_, Screen>, after: &str, why: &str) { + let (plain, anchor, head) = marked(after); + let selection = harness.state().editor.buffer.selection(); + let found = (text(harness), selection.anchor, selection.head); + assert_eq!(found, (plain, anchor, head), "{why}"); +} + +// The keys + #[test] -fn enter_keeps_the_indentation_of_the_line() { - let mut harness = screen(" if x:"); - focus(&mut harness); - harness.state_mut().editor.buffer.move_to(7, false); - press(&mut harness, Modifiers::NONE, Key::Enter); - assert_eq!(text(&harness), " if x:\n "); +fn the_keys_move_the_caret() { + for (modifiers, key, before, after) in [ + (NONE, Key::ArrowLeft, "ab|c", "a|bc"), + (NONE, Key::ArrowRight, "a|bc", "ab|c"), + (NONE, Key::ArrowLeft, "a[bc]d", "a|bcd"), + (NONE, Key::ArrowRight, "a[bc]d", "abc|d"), + (CTRL, Key::ArrowLeft, "one two|", "one |two"), + (CTRL, Key::ArrowRight, "|one two", "one| two"), + (NONE, Key::ArrowUp, "abc\nab|c", "ab|c\nabc"), + (NONE, Key::ArrowDown, "ab|c\nabc", "abc\nab|c"), + (NONE, Key::ArrowUp, "ab|c\nabc", "|abc\nabc"), + (NONE, Key::ArrowDown, "abc\na|bc", "abc\nabc|"), + (NONE, Key::Home, " ab|c", " |abc"), + (NONE, Key::Home, " |abc", "| abc"), + (NONE, Key::Home, "| abc", " |abc"), + (NONE, Key::End, "a|bc\nd", "abc|\nd"), + (CTRL, Key::Home, "abc\nd|e", "|abc\nde"), + (CTRL, Key::End, "a|bc\nde", "abc\nde|"), + (CTRL, Key::A, "a|b\nc", "[ab\nc]"), + ] { + let mut harness = opened_at(before); + press(&mut harness, modifiers, key); + assert_shows(&harness, after, &format!("{key:?} in {before:?}")); + assert!( + harness.state().changed.is_empty(), + "{key:?} changed nothing" + ); + } } #[test] -fn shift_arrows_select_and_backspace_takes_the_selection() { - let mut harness = screen("hello world"); - focus(&mut harness); - harness.state_mut().editor.buffer.move_to(11, false); - press( - &mut harness, - Modifiers::SHIFT | Modifiers::COMMAND, - Key::ArrowLeft, - ); - assert_eq!(harness.state().editor.buffer.selected_text(), "world"); - press(&mut harness, Modifiers::NONE, Key::Backspace); - assert_eq!(text(&harness), "hello "); - press(&mut harness, Modifiers::COMMAND, Key::Z); - assert_eq!(text(&harness), "hello world"); +fn shift_stretches_the_selection_to_where_the_key_goes() { + for (modifiers, key, before, after) in [ + (SHIFT, Key::ArrowRight, "a|bc", "a[b]c"), + (SHIFT, Key::ArrowRight, "a[b]c", "a[bc]"), + (SHIFT, Key::ArrowDown, "a|bc\nabc", "a[bc\na]bc"), + (SHIFT, Key::End, "a|bc", "a[bc]"), + (SHIFT | CTRL, Key::ArrowRight, "|one two", "[one] two"), + (SHIFT | CTRL, Key::End, "a|b\nc", "a[b\nc]"), + ] { + let mut harness = opened_at(before); + press(&mut harness, modifiers, key); + assert_shows(&harness, after, &format!("{key:?} in {before:?}")); + } +} + +#[test] +fn the_keys_edit_the_text() { + for (modifiers, key, before, after) in [ + (NONE, Key::Backspace, "ab|c", "a|c"), + (NONE, Key::Delete, "a|bc", "a|c"), + (NONE, Key::Backspace, "a[bc]d", "a|d"), + (CTRL, Key::Backspace, "one two|", "one |"), + (CTRL, Key::Delete, "|one two", "| two"), + (CTRL | SHIFT, Key::K, "one\nt|wo\nthree", "one\n|three"), + (NONE, Key::Enter, " if x:|", " if x:\n |"), + (NONE, Key::Enter, " | x", " \n | x"), + (NONE, Key::Tab, "|x", " |x"), + (SHIFT, Key::Tab, " |x", "|x"), + (ALT, Key::ArrowUp, "a\nb|", "b|\na"), + (ALT, Key::ArrowDown, "|a\nb", "b\n|a"), + (CTRL, Key::Slash, "a|b", "# a|b"), + ] { + let mut harness = opened_at(before); + press(&mut harness, modifiers, key); + assert_shows(&harness, after, &format!("{key:?} in {before:?}")); + assert!( + !harness.state().changed.is_empty(), + "{key:?} said the change" + ); + } +} + +#[test] +fn what_is_undone_is_redone_by_either_key() { + for (modifiers, key) in [(CTRL, Key::Y), (CTRL | SHIFT, Key::Z)] { + let mut harness = opened_at("ab|"); + press(&mut harness, NONE, Key::Backspace); + press(&mut harness, CTRL, Key::Z); + assert_eq!(text(&harness), "ab"); + press(&mut harness, modifiers, key); + assert_eq!(text(&harness), "a", "{key:?}"); + } } #[test] fn up_and_down_keep_the_column_across_a_short_line() { - let mut harness = screen("abcdef\nab\nabcdef"); - focus(&mut harness); - harness.state_mut().editor.buffer.move_to(5, false); - press(&mut harness, Modifiers::NONE, Key::ArrowDown); - assert_eq!(caret(&harness), 9, "the short line's end"); - press(&mut harness, Modifiers::NONE, Key::ArrowDown); - assert_eq!(caret(&harness), 15, "back to column 5"); - press(&mut harness, Modifiers::NONE, Key::Home); - assert_eq!(caret(&harness), 10); - press(&mut harness, Modifiers::NONE, Key::End); - assert_eq!(caret(&harness), 16); - press(&mut harness, Modifiers::COMMAND, Key::Home); - assert_eq!(caret(&harness), 0); + let mut harness = opened_at("abcde|f\nab\nabcdef"); + press(&mut harness, NONE, Key::ArrowDown); + assert_shows(&harness, "abcdef\nab|\nabcdef", "the short line's end"); + press(&mut harness, NONE, Key::ArrowDown); + assert_shows(&harness, "abcdef\nab\nabcde|f", "back to its column"); } +/// The column is where the last move or the last edit left the caret, not where it once was. #[test] -fn alt_arrows_move_the_line_and_ctrl_slash_comments_it() { - let mut harness = screen("a\nb"); - focus(&mut harness); - harness.state_mut().editor.buffer.move_to(2, false); - press(&mut harness, Modifiers::ALT, Key::ArrowUp); - assert_eq!(text(&harness), "b\na"); - press(&mut harness, Modifiers::COMMAND, Key::Slash); - assert_eq!(text(&harness), "# b\na"); +fn a_move_or_an_edit_between_two_lines_forgets_the_column() { + for (key, lands) in [(Key::ArrowLeft, 8), (Key::End, 9), (Key::Backspace, 8)] { + let mut harness = opened_at("abcde|f\nab\nabcdef"); + press(&mut harness, NONE, Key::ArrowDown); + press(&mut harness, NONE, key); + assert_eq!(caret(&harness), lands, "{key:?}"); + press(&mut harness, NONE, Key::ArrowDown); + let line = harness.state().editor.buffer.line_start(2); + let column = lands - 7; + assert_eq!(caret(&harness) - line, column, "{key:?}"); + } } #[test] -fn a_composition_shows_until_it_commits_and_only_the_commit_is_typed() { - let mut harness = screen(""); - focus(&mut harness); - harness.event(Event::Ime(ImeEvent::Preedit { - text: "e".into(), - active_range_chars: None, - })); +fn a_page_goes_as_far_as_the_text_shown() { + let lines: Vec = (0..200).map(|n| format!("line {n}")).collect(); + let mut harness = opened_at(&format!("|{}", lines.join("\n"))); + let page = harness.state().editor.visible_lines().len(); + let line = + |harness: &Harness<'_, Screen>| harness.state().editor.buffer.line_of(caret(harness)); + press(&mut harness, NONE, Key::PageDown); + let down = line(&harness); + assert!(down + 3 > page && down <= page, "{down} of {page}"); + + press(&mut harness, NONE, Key::PageUp); + assert_eq!(line(&harness), 0); + press(&mut harness, SHIFT, Key::PageDown); + assert!(!harness.state().editor.buffer.selection().is_empty()); +} + +/// Ctrl+Z is the text's and Ctrl+S the window's (D14). +#[test] +fn a_key_the_text_takes_is_not_left_to_the_window() { + let mut harness = opened_at("ab|"); + for (modifiers, key, left) in [ + (CTRL, Key::Z, false), + (NONE, Key::ArrowLeft, false), + (NONE, Key::Tab, false), + (CTRL, Key::Slash, false), + (CTRL, Key::S, true), + (CTRL, Key::Enter, true), + (CTRL, Key::ArrowDown, true), + (ALT, Key::ArrowLeft, true), + (CTRL, Key::K, true), + ] { + harness.state_mut().left.clear(); + press(&mut harness, modifiers, key); + assert_eq!( + harness.state().left.contains(&key), + left, + "{modifiers:?} {key:?}" + ); + } +} + +#[test] +fn with_no_comment_to_put_ctrl_slash_is_left_to_the_window() { + let mut harness = opened_at("ab|"); + harness.state_mut().comment = None; + press(&mut harness, CTRL, Key::Slash); + + assert_eq!(text(&harness), "ab"); + assert!(harness.state().left.contains(&Key::Slash)); +} + +/// Not the next control: the focus stays in the text. +#[test] +fn tab_keeps_the_focus_in_the_text() { + let mut harness = opened_at("|x"); + press(&mut harness, NONE, Key::Tab); + + let code = harness.get_by(|node| node.author_id() == Some("code")); + assert!(code.is_focused()); +} + +#[test] +fn what_is_not_focused_takes_no_key() { + let mut harness = screen("abc"); + harness.event(Event::Text("x".into())); + press(&mut harness, NONE, Key::Delete); + + assert_eq!(text(&harness), "abc"); +} + +// Read only + +#[test] +fn a_read_only_text_takes_no_change() { + for (modifiers, key) in [ + (NONE, Key::Backspace), + (NONE, Key::Delete), + (CTRL | SHIFT, Key::K), + (NONE, Key::Enter), + (NONE, Key::Tab), + (SHIFT, Key::Tab), + (ALT, Key::ArrowUp), + (CTRL, Key::Slash), + (CTRL, Key::Z), + (CTRL, Key::Y), + ] { + let mut harness = opened_at(" a\n b|\n c"); + harness.state_mut().read_only = true; + press(&mut harness, modifiers, key); + assert_eq!(text(&harness), " a\n b\n c", "{key:?}"); + } + let mut harness = opened_at("a[b]c"); + harness.state_mut().read_only = true; + for event in [ + Event::Text("x".into()), + Event::Paste("x".into()), + Event::Cut, + Event::Ime(ImeEvent::Commit("x".into())), + Event::Ime(ImeEvent::DeleteSurrounding { + before_chars: 1, + after_chars: 0, + }), + ] { + harness.event(event.clone()); + harness.run(); + assert_eq!(text(&harness), "abc", "{event:?}"); + } +} + +#[test] +fn a_read_only_text_is_walked_and_selected() { + let mut harness = opened_at("|abc"); + harness.state_mut().read_only = true; + press(&mut harness, NONE, Key::ArrowRight); + assert_eq!(caret(&harness), 1); + press(&mut harness, CTRL, Key::A); + assert_eq!(harness.state().editor.buffer.selected_text(), "abc"); +} + +// The clipboard + +/// What the frames of `event` put on the clipboard. +fn copied(harness: &mut Harness<'_, Screen>, event: Event) -> Option { + harness.event(event); + harness.step(); + let commands = &harness.output().platform_output.commands; + commands.iter().find_map(|command| match command { + egui::OutputCommand::CopyText(text) => Some(text.clone()), + _ => None, + }) +} + +#[test] +fn a_copy_takes_what_is_selected_and_leaves_it() { + let mut harness = opened_at("a[bc]d"); + assert_eq!(copied(&mut harness, Event::Copy).as_deref(), Some("bc")); + assert_shows(&harness, "a[bc]d", "left"); +} + +#[test] +fn a_cut_takes_what_is_selected_out() { + let mut harness = opened_at("x\na[bc]d"); + assert_eq!(copied(&mut harness, Event::Cut).as_deref(), Some("bc")); harness.run(); - assert_eq!(text(&harness), ""); - assert_eq!(harness.state().editor.preedit, "e"); - harness.event(Event::Ime(ImeEvent::Commit("ê".into()))); + assert_shows(&harness, "x\na|d", "out"); + assert_eq!(harness.state().changed, [1]); +} + +/// The clipboard keeps what it holds. +#[test] +fn with_nothing_selected_there_is_nothing_to_copy_or_cut() { + for event in [Event::Copy, Event::Cut] { + let mut harness = opened_at("ab|c"); + assert_eq!(copied(&mut harness, event.clone()), None, "{event:?}"); + assert_eq!(text(&harness), "abc", "{event:?}"); + } +} + +#[test] +fn a_paste_replaces_what_is_selected() { + let mut harness = opened_at("a[bc]d"); + harness.event(Event::Paste("X\nY".into())); + harness.run(); + + assert_shows(&harness, "aX\nY|d", "pasted"); +} + +// The input method + +fn ime(harness: &mut Harness<'_, Screen>, event: ImeEvent) { + harness.event(Event::Ime(event)); harness.run(); +} + +fn preedit(words: &str) -> ImeEvent { + ImeEvent::Preedit { + text: words.into(), + active_range_chars: None, + } +} + +#[test] +fn a_composition_is_drawn_and_only_its_commit_is_typed() { + let mut harness = opened_at("|"); + ime(&mut harness, preedit("e")); + assert_eq!(text(&harness), ""); + assert!(crate::testing::painted(&harness).contains(&"e".to_owned())); + + ime(&mut harness, ImeEvent::Commit("ê".into())); assert_eq!(text(&harness), "ê"); assert!(harness.state().editor.preedit.is_empty()); } #[test] -fn a_focused_editor_asks_for_the_input_method_at_its_caret() { - let mut harness = screen("abc"); - focus(&mut harness); - let ime = harness.output().platform_output.ime; - assert!(ime.is_some()); +fn a_composition_given_up_types_nothing() { + let mut harness = opened_at("|"); + ime(&mut harness, preedit("e")); + ime(&mut harness, preedit("")); + assert!(harness.state().editor.preedit.is_empty()); + + ime(&mut harness, ImeEvent::Commit(String::new())); + assert!(text(&harness).is_empty() && harness.state().changed.is_empty()); } #[test] -fn a_read_only_text_moves_and_selects_but_takes_no_typing() { - let mut harness = screen("abc"); - harness.state_mut().read_only = true; - focus(&mut harness); - harness - .get_by(|node| node.author_id() == Some("code")) - .type_text("x"); - press(&mut harness, Modifiers::NONE, Key::Backspace); - press(&mut harness, Modifiers::COMMAND, Key::A); - assert_eq!(text(&harness), "abc"); - assert_eq!(harness.state().editor.buffer.selected_text(), "abc"); +fn the_input_method_takes_out_what_is_around_the_caret() { + for (before_chars, after_chars, after) in + [(1, 0, "a|cd"), (0, 1, "ab|d"), (2, 1, "|d"), (9, 9, "|")] + { + let mut harness = opened_at("ab|cd"); + ime( + &mut harness, + ImeEvent::DeleteSurrounding { + before_chars, + after_chars, + }, + ); + assert_shows( + &harness, + after, + &format!("{before_chars} and {after_chars}"), + ); + } +} + +// The pointer + +fn pointer(harness: &mut Harness<'_, Screen>, at: egui::Pos2, pressed: bool, modifiers: Modifiers) { + harness.event(Event::PointerMoved(at)); + harness.event(Event::ModifiersChanged(modifiers)); + harness.event(Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed, + modifiers, + }); + harness.run(); +} + +fn click(harness: &mut Harness<'_, Screen>, at: egui::Pos2, modifiers: Modifiers) { + pointer(harness, at, true, modifiers); + pointer(harness, at, false, modifiers); + harness.event(Event::ModifiersChanged(NONE)); } #[test] -fn the_context_menu_selects_all() { - let mut harness = screen("one two"); - harness - .get_by(|node| node.author_id() == Some("code")) - .click_secondary(); +fn a_press_puts_the_caret_on_the_nearer_side_of_the_character() { + for (part, at) in [(0.2, 2), (0.8, 3)] { + let mut harness = screen("abcdef"); + harness.run(); + let pointed = point(&harness, "abcdef", 2, part); + click(&mut harness, pointed, NONE); + assert_eq!(caret(&harness), at, "{part}"); + assert!(harness.state().editor.buffer.selection().is_empty()); + } +} + +#[test] +fn a_press_with_shift_stretches_the_selection_to_it() { + let mut harness = opened_at("a|bcdef"); + let pointed = point(&harness, "abcdef", 4, 0.1); + click(&mut harness, pointed, SHIFT); + + assert_shows(&harness, "a[bcd]ef", "stretched"); +} + +#[test] +fn a_drag_selects_from_where_it_was_pressed() { + let mut harness = screen("abcdef\nsecond"); harness.run(); + let from = point(&harness, "abcdef", 1, 0.1); + let to = point(&harness, "second", 3, 0.1); + pointer(&mut harness, from, true, NONE); + harness.event(Event::PointerMoved(to)); + harness.run(); + pointer(&mut harness, to, false, NONE); + + assert_shows(&harness, "a[bcdef\nsec]ond", "dragged"); +} + +/// Below the last line is the end of it, above the text its start. +#[test] +fn a_press_under_the_text_is_on_its_last_line() { + let mut harness = screen("abc\ndef"); + harness.run(); + click(&mut harness, egui::pos2(300.0, 250.0), NONE); + + assert_eq!(caret(&harness), 7); +} + +// The menu + +fn menu_of(harness: &mut Harness<'_, Screen>) { + let code = harness.get_by(|node| node.author_id() == Some("code")); + code.click_secondary(); + harness.run(); +} + +fn choose(harness: &mut Harness<'_, Screen>, entry: &str) { harness - .get_by(|node| node.author_id() == Some("editor-menu-select-all")) + .get_by(|node| node.author_id() == Some(entry)) .click(); + harness.step(); + harness.step(); +} + +fn offered(harness: &Harness<'_, Screen>) -> Vec { + harness + .query_all_by(|node| { + node.author_id() + .is_some_and(|id| id.starts_with("editor-menu-")) + }) + .filter_map(|node| node.accesskit_node().author_id().map(str::to_owned)) + .collect() +} + +#[test] +fn the_menu_offers_what_the_text_takes() { + for (read_only, entries) in [ + ( + false, + vec![ + "editor-menu-cut", + "editor-menu-copy", + "editor-menu-paste", + "editor-menu-select-all", + ], + ), + (true, vec!["editor-menu-copy", "editor-menu-select-all"]), + ] { + let mut harness = screen("abc"); + harness.state_mut().read_only = read_only; + menu_of(&mut harness); + assert_eq!(offered(&harness), entries); + } +} + +#[test] +fn the_menu_copies_and_cuts_what_is_selected() { + for (entry, after) in [("editor-menu-copy", "a[bc]d"), ("editor-menu-cut", "a|d")] { + let mut harness = opened_at("a[bc]d"); + menu_of(&mut harness); + choose(&mut harness, entry); + harness.run(); + assert_shows(&harness, after, entry); + } +} + +#[test] +fn the_menu_asks_the_window_for_what_to_paste() { + let mut harness = opened_at("ab|"); + menu_of(&mut harness); + harness + .get_by(|node| node.author_id() == Some("editor-menu-paste")) + .click(); + let mut asked = false; + for _ in 0..4 { + harness.step(); + asked |= harness.output().viewport_output.values().any(|viewport| { + viewport + .commands + .contains(&egui::ViewportCommand::RequestPaste) + }); + } + assert!(asked); +} + +#[test] +fn the_menu_selects_the_whole_text_and_gives_it_the_keys_back() { + let mut harness = screen("one two"); + menu_of(&mut harness); + choose(&mut harness, "editor-menu-select-all"); harness.run(); + assert_eq!(harness.state().editor.buffer.selected_text(), "one two"); + let code = harness.get_by(|node| node.author_id() == Some("code")); + assert!(code.is_focused()); } #[test] -fn a_paste_and_a_cut_go_through_the_text() { +fn a_focused_editor_asks_for_the_input_method_at_its_caret() { let mut harness = screen("abc"); focus(&mut harness); - harness - .state_mut() - .editor - .buffer - .select(text::Selection { anchor: 0, head: 1 }); - harness.event(Event::Cut); - harness.run(); - assert_eq!(text(&harness), "bc"); - harness.event(Event::Paste("a".into())); - harness.run(); - assert_eq!(text(&harness), "abc"); + let ime = harness.output().platform_output.ime; + assert!(ime.is_some()); } #[test] diff --git a/crates/ui/src/widgets/json_explorer/graph.rs b/crates/ui/src/widgets/json_explorer/graph.rs index d8afdc91f..6745a7697 100644 --- a/crates/ui/src/widgets/json_explorer/graph.rs +++ b/crates/ui/src/widgets/json_explorer/graph.rs @@ -59,11 +59,11 @@ pub(super) struct Ground { } impl Ground { - fn zoom(&self) -> f32 { + pub(super) fn zoom(&self) -> f32 { self.zoom.unwrap_or(1.0) } - fn pan(&self) -> Vec2 { + pub(super) fn pan(&self) -> Vec2 { self.pan.unwrap_or(START) } @@ -108,7 +108,7 @@ impl Ground { } /// Around the middle of the ground, which is what stays put under the eye. - fn zoom_to(&mut self, ground: Rect, scale: f32) { + pub(super) fn zoom_to(&mut self, ground: Rect, scale: f32) { let middle = ground.size() / 2.0; let ratio = scale / self.zoom(); self.pan = Some(middle - (middle - self.pan()) * ratio); diff --git a/crates/ui/src/widgets/json_explorer/mod.rs b/crates/ui/src/widgets/json_explorer/mod.rs index a9f2186f6..e82879b0a 100644 --- a/crates/ui/src/widgets/json_explorer/mod.rs +++ b/crates/ui/src/widgets/json_explorer/mod.rs @@ -919,3 +919,5 @@ fn size_words(bytes: u32, language: Language) -> String { #[cfg(test)] mod tests; +#[cfg(test)] +mod view_tests; diff --git a/crates/ui/src/widgets/json_explorer/tests.rs b/crates/ui/src/widgets/json_explorer/tests.rs index bde4aa012..f50aa5813 100644 --- a/crates/ui/src/widgets/json_explorer/tests.rs +++ b/crates/ui/src/widgets/json_explorer/tests.rs @@ -1,12 +1,11 @@ //! The explorer's reads over views the core answered, as the reference's model specs had them. -use egui_kittest::kittest::Queryable; use engine::json::model::{JsonOpening, JsonQuery, JsonView, explore}; use engine::json::parse::Span; use engine::json::read::StructureFormat; use super::reads::{find, preview, trail_of}; -use super::{Explorer, ExplorerView, Mode, entry_at, span_of, utf16_slice}; +use super::{Explorer, entry_at, span_of, utf16_slice}; const EVENT: &str = r#"{"id":"evt_1","data":{"object":{"amount":4900,"lines":[{"description":"Pro · mensuel"}]}}}"#; @@ -114,71 +113,6 @@ fn stepping_to_a_match_reveals_it_and_wraps_around() { )); } -#[test] -fn the_line_the_search_goes_to_is_scrolled_into_view() { - let rows: Vec = (0..300).map(|n| format!(r#""k{n}":{n}"#)).collect(); - let text = format!("{{{}}}", rows.join(",")); - let mut harness = crate::testing::harness() - .with_size(egui::vec2(1_100.0, 800.0)) - .build_ui_state( - |ui, (explorer, view, text): &mut (Explorer, JsonView, String)| { - ExplorerView::new(explorer, view, text) - .mode(Mode::Tree) - .show(ui); - }, - (Explorer::default(), view(&text, JsonOpening::All), text), - ); - harness.run(); - let explorer = &mut harness.state_mut().0; - explorer.select("$.k250"); - explorer.tree.reveal = true; - harness.run(); - - let line = harness.get_by(|node| node.description().as_deref() == Some("$.k250")); - assert!(line.rect().bottom() <= 801.0, "{:?}", line.rect()); -} - -/// Escape is the window's once there is nothing to empty. -#[test] -fn escape_empties_the_search_and_stays_in_it() { - let state = (Explorer::default(), 0); - let mut harness = crate::testing::harness() - .with_size(egui::vec2(1_100.0, 800.0)) - .build_ui_state( - |ui, (explorer, escapes): &mut (Explorer, usize)| { - let view = view(EVENT, JsonOpening::All); - ExplorerView::new(explorer, &view, EVENT).show(ui); - *escapes += usize::from(ui.input(|input| input.key_pressed(egui::Key::Escape))); - }, - state, - ); - harness.run(); - harness - .get_by(|node| node.author_id() == Some("json-search")) - .click(); - harness.run(); - harness - .get_by(|node| node.author_id() == Some("json-search")) - .type_text("pro"); - harness.run(); - assert_eq!(harness.state().0.search, "pro"); - - harness.key_press(egui::Key::Escape); - harness.run(); - assert_eq!( - (harness.state().0.search.as_str(), harness.state().1), - ("", 0) - ); - assert!( - harness - .get_by(|node| node.author_id() == Some("json-search")) - .is_focused() - ); - harness.key_press(egui::Key::Escape); - harness.run(); - assert_eq!(harness.state().1, 1); -} - #[test] fn the_count_starts_over_when_the_document_lost_the_match_it_was_on() { let found = |text: &str| { @@ -198,56 +132,3 @@ fn the_count_starts_over_when_the_document_lost_the_match_it_was_on() { assert_eq!(explorer.step(&after, true).as_deref(), Some("$.a")); } - -/// Beside the tree and the graph are a panel and a breadcrumb, where egui would take the focus. -#[test] -fn the_arrows_stay_in_the_tree_and_in_the_graph() { - use egui::Key; - for (mode, entry, steps) in [ - ( - Mode::Tree, - "json-line", - [ - (Key::ArrowRight, "$.id"), - (Key::ArrowDown, "$.data"), - (Key::ArrowDown, "$.data.object"), - (Key::ArrowUp, "$.data"), - ], - ), - ( - Mode::Graph, - "json-row", - [ - (Key::ArrowRight, "$.id"), - (Key::ArrowDown, "$.data"), - (Key::ArrowUp, "$.id"), - (Key::ArrowLeft, "$"), - ], - ), - ] { - let mut harness = crate::testing::harness() - .with_size(egui::vec2(1_100.0, 800.0)) - .build_ui_state( - move |ui, explorer: &mut Explorer| { - let view = view(EVENT, JsonOpening::All); - ExplorerView::new(explorer, &view, EVENT) - .mode(mode) - .show(ui); - }, - Explorer::default(), - ); - harness.run(); - harness - .get_by(|node| { - node.author_id() == Some(entry) && node.description().as_deref() == Some("$.id") - }) - .click(); - harness.run(); - for (at, (key, path)) in steps.into_iter().enumerate() { - harness.key_press(key); - harness.run(); - let selected = harness.state().selected.as_deref(); - assert_eq!(selected, Some(path), "{mode:?}, step {at}"); - } - } -} diff --git a/crates/ui/src/widgets/json_explorer/view_tests.rs b/crates/ui/src/widgets/json_explorer/view_tests.rs new file mode 100644 index 000000000..f867a274d --- /dev/null +++ b/crates/ui/src/widgets/json_explorer/view_tests.rs @@ -0,0 +1,908 @@ +//! The explorer on screen, over what the core answers of the text at each frame. + +use egui::{Event, Key, Modifiers, Pos2, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use engine::json::model::{JsonView, explore}; +use engine::json::parse::JsonErrorReason; +use engine::json::read::StructureFormat; +use i18n::Language; + +use super::{Explorer, ExplorerView, Mode, Output, graph, reason, size_words}; +use crate::testing; + +const ORDER: &str = r#"{"id":7,"paid":true,"lines":[{"name":"Pro"},{"name":"Basic"}],"note":null}"#; + +struct Screen { + explorer: Explorer, + text: String, + format: StructureFormat, + mode: Mode, + with_code: bool, + extractable: bool, + /// What the frames answered since it was last read. + said: Output, +} + +impl Screen { + fn view(&self) -> JsonView { + explore(&self.explorer.query(self.text.clone(), self.format)) + } + + fn selected(&self) -> Option { + self.explorer.selected_path(&self.view()) + } +} + +fn screen(text: &str, mode: Mode) -> Harness<'static, Screen> { + sized(text, mode, vec2(1_100.0, 800.0)) +} + +fn sized(text: &str, mode: Mode, size: egui::Vec2) -> Harness<'static, Screen> { + let state = Screen { + explorer: Explorer::default(), + text: text.to_owned(), + format: StructureFormat::Json, + mode, + with_code: true, + extractable: false, + said: Output::default(), + }; + let mut harness = testing::harness().with_size(size).build_ui_state( + |ui, screen: &mut Screen| { + let view = screen.view(); + let output = ExplorerView::new(&mut screen.explorer, &view, &screen.text) + .mode(screen.mode) + .format(screen.format) + .with_code(screen.with_code) + .extractable(screen.extractable) + .language(Language::En) + .show(ui); + let said = &mut screen.said; + said.chosen = output.chosen.or(said.chosen.take()); + said.show_in_code = output.show_in_code.or(said.show_in_code); + said.extract = output.extract.or(said.extract.take()); + said.tree_proposed |= output.tree_proposed; + }, + state, + ); + harness.run(); + harness +} + +fn graph_of(text: &str) -> Harness<'static, Screen> { + screen(text, Mode::Graph) +} + +fn tree_of(text: &str) -> Harness<'static, Screen> { + screen(text, Mode::Tree) +} + +fn present(harness: &Harness<'_, Screen>, author_id: &str) -> bool { + harness + .query_all_by(|node| node.author_id() == Some(author_id)) + .next() + .is_some() +} + +fn click(harness: &mut Harness<'_, Screen>, author_id: &str) { + harness + .get_by(|node| node.author_id() == Some(author_id)) + .click(); + harness.run(); +} + +fn said(harness: &Harness<'_, Screen>, author_id: &str) -> String { + let node = harness.get_by(|node| node.author_id() == Some(author_id)); + let node = node.accesskit_node(); + node.value().or_else(|| node.label()).unwrap_or_default() +} + +/// The entries on screen: nodes, rows or lines, by their path. +fn shown(harness: &Harness<'_, Screen>) -> Vec { + harness + .query_all_by(|node| { + matches!( + node.author_id(), + Some("json-node-head" | "json-row" | "json-line") + ) + }) + .filter_map(|node| node.accesskit_node().description()) + .collect() +} + +fn entry<'a>( + harness: &'a Harness<'_, Screen>, + author_id: &'a str, + path: &'a str, +) -> egui_kittest::Node<'a> { + harness.get_by(|node| { + node.author_id() == Some(author_id) && node.description().as_deref() == Some(path) + }) +} + +fn pick(harness: &mut Harness<'_, Screen>, author_id: &str, path: &str) { + entry(harness, author_id, path).click(); + harness.run(); +} + +fn press(harness: &mut Harness<'_, Screen>, modifiers: Modifiers, key: Key) { + harness.key_press_modifiers(modifiers, key); + harness.run(); +} + +fn walk(harness: &mut Harness<'_, Screen>, steps: &[(Key, &str)]) { + for (at, (key, path)) in steps.iter().enumerate() { + press(harness, Modifiers::NONE, *key); + let selected = harness.state().selected(); + assert_eq!(selected.as_deref(), Some(*path), "step {at}, {key:?}"); + } +} + +fn copied(harness: &mut Harness<'_, Screen>, author_id: &str) -> Option { + harness + .get_by(|node| node.author_id() == Some(author_id)) + .click(); + let mut copied = None; + for _ in 0..4 { + harness.step(); + let commands = &harness.output().platform_output.commands; + copied = copied.or_else(|| { + commands.iter().find_map(|command| match command { + egui::OutputCommand::CopyText(text) => Some(text.clone()), + _ => None, + }) + }); + } + copied +} + +fn searches(harness: &mut Harness<'_, Screen>, words: &str) { + harness + .get_by(|node| node.author_id() == Some("json-search")) + .click(); + harness.run(); + harness + .get_by(|node| node.author_id() == Some("json-search")) + .type_text(words); + for _ in 0..6 { + harness.step(); + } + harness.run(); +} + +// The graph + +#[test] +fn a_node_clicked_is_the_selection() { + let mut harness = graph_of(ORDER); + pick(&mut harness, "json-node-head", "$.lines"); + + assert_eq!(said(&harness, "json-selected-path"), "$.lines"); + assert_eq!(harness.state().said.chosen.as_deref(), Some("$.lines")); +} + +#[test] +fn a_row_that_holds_a_value_is_selected_and_one_that_opens_folds_and_unfolds() { + let mut harness = graph_of(ORDER); + pick(&mut harness, "json-row", "$.id"); + assert_eq!(said(&harness, "json-selected-path"), "$.id"); + assert!(shown(&harness).contains(&"$.lines[0]".to_owned())); + + pick(&mut harness, "json-row", "$.lines"); + assert!(!shown(&harness).contains(&"$.lines[0]".to_owned())); + pick(&mut harness, "json-row", "$.lines"); + assert!(shown(&harness).contains(&"$.lines[0]".to_owned())); +} + +/// Down the rows and no further, into a child, back to the row that opened it. +#[test] +fn the_arrows_walk_the_graph() { + let mut harness = graph_of(ORDER); + pick(&mut harness, "json-node-head", "$"); + walk( + &mut harness, + &[ + (Key::ArrowUp, "$"), + (Key::ArrowDown, "$.id"), + (Key::ArrowUp, "$"), + (Key::ArrowRight, "$.id"), + (Key::ArrowRight, "$.id"), + (Key::ArrowDown, "$.paid"), + (Key::ArrowDown, "$.lines"), + (Key::ArrowRight, "$.lines"), + (Key::ArrowDown, "$.lines[0]"), + (Key::ArrowDown, "$.lines[1]"), + (Key::ArrowDown, "$.lines[1]"), + (Key::ArrowLeft, "$.lines"), + (Key::ArrowLeft, "$.lines"), + (Key::ArrowLeft, "$"), + (Key::ArrowLeft, "$"), + ], + ); +} + +#[test] +fn the_first_arrow_puts_the_cursor_on_the_root() { + for key in [ + Key::ArrowDown, + Key::ArrowUp, + Key::ArrowLeft, + Key::ArrowRight, + ] { + let mut harness = graph_of(ORDER); + harness + .get_by(|node| node.author_id() == Some("json-graph")) + .focus(); + harness.run(); + walk(&mut harness, &[(key, "$")]); + } +} + +#[test] +fn a_row_is_opened_by_the_right_arrow_and_either_by_enter_or_space() { + for (key, then) in [ + (Key::Enter, false), + (Key::Space, false), + (Key::ArrowRight, true), + ] { + let mut harness = graph_of(ORDER); + pick(&mut harness, "json-node-head", "$"); + for _ in 0..3 { + press(&mut harness, Modifiers::NONE, Key::ArrowDown); + } + press(&mut harness, Modifiers::NONE, Key::Enter); + assert!( + !shown(&harness).contains(&"$.lines[0]".to_owned()), + "folded" + ); + press(&mut harness, Modifiers::NONE, key); + assert!( + shown(&harness).contains(&"$.lines[0]".to_owned()), + "{key:?}" + ); + press(&mut harness, Modifiers::NONE, key); + assert_eq!( + shown(&harness).contains(&"$.lines[0]".to_owned()), + then, + "{key:?}" + ); + } +} + +/// It goes up until the root, whose Escape is the window's. +#[test] +fn escape_goes_back_up_the_graph() { + let mut harness = graph_of(ORDER); + pick(&mut harness, "json-row", "$.lines[0]"); + let names: Vec<_> = (0..4) + .map(|_| { + press(&mut harness, Modifiers::NONE, Key::Escape); + harness.state().selected().unwrap() + }) + .collect(); + + assert_eq!(names, ["$.lines", "$.lines", "$", "$"]); +} + +#[test] +fn shift_and_an_arrow_fold_everything_or_open_it() { + for mode in [Mode::Graph, Mode::Tree] { + let mut harness = screen(ORDER, mode); + let first = if mode == Mode::Graph { + "json-node-head" + } else { + "json-line" + }; + pick( + &mut harness, + first, + if mode == Mode::Graph { "$" } else { "$.id" }, + ); + press(&mut harness, Modifiers::SHIFT, Key::ArrowLeft); + assert!( + !shown(&harness).contains(&"$.lines[0]".to_owned()), + "{mode:?}" + ); + press(&mut harness, Modifiers::SHIFT, Key::ArrowRight); + assert!( + shown(&harness).contains(&"$.lines[0]".to_owned()), + "{mode:?}" + ); + } +} + +#[test] +fn the_buttons_fold_everything_and_open_it() { + for mode in [Mode::Graph, Mode::Tree] { + let mut harness = screen(ORDER, mode); + click(&mut harness, "json-collapse-all"); + assert!( + !shown(&harness).contains(&"$.lines[0]".to_owned()), + "{mode:?}" + ); + click(&mut harness, "json-open-all"); + assert!( + shown(&harness).contains(&"$.lines[0]".to_owned()), + "{mode:?}" + ); + } +} + +#[test] +fn alt_and_an_arrow_move_the_node_and_the_layout_is_reset() { + for (key, step) in [ + (Key::ArrowLeft, vec2(-2.0, 0.0)), + (Key::ArrowRight, vec2(2.0, 0.0)), + (Key::ArrowUp, vec2(0.0, -1.0)), + (Key::ArrowDown, vec2(0.0, 1.0)), + ] { + let mut harness = graph_of(ORDER); + assert!(!present(&harness, "json-reset-layout")); + pick(&mut harness, "json-node-head", "$.lines"); + press(&mut harness, Modifiers::ALT, key); + assert_eq!(harness.state().explorer.offsets["$.lines"], step, "{key:?}"); + + click(&mut harness, "json-reset-layout"); + assert!(harness.state().explorer.offsets.is_empty()); + } +} + +/// Moved back where it was placed, there is nothing to reset. +#[test] +fn a_node_moved_there_and_back_is_not_moved() { + let mut harness = graph_of(ORDER); + pick(&mut harness, "json-node-head", "$.lines"); + press(&mut harness, Modifiers::ALT, Key::ArrowLeft); + press(&mut harness, Modifiers::ALT, Key::ArrowRight); + + assert!(!present(&harness, "json-reset-layout")); +} + +fn drag(harness: &mut Harness<'_, Screen>, from: Pos2, by: egui::Vec2) { + let button = |pos, pressed| Event::PointerButton { + pos, + button: egui::PointerButton::Primary, + pressed, + modifiers: Modifiers::NONE, + }; + harness.event(Event::PointerMoved(from)); + harness.event(button(from, true)); + harness.run(); + for part in 1..=4_u8 { + harness.event(Event::PointerMoved(from + by * (f32::from(part) / 4.0))); + harness.run(); + } + harness.event(button(from + by, false)); + harness.run(); +} + +fn centre(node: &egui_kittest::Node<'_>) -> Pos2 { + node.rect().center() +} + +#[test] +fn a_node_dragged_is_moved_and_not_clicked() { + let mut harness = graph_of(ORDER); + let from = centre(&entry(&harness, "json-node-head", "$.lines")); + drag(&mut harness, from, vec2(40.0, 48.0)); + + let moved = harness.state().explorer.offsets["$.lines"]; + assert!((moved.y - 2.0).abs() < 0.3 && moved.x > 1.0, "{moved:?}"); + assert_eq!(harness.state().said.chosen, None); + let after = centre(&entry(&harness, "json-node-head", "$.lines")); + assert!( + (after - from - vec2(40.0, 48.0)).length() < 8.0, + "{after:?}" + ); +} + +#[test] +fn the_ground_dragged_or_scrolled_pans_the_graph() { + let mut harness = graph_of(ORDER); + let before = centre(&entry(&harness, "json-node-head", "$")); + drag(&mut harness, egui::pos2(500.0, 700.0), vec2(30.0, -20.0)); + let panned = centre(&entry(&harness, "json-node-head", "$")); + assert!( + (panned - before - vec2(30.0, -20.0)).length() < 8.0, + "{before:?} {panned:?}" + ); + assert!(harness.state().explorer.offsets.is_empty()); + + scroll(&mut harness, 25.0); + let scrolled = centre(&entry(&harness, "json-node-head", "$")); + assert!( + (scrolled - panned - vec2(0.0, 25.0)).length() < 2.0, + "{panned:?} {scrolled:?}" + ); +} + +fn scroll(harness: &mut Harness<'_, Screen>, by: f32) { + harness.event(Event::PointerMoved(egui::pos2(500.0, 600.0))); + harness.event(Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, by), + modifiers: Modifiers::NONE, + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + }); + for _ in 0..30 { + harness.step(); + } +} + +fn zoom(harness: &Harness<'_, Screen>) -> String { + said(harness, "json-zoom-reset") +} + +#[test] +fn the_zoom_goes_by_steps_between_its_two_ends() { + let mut harness = graph_of(ORDER); + assert_eq!(zoom(&harness), "100 %"); + let mut seen = Vec::new(); + for _ in 0..4 { + click(&mut harness, "json-zoom-in"); + seen.push(zoom(&harness)); + } + assert_eq!(seen, ["125 %", "150 %", "200 %", "200 %"]); + click(&mut harness, "json-zoom-reset"); + assert_eq!(zoom(&harness), "100 %"); + seen.clear(); + for _ in 0..6 { + click(&mut harness, "json-zoom-out"); + seen.push(zoom(&harness)); + } + assert_eq!(seen, ["80 %", "67 %", "50 %", "40 %", "25 %", "25 %"]); +} + +/// Around the middle of the ground: what is under the eye stays there. +#[test] +fn the_zoom_keeps_the_middle_where_it_is() { + let rect = egui::Rect::from_min_size(egui::pos2(100.0, 50.0), vec2(400.0, 300.0)); + let mut ground = graph::Ground::default(); + let middle = |ground: &graph::Ground| (rect.size() / 2.0 - ground.pan()) / ground.zoom(); + let before = middle(&ground); + ground.zoom_to(rect, 2.0); + + assert!((middle(&ground) - before).length() < 0.01); +} + +#[test] +fn fit_brings_the_whole_graph_in() { + let many: Vec = (0..6) + .map(|n| format!(r#""k{n}":{{"a":{{"b":[1]}}}}"#)) + .collect(); + let mut harness = sized( + &format!("{{{}}}", many.join(",")), + Mode::Graph, + vec2(700.0, 400.0), + ); + let nodes = harness.state().view().graph.nodes.len(); + let heads = |harness: &Harness<'_, Screen>| { + harness + .query_all_by(|node| node.author_id() == Some("json-node-head")) + .count() + }; + assert!(heads(&harness) < nodes); + + click(&mut harness, "json-fit"); + assert_eq!(heads(&harness), nodes); +} + +#[test] +fn fit_never_goes_past_the_size_of_the_text() { + let mut harness = graph_of(ORDER); + click(&mut harness, "json-zoom-in"); + click(&mut harness, "json-fit"); + + assert_eq!(zoom(&harness), "100 %"); +} + +/// However large, it stays readable: the rest is panned to. +#[test] +fn fit_never_goes_under_the_smallest_zoom() { + let many: Vec = (0..60) + .map(|n| format!(r#""k{n}":{{"a":{{"b":[1]}}}}"#)) + .collect(); + let mut harness = graph_of(&format!("{{{}}}", many.join(","))); + click(&mut harness, "json-open-all"); + click(&mut harness, "json-fit"); + + assert_eq!(zoom(&harness), "25 %"); +} + +#[test] +fn rows_past_what_a_node_shows_are_counted() { + let many: Vec = (0..260).map(|n| n.to_string()).collect(); + let mut harness = sized( + &format!("[{}]", many.join(",")), + Mode::Graph, + vec2(1_100.0, 5_300.0), + ); + harness.run(); + + let painted = testing::painted(&harness); + assert!( + painted.iter().any(|words| words.contains("60")), + "{painted:?}" + ); + assert!(shown(&harness).contains(&"$[199]".to_owned())); + assert!(!shown(&harness).contains(&"$[200]".to_owned())); +} + +#[test] +fn a_graph_too_large_is_folded_and_proposes_the_tree() { + let objects = vec![r#"{"a":1}"#; 200].join(","); + let arrays: Vec = (0..11).map(|n| format!(r#""k{n}":[{objects}]"#)).collect(); + let mut harness = graph_of(&format!("{{{}}}", arrays.join(","))); + click(&mut harness, "json-open-all"); + assert!(present(&harness, "json-folded")); + + click(&mut harness, "json-show-tree"); + assert!(harness.state().said.tree_proposed); +} + +/// Its cursor out of sight, the ground pans to it. +#[test] +fn the_cursor_is_brought_into_view() { + let rows: Vec = (0..60).map(|n| format!(r#""k{n}":{n}"#)).collect(); + let mut harness = graph_of(&format!("{{{}}}", rows.join(","))); + pick(&mut harness, "json-node-head", "$"); + for _ in 0..50 { + press(&mut harness, Modifiers::NONE, Key::ArrowDown); + } + let low = entry(&harness, "json-row", "$.k49").rect(); + assert!(low.bottom() < 764.0 && low.top() > 60.0, "{low:?}"); + for _ in 0..50 { + press(&mut harness, Modifiers::NONE, Key::ArrowUp); + } + let head = entry(&harness, "json-node-head", "$").rect(); + assert!(head.top() >= 59.0, "{head:?}"); +} + +#[test] +fn the_breadcrumb_names_what_holds_the_selection_and_goes_there() { + let mut harness = graph_of(ORDER); + pick(&mut harness, "json-row", "$.lines[1]"); + let crumbs = harness.get_by(|node| node.author_id() == Some("json-crumbs")); + let named = crumbs.accesskit_node().label().unwrap_or_default(); + assert_eq!(named.split(" › ").count(), 3, "{named}"); + + let label = named.split(" › ").next().unwrap().to_owned(); + harness + .get_by(|node| { + node.role() == egui::accesskit::Role::Link + && node.label().as_deref() == Some(label.as_str()) + }) + .click(); + harness.run(); + assert_eq!(harness.state().selected().as_deref(), Some("$")); +} + +// The tree + +/// ← folds a line open and goes to what holds one that is not; → opens it, then goes into it. +#[test] +fn the_arrows_walk_the_tree() { + let mut harness = tree_of(ORDER); + pick(&mut harness, "json-line", "$.id"); + walk( + &mut harness, + &[ + (Key::ArrowUp, "$"), + (Key::ArrowUp, "$"), + (Key::ArrowDown, "$.id"), + (Key::ArrowRight, "$.id"), + (Key::ArrowDown, "$.paid"), + (Key::ArrowDown, "$.lines"), + (Key::ArrowRight, "$.lines[0]"), + (Key::ArrowLeft, "$.lines[0]"), + (Key::ArrowLeft, "$.lines"), + (Key::ArrowLeft, "$.lines"), + (Key::ArrowLeft, "$"), + (Key::ArrowLeft, "$"), + ], + ); +} + +#[test] +fn a_line_is_opened_and_folded_by_a_click_and_by_the_keys() { + let mut harness = tree_of(ORDER); + let open = |harness: &Harness<'_, Screen>| shown(harness).contains(&"$.lines[0]".to_owned()); + assert!(open(&harness)); + pick(&mut harness, "json-line", "$.lines"); + assert!(!open(&harness)); + for (key, then) in [ + (Key::ArrowRight, true), + (Key::Enter, false), + (Key::Space, true), + ] { + press(&mut harness, Modifiers::NONE, key); + assert_eq!(open(&harness), then, "{key:?}"); + } +} + +#[test] +fn the_tree_stops_at_its_last_line() { + let mut harness = tree_of(r#"{"a":1}"#); + pick(&mut harness, "json-line", "$.a"); + walk(&mut harness, &[(Key::ArrowDown, "$.a")]); +} + +#[test] +fn the_line_reached_by_the_keys_is_scrolled_into_view() { + let rows: Vec = (0..80).map(|n| format!(r#""k{n}":{n}"#)).collect(); + let mut harness = tree_of(&format!("{{{}}}", rows.join(","))); + pick(&mut harness, "json-line", "$.k0"); + for _ in 0..70 { + press(&mut harness, Modifiers::NONE, Key::ArrowDown); + } + let low = entry(&harness, "json-line", "$.k70").rect(); + assert!(low.bottom() <= 801.0 && low.top() > 56.0, "{low:?}"); + for _ in 0..70 { + press(&mut harness, Modifiers::NONE, Key::ArrowUp); + } + let high = entry(&harness, "json-line", "$.k0").rect(); + assert!(high.top() > 50.0, "{high:?}"); +} + +#[test] +fn a_tree_cut_short_says_so() { + let many: Vec = (0..5_100).map(|n| n.to_string()).collect(); + let mut harness = tree_of(&format!("[{}]", many.join(","))); + let last = harness.state().view().tree.last().unwrap().path.clone(); + harness.state_mut().explorer.select(&last); + harness.state_mut().explorer.tree.reveal = true; + harness.run(); + scroll(&mut harness, -200.0); + + let words = i18n::translate(Language::En, i18n::keys::json::TREE_TRUNCATED, &[]); + assert!(testing::painted(&harness).contains(&words)); +} + +// The search + +#[test] +fn a_search_waits_for_a_pause_then_counts_its_matches() { + let mut harness = graph_of(ORDER); + assert!(!present(&harness, "json-match-next")); + searches(&mut harness, "name"); + + assert_eq!(harness.state().view().match_count, 2); + assert_eq!(said(&harness, "json-match-count"), "2"); +} + +#[test] +fn the_matches_are_walked_by_the_buttons_and_by_enter() { + let mut harness = graph_of(ORDER); + searches(&mut harness, "name"); + let (first, second) = ("$.lines[0].name", "$.lines[1].name"); + let goes = |harness: &Harness<'_, Screen>| harness.state().selected().unwrap_or_default(); + + click(&mut harness, "json-match-next"); + assert_eq!( + ( + goes(&harness).as_str(), + said(&harness, "json-match-count").as_str() + ), + (first, "1 / 2") + ); + click(&mut harness, "json-match-next"); + assert_eq!(goes(&harness), second); + click(&mut harness, "json-match-next"); + assert_eq!(goes(&harness), first); + click(&mut harness, "json-match-previous"); + assert_eq!(goes(&harness), second); + click(&mut harness, "json-match-previous"); + assert_eq!(goes(&harness), first); + + harness + .get_by(|node| node.author_id() == Some("json-search")) + .focus(); + harness.run(); + press(&mut harness, Modifiers::NONE, Key::Enter); + assert_eq!(goes(&harness), second); + press(&mut harness, Modifiers::SHIFT, Key::Enter); + assert_eq!(goes(&harness), first); + assert!( + harness + .get_by(|node| node.author_id() == Some("json-search")) + .is_focused() + ); +} + +#[test] +fn with_no_match_there_is_nowhere_to_go() { + let mut harness = graph_of(ORDER); + searches(&mut harness, "nowhere"); + click(&mut harness, "json-match-next"); + + assert_eq!(harness.state().said.chosen, None); + assert_eq!(said(&harness, "json-match-count"), "0"); +} + +#[test] +fn escape_empties_the_search() { + let mut harness = graph_of(ORDER); + searches(&mut harness, "name"); + press(&mut harness, Modifiers::NONE, Key::Escape); + for _ in 0..6 { + harness.step(); + } + + assert!(!present(&harness, "json-match-next")); + assert_eq!(harness.state().view().match_count, 0); +} + +// The selection and the document + +#[test] +fn with_nothing_chosen_the_root_is_described() { + let harness = graph_of(ORDER); + + assert_eq!(said(&harness, "json-selected-path"), "$"); + assert!(said(&harness, "json-selected-kind").contains('4')); +} + +#[test] +fn each_kind_is_said() { + let text = r#"{"o":{"a":1},"l":[1,2],"s":"x","n":1.5,"b":true,"z":null}"#; + for (path, kind) in [ + ("$.o", "Object"), + ("$.l", "Array"), + ("$.s", "String"), + ("$.n", "Number"), + ("$.b", "Boolean"), + ("$.z", "Null"), + ] { + for mode in [Mode::Graph, Mode::Tree] { + let mut harness = screen(text, mode); + harness.state_mut().explorer.select(path); + harness.run(); + let words = said(&harness, "json-selected-kind").to_lowercase(); + assert!(words.contains(&kind.to_lowercase()), "{path}: {words}"); + } + } + let mut harness = screen("at = 1979-05-27T07:32:00Z\n", Mode::Graph); + harness.state_mut().format = StructureFormat::Toml; + harness.state_mut().explorer.select("$.at"); + harness.run(); + assert!( + said(&harness, "json-selected-kind") + .to_lowercase() + .contains("date") + ); +} + +/// A string without its quotes, anything else as it is written. +#[test] +fn the_path_and_the_value_are_copied() { + let text = r#"{"s":"a \"b\"","l":[1, 2]}"#; + for (path, value) in [("$.s", r#"a "b""#), ("$.l", "[1, 2]")] { + for width in [1_100.0, 500.0] { + let mut harness = sized(text, Mode::Tree, vec2(width, 800.0)); + harness.state_mut().explorer.select(path); + harness.run(); + assert_eq!( + copied(&mut harness, "json-copy-path").as_deref(), + Some(path), + "{width}" + ); + assert_eq!( + copied(&mut harness, "json-copy-value").as_deref(), + Some(value), + "{width}" + ); + } + } +} + +#[test] +fn it_is_shown_in_the_code_where_there_is_one() { + let mut harness = graph_of(ORDER); + pick(&mut harness, "json-row", "$.id"); + click(&mut harness, "json-show-in-code"); + let span = harness.state().said.show_in_code.unwrap(); + assert_eq!(super::utf16_slice(ORDER, span), "7"); + + harness.state_mut().with_code = false; + harness.run(); + assert!(!present(&harness, "json-show-in-code")); +} + +#[test] +fn an_entry_is_extracted_under_an_answer_alone() { + let mut harness = graph_of(ORDER); + assert!(!present(&harness, "json-extract")); + harness.state_mut().extractable = true; + pick(&mut harness, "json-row", "$.id"); + click(&mut harness, "json-extract"); + + assert_eq!(harness.state().said.extract.as_deref(), Some("$.id")); +} + +#[test] +fn narrow_the_panel_keeps_the_path_and_its_actions() { + let harness = sized(ORDER, Mode::Graph, vec2(500.0, 800.0)); + + assert!(present(&harness, "json-selected-path") && present(&harness, "json-copy-value")); + assert!(!present(&harness, "json-selected-kind") && !present(&harness, "json-stats")); +} + +#[test] +fn the_document_is_measured() { + let harness = graph_of(ORDER); + let stats = said(&harness, "json-stats"); + + assert_eq!(stats, "Keys 6 · Depth 2 · Size 74 B"); +} + +#[test] +fn a_size_is_written_in_the_unit_it_reaches() { + for (bytes, words) in [ + (0, "0 B"), + (1_023, "1,023 B"), + (1_024, "1 KB"), + (1_536, "1.5 KB"), + (1_048_576, "1 MB"), + ] { + assert_eq!(size_words(bytes, Language::En), words); + } +} + +#[test] +fn what_the_format_drops_is_said() { + for (format, text, says) in [ + (StructureFormat::Json, r#"{"a":1}"#, false), + (StructureFormat::Yaml, "a: 1", true), + (StructureFormat::Toml, "a = 1", true), + (StructureFormat::Xml, "", true), + ] { + let mut harness = graph_of(text); + harness.state_mut().format = format; + harness.run(); + assert_eq!(present(&harness, "json-format-note"), says, "{format:?}"); + assert!(!present(&harness, "json-notice")); + } + let mut harness = graph_of("a: 1\n---\nb: 2\n"); + harness.state_mut().format = StructureFormat::Yaml; + harness.run(); + assert!( + present(&harness, "json-notice"), + "the second document is not read" + ); +} + +#[test] +fn a_text_that_cannot_be_read_says_where_and_goes_there() { + let mut harness = graph_of(r#"{"a":}"#); + let words = said(&harness, "json-invalid"); + assert!(words.contains("JSON") && words.contains('6'), "{words}"); + assert!(!present(&harness, "json-search")); + + click(&mut harness, "json-error-show"); + let span = harness.state().said.show_in_code.unwrap(); + assert_eq!((span.start, span.end), (5, 5)); +} + +#[test] +fn every_reason_has_its_own_words() { + use JsonErrorReason as Reason; + let mut said: Vec = [ + Reason::UnexpectedEnd, + Reason::UnexpectedCharacter, + Reason::InvalidNumber, + Reason::InvalidEscape, + Reason::ControlCharacter, + Reason::TrailingCharacters, + Reason::TooDeep, + Reason::Malformed, + Reason::TooLarge, + ] + .map(|each| i18n::translate(Language::En, reason(each), &[])) + .to_vec(); + said.sort(); + said.dedup(); + + assert_eq!(said.len(), 9); +} diff --git a/crates/ui/src/widgets/layout.rs b/crates/ui/src/widgets/layout.rs index c99214c8b..6dc80e88f 100644 --- a/crates/ui/src/widgets/layout.rs +++ b/crates/ui/src/widgets/layout.rs @@ -262,4 +262,24 @@ mod tests { harness.run(); assert_eq!(harness.state().1, Some(RAIL_WIDTH.0 + 16)); } + + #[test] + fn a_rail_put_away_leaves_the_whole_region() { + let mut harness = crate::testing::harness() + .with_size(egui::vec2(800.0, 400.0)) + .build_ui_state( + |ui, (shown, left): &mut (bool, Rect)| { + let region = ui.max_rect(); + *left = + RailWidth::default().beside(ui, region, (*shown, 200), "rail-edge", |_| ()); + }, + (false, Rect::NOTHING), + ); + harness.run(); + let whole = harness.state().1.width(); + harness.state_mut().0 = true; + harness.run(); + + assert!((whole - harness.state().1.width() - 208.0).abs() < 0.5); + } } diff --git a/crates/ui/src/widgets/menu.rs b/crates/ui/src/widgets/menu.rs index 851b91820..008ee8f37 100644 --- a/crates/ui/src/widgets/menu.rs +++ b/crates/ui/src/widgets/menu.rs @@ -1229,4 +1229,17 @@ mod tests { harness.run(); assert_eq!(*harness.state(), 0); } + + #[test] + fn a_filter_that_finds_nothing_says_so_and_picks_nothing() { + let mut harness = opened(); + harness + .get_by(|node| node.author_id() == Some("format-filter")) + .type_text("zzz"); + harness.run(); + harness.key_press(Key::Enter); + harness.run(); + + assert_eq!(*harness.state(), 0); + } } diff --git a/crates/ui/src/widgets/picker.rs b/crates/ui/src/widgets/picker.rs index 9c71c0ea5..81b1b71ad 100644 --- a/crates/ui/src/widgets/picker.rs +++ b/crates/ui/src/widgets/picker.rs @@ -321,4 +321,31 @@ mod tests { harness.run(); assert_eq!(*harness.state(), Some(2)); } + + #[test] + fn what_is_found_nowhere_is_said() { + let mut harness = harness(); + harness + .get_by(|node| node.author_id() == Some("move-filter")) + .type_text("nowhere"); + harness.run(); + + assert!(rows(&harness).is_empty()); + let none = i18n::translate(Language::En, keys::choice_menu::NO_RESULTS, &[]); + assert!(crate::testing::painted(&harness).contains(&none)); + harness.key_press(Key::Enter); + harness.run(); + assert_eq!(*harness.state(), None); + } + + #[test] + fn a_place_is_found_by_what_it_is_in() { + let mut harness = harness(); + harness + .get_by(|node| node.author_id() == Some("move-filter")) + .type_text("work › folder 299"); + harness.run(); + + assert_eq!(rows(&harness).len(), 1); + } } diff --git a/crates/ui/src/widgets/rich.rs b/crates/ui/src/widgets/rich.rs index c53bb3599..8556eba3b 100644 --- a/crates/ui/src/widgets/rich.rs +++ b/crates/ui/src/widgets/rich.rs @@ -871,147 +871,4 @@ fn image(ui: &mut Ui, alt: &str, (src, width): (&str, Option), frame: &mut F } #[cfg(test)] -mod tests { - use egui_kittest::kittest::{NodeT, Queryable}; - - use super::*; - - fn shown(markdown: &'static str) -> egui_kittest::Harness<'static, Option> { - let document = richtext::read(markdown); - let mut harness = crate::testing::harness() - .with_size(vec2(700.0, 900.0)) - .build_ui_state( - move |ui, link: &mut Option| { - if let Some(href) = rich_reader(ui, &document, 1.0).link { - *link = Some(href); - } - }, - None, - ); - harness.run(); - harness - } - - fn says(harness: &egui_kittest::Harness<'_, T>, words: &str) -> bool { - harness - .query_all_by(|node| { - node.label() - .or_else(|| node.value()) - .is_some_and(|said| said.contains(words)) - }) - .next() - .is_some() - } - - #[test] - fn every_sample_note_reads_in_both_languages() { - let fr = i18n::translate( - i18n::Language::Fr, - i18n::keys::notes::samples::release::CONTENT, - &[], - ); - let en = i18n::translate( - i18n::Language::En, - i18n::keys::notes::samples::release::CONTENT, - &[], - ); - for content in [fr, en] { - let document = richtext::read(&content); - let mut harness = crate::testing::harness() - .with_size(vec2(700.0, 900.0)) - .build_ui(move |ui| { - rich_reader(ui, &document, 1.0); - }); - harness.run(); - let code = harness.get_by(|node| node.role() == egui::accesskit::Role::Code); - assert!( - code.accesskit_node() - .label() - .unwrap_or_default() - .starts_with("kubectl rollout") - ); - } - } - - #[test] - fn headings_lists_tasks_quotes_and_tables_are_read() { - let harness = shown( - "# Titre\n\n- un\n - deux\n\n1. premier\n\n- [x] fait\n\n> cité\n\n| a | b |\n| --- | --- |\n| 1 | 2 |\n\n---", - ); - for words in ["Titre", "un", "deux", "premier", "fait", "cité"] { - assert!(says(&harness, words), "{words} is read"); - } - } - - #[test] - fn a_web_link_is_answered_and_another_scheme_is_not() { - let mut harness = shown("[le site](https://exemple.fr)"); - harness.get_by_label("le site").click(); - harness.run(); - assert_eq!(harness.state().as_deref(), Some("https://exemple.fr")); - - let mut harness = shown("[un fichier](file:///etc/passwd)"); - harness.get_by_label("un fichier").click(); - harness.run(); - assert!(harness.state().is_none(), "never a file"); - } - - #[test] - fn a_link_in_a_table_is_read_and_answered() { - let mut harness = shown("| a | b |\n| --- | --- |\n| un | [le site](https://exemple.fr) |"); - assert!(says(&harness, "un")); - let at = harness.get_by_label("le site").rect().left_top() + vec2(16.0, 14.0); - harness.hover_at(at); - for pressed in [true, false] { - harness.event(egui::Event::PointerButton { - pos: at, - button: egui::PointerButton::Primary, - pressed, - modifiers: egui::Modifiers::NONE, - }); - } - harness.run(); - assert_eq!(harness.state().as_deref(), Some("https://exemple.fr")); - } - - /// Edited, the click is the caret's: the link wants Ctrl, in a table as elsewhere. - #[test] - fn edited_a_link_is_followed_with_ctrl_alone() { - for markdown in [ - "[site](https://exemple.fr)", - "| [site](https://exemple.fr) |\n| --- |\n| b |", - ] { - for (modifiers, link) in [ - (egui::Modifiers::NONE, None), - (egui::Modifiers::COMMAND, Some("https://exemple.fr")), - ] { - let document = richtext::read(markdown); - let selection = Selection::default(); - let mut harness = crate::testing::harness() - .with_size(vec2(700.0, 300.0)) - .build_ui_state( - move |ui, painted: &mut Painted| { - let now = RichView::new(&document).editing(&selection).show(ui); - painted.link = now.link.or(painted.link.take()); - painted.leaves = now.leaves; - }, - Painted::default(), - ); - harness.run(); - let at = harness.state().leaves[0].origin + vec2(12.0, 10.0); - harness.event(egui::Event::ModifiersChanged(modifiers)); - harness.event(egui::Event::PointerMoved(at)); - for pressed in [true, false] { - harness.event(egui::Event::PointerButton { - pos: at, - button: egui::PointerButton::Primary, - pressed, - modifiers, - }); - } - harness.run(); - assert_eq!(harness.state().link.as_deref(), link, "{markdown}"); - } - } - } -} +mod tests; diff --git a/crates/ui/src/widgets/rich/tests.rs b/crates/ui/src/widgets/rich/tests.rs new file mode 100644 index 000000000..801240c5b --- /dev/null +++ b/crates/ui/src/widgets/rich/tests.rs @@ -0,0 +1,625 @@ +use egui_kittest::kittest::{NodeT, Queryable}; + +use super::*; + +fn shown(markdown: &'static str) -> egui_kittest::Harness<'static, Option> { + let document = richtext::read(markdown); + let mut harness = crate::testing::harness() + .with_size(vec2(700.0, 900.0)) + .build_ui_state( + move |ui, link: &mut Option| { + if let Some(href) = rich_reader(ui, &document, 1.0).link { + *link = Some(href); + } + }, + None, + ); + harness.run(); + harness +} + +fn says(harness: &egui_kittest::Harness<'_, T>, words: &str) -> bool { + harness + .query_all_by(|node| { + node.label() + .or_else(|| node.value()) + .is_some_and(|said| said.contains(words)) + }) + .next() + .is_some() +} + +#[test] +fn every_sample_note_reads_in_both_languages() { + let fr = i18n::translate( + i18n::Language::Fr, + i18n::keys::notes::samples::release::CONTENT, + &[], + ); + let en = i18n::translate( + i18n::Language::En, + i18n::keys::notes::samples::release::CONTENT, + &[], + ); + for content in [fr, en] { + let document = richtext::read(&content); + let mut harness = crate::testing::harness() + .with_size(vec2(700.0, 900.0)) + .build_ui(move |ui| { + rich_reader(ui, &document, 1.0); + }); + harness.run(); + let code = harness.get_by(|node| node.role() == egui::accesskit::Role::Code); + assert!( + code.accesskit_node() + .label() + .unwrap_or_default() + .starts_with("kubectl rollout") + ); + } +} + +#[test] +fn headings_lists_tasks_quotes_and_tables_are_read() { + let harness = shown( + "# Titre\n\n- un\n - deux\n\n1. premier\n\n- [x] fait\n\n> cité\n\n| a | b |\n| --- | --- |\n| 1 | 2 |\n\n---", + ); + for words in ["Titre", "un", "deux", "premier", "fait", "cité"] { + assert!(says(&harness, words), "{words} is read"); + } +} + +#[test] +fn a_web_link_is_answered_and_another_scheme_is_not() { + let mut harness = shown("[le site](https://exemple.fr)"); + harness.get_by_label("le site").click(); + harness.run(); + assert_eq!(harness.state().as_deref(), Some("https://exemple.fr")); + + let mut harness = shown("[un fichier](file:///etc/passwd)"); + harness.get_by_label("un fichier").click(); + harness.run(); + assert!(harness.state().is_none(), "never a file"); +} + +#[test] +fn a_link_in_a_table_is_read_and_answered() { + let mut harness = shown("| a | b |\n| --- | --- |\n| un | [le site](https://exemple.fr) |"); + assert!(says(&harness, "un")); + let at = harness.get_by_label("le site").rect().left_top() + vec2(16.0, 14.0); + harness.hover_at(at); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed, + modifiers: egui::Modifiers::NONE, + }); + } + harness.run(); + assert_eq!(harness.state().as_deref(), Some("https://exemple.fr")); +} + +/// Edited, the click is the caret's: the link wants Ctrl, in a table as elsewhere. +#[test] +fn edited_a_link_is_followed_with_ctrl_alone() { + for markdown in [ + "[site](https://exemple.fr)", + "| [site](https://exemple.fr) |\n| --- |\n| b |", + ] { + for (modifiers, link) in [ + (egui::Modifiers::NONE, None), + (egui::Modifiers::COMMAND, Some("https://exemple.fr")), + ] { + let document = richtext::read(markdown); + let selection = Selection::default(); + let mut harness = crate::testing::harness() + .with_size(vec2(700.0, 300.0)) + .build_ui_state( + move |ui, painted: &mut Painted| { + let now = RichView::new(&document).editing(&selection).show(ui); + painted.link = now.link.or(painted.link.take()); + painted.leaves = now.leaves; + }, + Painted::default(), + ); + harness.run(); + let at = harness.state().leaves[0].origin + vec2(12.0, 10.0); + harness.event(egui::Event::ModifiersChanged(modifiers)); + harness.event(egui::Event::PointerMoved(at)); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed, + modifiers, + }); + } + harness.run(); + assert_eq!(harness.state().link.as_deref(), link, "{markdown}"); + } + } +} + +// What a run is written with + +fn ink() -> &'static Palette { + palette(&egui::Context::default()) +} + +fn run(markdown: &str) -> TextFormat { + let document = richtext::read(markdown); + let Block::Paragraph(content) = &document.blocks[0] else { + panic!("a paragraph"); + }; + let (job, _) = job(ink(), content, Style::body(ink(), 14.0), 500.0); + job.sections[0].format.clone() +} + +fn weight(format: &TextFormat) -> f32 { + let set = format + .coords + .as_ref() + .iter() + .find(|(tag, _)| *tag == egui::epaint::text::Tag::new(b"wght")); + set.map_or(0.0, |(_, value)| *value) +} + +#[test] +fn a_mark_changes_what_it_says_and_nothing_else() { + let plain = run("mot"); + assert_eq!(plain.font_id, FontId::proportional(BODY)); + assert_eq!((plain.color, plain.italics), (ink().text_0, false)); + assert!((weight(&plain) - 400.0).abs() < 0.5); + + assert!((weight(&run("**mot**")) - 650.0).abs() < 0.5); + assert!(run("*mot*").italics); + + let struck = run("~~mot~~"); + assert_eq!( + (struck.color, struck.strikethrough.width), + (ink().text_2, 1.0) + ); + let code = run("`mot`"); + assert_eq!( + (code.font_id, code.background), + (FontId::monospace(BODY * 0.88), ink().bg_3) + ); + let link = run("[mot](https://a.fr)"); + assert_eq!((link.color, link.underline.width), (ink().amber_text, 1.0)); + assert!(plain.strikethrough.width == 0.0 && plain.underline.width == 0.0); +} + +#[test] +fn a_link_covers_its_own_characters() { + let document = richtext::read("été [le site](https://a.fr) et [x](https://b.fr)"); + let Block::Paragraph(content) = &document.blocks[0] else { + panic!("a paragraph"); + }; + let (_, links) = job(ink(), content, Style::body(ink(), 14.0), 500.0); + + assert_eq!( + links, + [ + (4..11, "https://a.fr".to_owned()), + (15..16, "https://b.fr".to_owned()) + ] + ); +} + +#[test] +fn an_empty_paragraph_keeps_the_height_of_a_line() { + let (job, links) = job(ink(), &[], Style::body(ink(), 14.0), 500.0); + + assert!(links.is_empty()); + assert_eq!(job.sections.len(), 1); + assert_eq!(job.sections[0].format.line_height, Some(14.0 * LINE_HEIGHT)); +} + +#[test] +fn three_levels_of_heading_are_larger_than_the_text() { + let sizes = [1, 2, 3, 4, 6].map(|level| heading_size(level, 14.0)); + + assert_eq!( + sizes.map(|size| size.to_string()), + ["22", "18", "15", "14", "14"] + ); +} + +#[test] +fn a_heading_larger_than_the_text_stands_further_from_what_is_above() { + let heading = |level| Block::Heading { + level, + content: Vec::new(), + }; + assert!((gap_before(&heading(1), 14.0) - 1.1 * 22.0).abs() < 0.01); + for block in [heading(4), Block::Rule] { + assert!((gap_before(&block, 14.0) - GAP * 14.0).abs() < 0.01); + } +} + +#[test] +fn a_fence_names_its_language_by_its_tag_or_by_a_shell_s_name() { + let shell = syntax_of("sh"); + assert!(shell.is_some()); + for (fence, syntax) in [ + ("bash", shell), + ("shell", shell), + ("ZSH", shell), + ("RS", syntax_of("rs")), + ("nowhere", None), + ("", None), + ] { + assert_eq!(syntax_of(fence), syntax, "{fence}"); + } + assert_ne!(syntax_of("rs"), None); +} + +#[test] +fn a_web_address_is_one_whatever_its_case() { + for (href, web) in [ + ("https://a.fr", true), + ("HTTP://A.FR", true), + ("file:///etc/passwd", false), + ("javascript:alert(1)", false), + ("mailto:a@b.fr", false), + ("a.fr/http://b.fr", false), + ] { + assert_eq!(is_web(href), web, "{href}"); + } +} + +// Read + +fn painted(markdown: &'static str) -> Vec { + crate::testing::painted(&shown(markdown)) +} + +#[test] +fn an_ordered_list_counts_from_its_start() { + let words = painted("3. trois\n4. quatre"); + + assert!( + words.contains(&"3.".to_owned()) && words.contains(&"4.".to_owned()), + "{words:?}" + ); +} + +#[test] +fn a_task_is_named_by_its_text_or_by_its_place() { + let harness = shown("- [x] fait\n- [ ] "); + let tasks: Vec<(String, bool)> = harness + .query_all_by(|node| node.author_id() == Some("rich-task")) + .map(|node| { + let node = node.accesskit_node(); + let checked = node.toggled() == Some(egui::accesskit::Toggled::True); + (node.label().unwrap_or_default(), checked) + }) + .collect(); + + assert_eq!(tasks, [("fait".to_owned(), true), ("2".to_owned(), false)]); +} + +#[test] +fn a_block_of_code_names_its_language_in_its_corner() { + assert!(painted("```rust\nlet a = 1;\n```").contains(&"rust".to_owned())); + let bare = painted("```\nlet a = 1;\n```"); + assert_eq!(bare, ["let a = 1;"]); +} + +#[test] +fn another_image_than_a_drawing_is_written_as_it_was() { + assert!( + painted("![alt](https://a.fr/b.png)").contains(&"![alt](https://a.fr/b.png)".to_owned()) + ); + let drawing = painted("![Le plan](devnotes:drawing/abc)"); + assert!(drawing.contains(&"Le plan".to_owned()), "{drawing:?}"); +} + +// Edited + +/// What the frames of an editor answered, over `markdown`. +fn edited(markdown: &str) -> egui_kittest::Harness<'static, Painted> { + let document = richtext::read(markdown); + let selection = Selection::default(); + let mut harness = crate::testing::harness() + .with_size(vec2(700.0, 900.0)) + .build_ui_state( + move |ui, painted: &mut Painted| { + let now = RichView::new(&document).editing(&selection).show(ui); + painted.ticked = now.ticked.or(painted.ticked.take()); + painted.picked = now.picked.or(painted.picked.take()); + painted.leaves = now.leaves; + painted.images = now.images; + painted.wanted = now.wanted; + }, + Painted::default(), + ); + harness.run(); + harness +} + +fn click_at(harness: &mut egui_kittest::Harness<'_, Painted>, at: Pos2) { + harness.event(egui::Event::PointerMoved(at)); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed, + modifiers: egui::Modifiers::NONE, + }); + } + harness.run(); +} + +/// In the document's order, whatever holds them. +#[test] +fn each_leaf_is_answered_with_its_path() { + let harness = edited( + "# t\n\n- a\n - b\n\n> c\n>\n> - d\n\n| e | f |\n| --- | --- |\n| g | h |\n\n```\ni\n```", + ); + let leaves: Vec<(String, Vec)> = harness + .state() + .leaves + .iter() + .map(|leaf| (leaf.galley.text().to_owned(), leaf.path.clone())) + .collect(); + let expected = [ + ("t", vec![0]), + ("a", vec![1, 0, 0]), + ("b", vec![1, 0, 1, 0, 0]), + ("c", vec![2, 0]), + ("d", vec![2, 1, 0, 0]), + ("e", vec![3, 0, 0]), + ("f", vec![3, 0, 1]), + ("g", vec![3, 1, 0]), + ("h", vec![3, 1, 1]), + ("i", vec![4]), + ]; + + assert_eq!(leaves, expected.map(|(text, path)| (text.to_owned(), path))); +} + +#[test] +fn a_task_s_box_clicked_says_which_one() { + let mut harness = edited("texte\n\n- [ ] a\n- [ ] b"); + let boxes: Vec = harness + .query_all_by(|node| node.author_id() == Some("rich-task")) + .map(|node| node.rect()) + .collect(); + click_at(&mut harness, boxes[1].center()); + + assert_eq!(harness.state().ticked, Some((vec![1], 1))); +} + +#[test] +fn read_a_task_s_box_does_not_take_the_click() { + let mut harness = crate::testing::harness().build_ui_state( + |ui, ticked: &mut bool| { + let document = richtext::read("- [ ] a"); + *ticked |= RichView::new(&document).show(ui).ticked.is_some(); + }, + false, + ); + harness.run(); + harness + .get_by(|node| node.author_id() == Some("rich-task")) + .click(); + harness.run(); + + assert!(!harness.state()); +} + +#[test] +fn an_image_clicked_is_picked_and_each_is_answered_where_it_is() { + let mut harness = edited("a\n\n![x](devnotes:drawing/one)\n\n![y](devnotes:drawing/two)"); + let paths: Vec> = harness + .state() + .images + .iter() + .map(|image| image.path.clone()) + .collect(); + assert_eq!(paths, [vec![1], vec![2]]); + + let at = harness.state().images[1].rect.center(); + click_at(&mut harness, at); + assert_eq!(harness.state().picked, Some(vec![2])); +} + +// A drawing embedded + +/// The drawing as its `pictures` say it, in a room 400 px wide. +fn embedding( + markdown: &'static str, + size: [usize; 2], +) -> egui_kittest::Harness<'static, Vec> { + let document = richtext::read(markdown); + let mut harness = crate::testing::harness() + .with_size(vec2(800.0, 900.0)) + .build_ui_state( + move |ui, wanted: &mut Vec| { + ui.set_width(400.0); + let pixels = egui::ColorImage::filled(size, Color32::WHITE); + let texture = + ui.ctx() + .load_texture("drawing", pixels, egui::TextureOptions::LINEAR); + let pictures = move |id: &str| match id { + "shown" => Some(Embedded::Shown(texture.clone())), + "waiting" => Some(Embedded::Waiting), + "gone" => Some(Embedded::Missing), + _ => None, + }; + let painted = RichView::new(&document) + .pictures(&pictures, "Dessin introuvable") + .show(ui); + *wanted = painted.wanted; + }, + Vec::new(), + ); + harness.step(); + harness +} + +fn embeds(harness: &egui_kittest::Harness<'_, State>) -> Vec { + harness + .query_all_by(|node| node.author_id() == Some("rich-embed")) + .map(|node| node.rect()) + .collect() +} + +#[test] +fn a_picture_never_asked_for_is_wanted_and_one_coming_is_not() { + for (markdown, wanted) in [ + ("![a](devnotes:drawing/new)", vec!["new".to_owned()]), + ("![a](devnotes:drawing/waiting)", Vec::new()), + ("![a](devnotes:drawing/shown)", Vec::new()), + ("![a](https://a.fr/b.png)", Vec::new()), + ] { + assert_eq!( + *embedding(markdown, [100, 50]).state(), + wanted, + "{markdown}" + ); + } +} + +#[test] +fn a_drawing_gone_is_said() { + let words = crate::testing::painted(&embedding("![a](devnotes:drawing/gone)", [100, 50])); + + assert!( + words.contains(&"Dessin introuvable".to_owned()), + "{words:?}" + ); +} + +/// At its own size, never wider than the text; given a width, a part of the text's. +#[test] +fn a_drawing_is_drawn_at_its_width_and_keeps_its_shape() { + for (markdown, natural, drawn) in [ + ("![a](devnotes:drawing/shown)", [100, 50], vec2(100.0, 50.0)), + ( + "![a](devnotes:drawing/shown)", + [800, 400], + vec2(400.0, 200.0), + ), + ( + "![a](devnotes:drawing/shown?w=50)", + [100, 50], + vec2(200.0, 100.0), + ), + ] { + let harness = embedding(markdown, natural); + let rects = embeds(&harness); + assert_eq!(rects.len(), 1, "{markdown}"); + assert!( + (rects[0].size() - drawn).length() < 1.0, + "{markdown}: {:?}", + rects[0].size() + ); + } +} + +// A slide + +fn slide_rects(markdown: &'static str) -> Vec { + let document = richtext::read(markdown); + let selection = Selection::default(); + let mut harness = crate::testing::harness() + .with_size(vec2(1_000.0, 900.0)) + .build_ui_state( + move |ui, leaves: &mut Vec| { + *leaves = RichView::new(&document) + .slide(300.0, 2.0) + .editing(&selection) + .show(ui) + .leaves; + }, + Vec::new(), + ); + harness.run(); + std::mem::take(harness.state_mut()) +} + +#[test] +fn a_slide_s_text_is_no_wider_than_it_reads() { + let leaves = + slide_rects("un texte assez long pour faire plus d’une ligne sur la largeur donnée"); + + assert!(leaves[0].galley.size().x <= 300.0); + assert!(leaves[0].galley.rows.len() > 1); +} + +#[test] +fn a_slide_s_title_has_its_own_scale() { + let leaves = slide_rects("# Titre\n\n# Autre"); + let heights: Vec = leaves.iter().map(|leaf| leaf.galley.size().y).collect(); + + assert!(heights[0] > 1.8 * heights[1], "{heights:?}"); +} + +#[test] +fn a_slide_s_code_is_centred_at_its_own_width() { + let leaves = slide_rects("```\ncourt\n```"); + + assert!(leaves[0].origin.x > 300.0, "{:?}", leaves[0].origin); +} + +// The marks under the text + +fn filled(found: &'static [Found], selection: &'static Selection) -> Vec { + let document = richtext::read("un deux\n\ntrois"); + let mut harness = crate::testing::harness() + .with_size(vec2(700.0, 300.0)) + .build_ui(move |ui| { + RichView::new(&document) + .found(found) + .editing(selection) + .show(ui); + }); + harness.run(); + harness + .output() + .shapes + .iter() + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Rect(rect) + if rect.fill != Color32::TRANSPARENT && rect.rect.height() < 60.0 => + { + Some(rect.rect) + } + _ => None, + }) + .collect() +} + +#[test] +fn a_match_is_lit_where_it_is() { + let none = Box::leak(Box::new(Selection::default())); + let bare = filled(&[], none).len(); + let found: &'static [Found] = Box::leak(Box::new([ + (vec![0], 3..7), + (vec![1], 0..5), + (vec![9], 0..1), + ])); + + assert_eq!(filled(found, none).len() - bare, 2); +} + +/// Over both ends' leaves, and the line end of the first. +#[test] +fn a_selection_across_two_paragraphs_is_lit_in_both() { + let none = Box::leak(Box::new(Selection::default())); + let bare = filled(&[], none).len(); + let position = |leaf: usize, offset| richtext::Position { + path: vec![leaf], + offset, + }; + let across = Box::leak(Box::new(Selection { + anchor: position(1, 2), + head: position(0, 3), + })); + let lit = filled(&[], across); + + assert_eq!(lit.len() - bare, 2); +} diff --git a/crates/ui/src/widgets/tests.rs b/crates/ui/src/widgets/tests.rs index a884d0b51..abb791402 100644 --- a/crates/ui/src/widgets/tests.rs +++ b/crates/ui/src/widgets/tests.rs @@ -226,3 +226,128 @@ fn an_icon_alone_says_its_name_and_its_keys_on_hover() { } assert!(says(&harness, "Masquer le rail")); } + +// One control at a time + +/// What `draw` paints, as circles and filled rectangles. +fn colours(draw: impl Fn(&mut egui::Ui) + 'static) -> Vec { + let mut harness = crate::testing::harness().build_ui(move |ui| draw(ui)); + harness.run(); + let shapes = &harness.output().shapes; + shapes + .iter() + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Circle(circle) => Some(circle.fill), + egui::Shape::Rect(rect) => Some(rect.fill), + _ => None, + }) + .collect() +} + +#[test] +fn each_priority_has_its_dot_s_colour() { + use engine::notes::priority::Priority; + let p = crate::theme::palette(&egui::Context::default()); + for (priority, colour) in [ + (Priority::None, p.line_no), + (Priority::Low, p.text_2), + (Priority::Medium, p.blue), + (Priority::High, p.amber_text), + (Priority::Urgent, p.red), + ] { + let drawn = colours(move |ui| { + priority_dot(ui, priority); + }); + assert!(drawn.contains(&colour), "{priority:?}"); + } +} + +#[test] +fn a_segment_taken_elsewhere_cannot_be_chosen() { + let mut harness = crate::testing::harness().build_ui_state( + |ui, chosen: &mut u8| { + Segmented::new(&[(0, "A"), (1, "B"), (2, "C")], "side") + .taken(1) + .show(ui, chosen); + }, + 0, + ); + harness.run(); + harness.get_by_label("B").click(); + harness.run(); + assert_eq!(*harness.state(), 0); + harness.get_by_label("C").click(); + harness.run(); + assert_eq!(*harness.state(), 2); +} + +#[test] +fn a_question_asked_in_place_answers_what_was_pressed() { + let mut harness = crate::testing::harness().build_ui_state( + |ui, (asked, pressed): &mut (bool, Option)| { + let question = asked.then_some("Supprimer 3 notes ?"); + let words = ("Supprimer", "Annuler"); + if let Some(now) = ask_in_place(ui, words, question, true, "delete") { + *pressed = Some(now); + *asked = now == InPlace::Ask; + } + }, + (false, None), + ); + harness.run(); + for (control, pressed) in [ + ("delete", InPlace::Ask), + ("delete-cancel", InPlace::Cancel), + ("delete", InPlace::Ask), + ("delete-confirm", InPlace::Confirm), + ] { + harness + .get_by(|node| node.author_id() == Some(control)) + .click(); + harness.run(); + assert_eq!(harness.state().1, Some(pressed), "{control}"); + } +} + +/// In the middle of its room, or near the top of one that has no end. +#[test] +fn an_empty_place_says_so_and_offers_its_actions() { + for (height, within) in [(400.0, 150.0..250.0), (f32::INFINITY, 20.0..120.0)] { + let mut harness = crate::testing::harness() + .with_size(egui::vec2(600.0, 500.0)) + .build_ui_state( + move |ui, clicked: &mut Option| { + let room = + egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, height)); + let actions = [ + EmptyAction { + label: "Créer", + author_id: "create", + primary: true, + }, + EmptyAction { + label: "Importer", + author_id: "import", + primary: false, + }, + ]; + if let Some(rank) = empty_state(ui, room, ("Rien ici", "empty"), &actions) { + *clicked = Some(rank); + } + }, + None, + ); + harness.run(); + let top = harness + .get_by(|node| node.author_id() == Some("empty")) + .rect() + .top(); + assert!(within.contains(&top), "{height}: {top}"); + + harness + .get_by(|node| node.author_id() == Some("import")) + .click(); + harness.run(); + assert_eq!(*harness.state(), Some(1)); + } +} From f348741def00cadb3dc3645d20927a09cf51721e Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:32:35 +0100 Subject: [PATCH 85/95] Tools: unit tests completed for the answers, copies and errors (#1847) Co-authored-by: Claude Opus 5.5 --- crates/ui/src/app/preferences_tests.rs | 50 +++++ crates/ui/src/services/errors.rs | 54 +++++ .../ui/src/tools/catalogue/answers_tests.rs | 203 ++++++++++++++++++ 3 files changed, 307 insertions(+) diff --git a/crates/ui/src/app/preferences_tests.rs b/crates/ui/src/app/preferences_tests.rs index ba4b1285a..c501550ac 100644 --- a/crates/ui/src/app/preferences_tests.rs +++ b/crates/ui/src/app/preferences_tests.rs @@ -316,3 +316,53 @@ fn a_variable_added_is_proposed_once_applied() { .is_empty() ); } + +/// The library left and opened again: its launch copy is taken then, and listed on its page. +fn copies(directory: &std::path::Path) -> Harness<'static, DevNotesApp> { + let first = open_library(directory); + crate::testing::close_library(first.state().backend()); + drop(first); + let startup = super::tests::startup(directory); + let mut harness = Harness::builder() + .with_size(egui::vec2(1_100.0, 720.0)) + .build_eframe(|cc| DevNotesApp::new(cc, startup).unwrap()); + harness + .ctx + .set_missing_glyph_policy(egui::epaint::text::MissingGlyphPolicy::Tofu); + settle(&mut harness); + type_into(&mut harness, "vault-passphrase", PASSPHRASE); + harness.key_press(Key::Enter); + settle(&mut harness); + harness.set_size(egui::vec2(1_300.0, 2_400.0)); + settle(&mut harness); + open(&mut harness); + click(&mut harness, "settings-page-backups"); + harness +} + +#[test] +fn a_copy_put_back_is_asked_first_and_can_be_let_be() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = copies(directory.path()); + assert_eq!(count(&harness, "backup-row"), 1); + let said = said(&harness, "backup-detail"); + assert!(said.contains(" · "), "its date and its size: {said}"); + + click(&mut harness, "backup-restore"); + assert!(present(&harness, "backup-confirm") && !present(&harness, "backup-restore")); + click(&mut harness, "backup-cancel"); + assert!(present(&harness, "backup-restore") && !present(&harness, "backup-confirm")); +} + +/// The library closes under it: the copy's own phrase is asked for. +#[test] +fn a_copy_put_back_closes_the_library_and_asks_for_its_phrase() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = copies(directory.path()); + click(&mut harness, "backup-restore"); + click(&mut harness, "backup-confirm-restore"); + settle(&mut harness); + + assert!(present(&harness, "vault-passphrase")); + assert!(!harness.state().state().gate.is_open()); +} diff --git a/crates/ui/src/services/errors.rs b/crates/ui/src/services/errors.rs index 74f08579b..67826a0d9 100644 --- a/crates/ui/src/services/errors.rs +++ b/crates/ui/src/services/errors.rs @@ -262,4 +262,58 @@ mod tests { assert_eq!(errors.shown().count(), 1); } + + /// Two codes are never said in the same words: the sentence is what tells them apart. + #[test] + fn each_code_has_its_own_sentence() { + use engine::error::ErrorCode; + + let sentence = |code| { + key_of(&AppError { + code, + params: std::collections::BTreeMap::default(), + detail: String::new(), + }) + }; + let said: Vec = [ + ErrorCode::SpaceNotFound, + ErrorCode::FolderNotFound, + ErrorCode::AttachmentNotFound, + ErrorCode::HttpEnvironmentNotFound, + ErrorCode::DuplicateEnvironmentName, + ErrorCode::RevisionNotFound, + ErrorCode::LibraryOpen, + ErrorCode::LastLibrary, + ErrorCode::NothingToSetAside, + ErrorCode::BackupNotFound, + ErrorCode::BackupUnopenable, + ErrorCode::StorageUnavailable, + ErrorCode::PassphraseRequired, + ErrorCode::LibraryDamaged, + ErrorCode::HttpVariable, + ErrorCode::HttpInvalidUrl, + ErrorCode::HttpTls, + ErrorCode::HttpFileUnreadable, + ErrorCode::HttpFileTooLarge, + ErrorCode::HttpFell, + ErrorCode::HttpGraphqlVariables, + ErrorCode::HttpWebsocketRefused, + ErrorCode::HttpScriptSkipped, + ErrorCode::HttpScriptMethod, + ErrorCode::HttpScriptProtected, + ErrorCode::HttpScriptFile, + ] + .into_iter() + .map(|code| sentence(code).unwrap_or_else(|| panic!("{code:?}"))) + .collect(); + let mut words: Vec = said + .iter() + .map(|key| i18n::translate(i18n::Language::En, *key, &[])) + .collect(); + let count = words.len(); + words.sort(); + words.dedup(); + + assert_eq!(words.len(), count); + } } diff --git a/crates/ui/src/tools/catalogue/answers_tests.rs b/crates/ui/src/tools/catalogue/answers_tests.rs index 62d9a1051..af5260dd0 100644 --- a/crates/ui/src/tools/catalogue/answers_tests.rs +++ b/crates/ui/src/tools/catalogue/answers_tests.rs @@ -817,3 +817,206 @@ fn a_tool_cleared_has_nothing_typed_left() { } } } + +/// New York's, whatever the machine's own zone. +fn in_new_york(text: &str, id: &str) -> Harness<'static, Bench> { + let here = "zones-type-in-America/New_York"; + let mut harness = says( + "zones", + &[Type("zones-input", "2026-07-01 12:00")], + "zones-row", + ); + if !has(&harness, here) { + type_in(&mut harness, "zones-search", "new york"); + waits_for(&mut harness, "it is found", |harness| { + has(harness, "zones-found-America/New_York") + }); + click(&mut harness, "zones-found-America/New_York"); + waits_for(&mut harness, "it is a row", |harness| has(harness, here)); + } + click(&mut harness, here); + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + let field = |harness: &Harness<'_, Bench>| value_of(harness, "zones-input"); + harness + .get_by(|node| node.author_id() == Some("zones-input")) + .focus(); + harness.step(); + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + harness.step(); + type_in(&mut harness, "zones-input", text); + assert_eq!(field(&harness), text); + waits_for(&mut harness, text, |harness| has(harness, id)); + harness +} + +#[test] +fn a_time_the_clocks_repeated_is_one_of_two() { + let mut harness = in_new_york("2026-11-01 01:30", "zones-reading-1"); + click(&mut harness, "zones-reading-1"); + waits_for(&mut harness, "the second is taken", |harness| { + let second = harness.get_by(|node| node.author_id() == Some("zones-reading-1")); + second.accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) + }); +} + +#[test] +fn a_time_the_clocks_skipped_says_so() { + let harness = in_new_york("2026-03-08 02:30", "zones-problem"); + + saying(&harness, "zones-problem", "America/New_York"); +} + +#[test] +fn now_is_put_where_a_time_is_typed() { + let mut harness = opened("zones"); + click(&mut harness, "zones-now"); + waits_for(&mut harness, "a time is there", |harness| { + !value_of(harness, "zones-input").is_empty() + }); +} + +#[test] +fn a_negative_or_endless_size_says_so() { + for text in ["-12 KB", "99999999999999999999999999999999999999 YB"] { + says("sizes", &[Type("sizes-input", text)], "sizes-problem"); + } +} + +/// Named by its field, so the wrong one is the one corrected. +#[test] +fn each_thing_wrong_with_a_transfer_is_said() { + for (size, rate) in [ + ("lots", "100"), + ("1", "fast"), + ("-1", "100"), + ("1", "0"), + ("1", "-2"), + ] { + says( + "sizes", + &[Type("transfer-size", size), Type("transfer-rate", rate)], + "transfer-problem", + ); + } +} + +#[test] +fn each_form_of_a_code_is_encoded() { + for (kind, fields) in [ + ( + "qr-kind-3", + [ + ("qr-to", "ada@example.test"), + ("qr-subject", "Hello"), + ("qr-body", "Body"), + ("qr-to", "x"), + ], + ), + ( + "qr-kind-4", + [ + ("qr-name", "Ada Lovelace"), + ("qr-phone", "+33 1 02 03 04 05"), + ("qr-email", "ada@example.test"), + ("qr-organisation", "Analytical"), + ], + ), + ] { + let mut done = vec![Press(kind)]; + done.extend(fields.map(|(field, text)| Type(field, text))); + says("qr", &done, "qr-facts"); + } +} + +#[test] +fn an_identifier_is_recognised_or_said_not_to_be() { + for (text, id) in [ + ("0190163d-8694-739b-aea5-966c26f8ad91", "identifiers-facts"), + ("00000000-0000-0000-0000-000000000000", "identifiers-facts"), + ("507f1f77bcf86cd799439011", "identifiers-facts"), + ("01ARZ3NDEKTSV4RRFFQ69G5FAV", "identifiers-facts"), + ("8ZZZZZZZZZZZZZZZZZZZZZZZZZ", "identifiers-out-of-range"), + ("V1StGXR8_Z5jdHi6B-myT", "identifiers-possible"), + ("no id at all !", "identifiers-unrecognised"), + ] { + says("identifiers", &[Type("identifiers-checked", text)], id); + } +} + +#[test] +fn how_many_are_drawn_goes_by_one_within_its_bounds() { + let mut harness = opened("identifiers"); + let count = |harness: &Harness<'_, Bench>| value_of(harness, "identifiers-count"); + assert_eq!(count(&harness), "5"); + click(&mut harness, "identifiers-more"); + assert_eq!(count(&harness), "6"); + for _ in 0..8 { + click(&mut harness, "identifiers-fewer"); + } + assert_eq!(count(&harness), "1"); +} + +#[test] +fn another_draw_gives_other_identifiers() { + let mut harness = opened("identifiers"); + waits_for(&mut harness, "they are drawn", |harness| { + has(harness, "identifiers-list") + }); + let ids = |harness: &Harness<'_, Bench>| { + painted(harness) + .into_iter() + .filter(|text| text.len() == 36 && text.matches('-').count() == 4) + .collect::>() + }; + let before = ids(&harness); + assert_eq!(before.len(), 5, "{before:?}"); + click(&mut harness, "identifiers-generate"); + waits_for(&mut harness, "others are drawn", |harness| { + let now = ids(harness); + now.len() == 5 && now != before + }); +} + +/// Every tool that offers an example can be cleared of it. +#[test] +fn a_sample_is_gone_once_its_tool_is_cleared() { + for entry in &super::TOOLS { + let mut tool = (entry.make)(); + if !tool.has_sample() { + continue; + } + tool.sample(i18n::Language::En); + tool.clear(); + assert!(tool.result(i18n::Language::En).is_none(), "{}", entry.id); + } +} + +/// Copied in once, where the tool says a note can fill it. +#[test] +fn a_note_is_taken_in_wherever_a_tool_offers_to() { + for entry in &super::TOOLS { + for (slot, _) in entry.from_note { + let mut tool = (entry.make)(); + let note = crate::tools::PickedNote { + title: "Standup".to_owned(), + content: "picked from a note".to_owned(), + language: None, + }; + tool.imported(slot, ¬e); + let mut harness = opened(entry.id); + harness.set_size(egui::vec2(1_300.0, 3_000.0)); + harness.state_mut().state.tools_view.put(entry.id, tool); + settle(&mut harness); + if entry.id == "qr" { + click(&mut harness, "qr-kind-0"); + } + assert!( + painted(&harness) + .iter() + .any(|text| text.contains("picked from a note")), + "{} {slot}", + entry.id + ); + } + } +} From be165b637f0031c17a111ed6cf22fd8030c8dbd4 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:35:35 +0100 Subject: [PATCH 86/95] Notes: unit tests rewritten for the canvas, cards and overlays (#1849) * Notes: a drag selects from where it was pressed Co-Authored-By: Claude Opus 5.5 * Notes: the press of a drag Co-Authored-By: Claude Opus 5.5 * Interface: unit tests rewritten for the notes area Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/ui/src/notes/calc.rs | 232 ++++++++++++++ crates/ui/src/notes/canvas/board/tests.rs | 129 ++++++++ crates/ui/src/notes/canvas/card/actions.rs | 46 +++ crates/ui/src/notes/canvas/card/body.rs | 2 +- crates/ui/src/notes/canvas/card/tests.rs | 118 +++++++ crates/ui/src/notes/canvas/tests.rs | 153 +++++++++ crates/ui/src/notes/header/facets.rs | 131 ++++++++ crates/ui/src/notes/header/selection.rs | 105 ++++++ crates/ui/src/notes/header/tests.rs | 302 +++++++++++++++++- .../src/notes/overlays/editor/calc/tests.rs | 90 ++++++ .../notes/overlays/editor/checklist/tests.rs | 142 ++++++++ .../src/notes/overlays/editor/format/tests.rs | 102 ++++++ .../notes/overlays/editor/json_view/tests.rs | 106 ++++++ .../notes/overlays/editor/revisions/tests.rs | 81 +++++ .../src/notes/overlays/editor/rich/tests.rs | 153 +++++++++ crates/ui/src/notes/overlays/editor/tests.rs | 51 ++- crates/ui/src/notes/overlays/tag_manager.rs | 41 +++ crates/ui/src/notes/overlays/trash_panel.rs | 32 ++ crates/ui/src/notes/overlays/undo_bar.rs | 54 ++++ crates/ui/src/notes/prettier.rs | 39 +++ crates/ui/src/notes/sidebar/tests.rs | 143 +++++++++ 21 files changed, 2231 insertions(+), 21 deletions(-) diff --git a/crates/ui/src/notes/calc.rs b/crates/ui/src/notes/calc.rs index 317e13cb2..16926643b 100644 --- a/crates/ui/src/notes/calc.rs +++ b/crates/ui/src/notes/calc.rs @@ -683,4 +683,236 @@ mod tests { } assert_eq!(checked, 20); } + + fn number_of(value: &str, unit: Option<(UnitId, Option)>) -> CalcValue { + CalcValue::Number { + value: value.to_owned(), + unit: unit.map(|(unit, per)| CalcUnit { unit, per }), + } + } + + /// Each form a result takes: on its line, then whole, as a copy gives it. + #[test] + fn each_kind_of_value_is_written_on_its_line_and_whole() { + let base = |radix| CalcValue::Base { + digits: "ff".to_owned(), + radix, + negative: radix == 16, + }; + let fraction = |denominator: &str, negative| CalcValue::Fraction { + numerator: "3".to_owned(), + denominator: denominator.to_owned(), + negative, + }; + let science = |exponent| CalcValue::Scientific { + mantissa: "1.23456".to_owned(), + exponent, + }; + let span = CalcValue::Span { + parts: vec![ + SpanPart { + value: "1250".to_owned(), + unit: UnitId::Week, + }, + SpanPart { + value: "3".to_owned(), + unit: UnitId::Day, + }, + ], + }; + for (value, shown, whole) in [ + (base(16), "-0xff", "-0xff"), + (base(8), "0off", "0off"), + (base(2), "0bff", "0bff"), + (base(36), "ff", "ff"), + (fraction("4", false), "3/4", "3/4"), + (fraction("1", true), "-3", "-3"), + (science(6), "1.235e+6", "1.23456e+6"), + (science(-6), "1.235e-6", "1.23456e-6"), + ( + CalcValue::Multiplier { + value: "1234.5".to_owned(), + }, + "×1,234.5", + "×1234.5", + ), + ( + CalcValue::Percent { + value: "1234.567".to_owned(), + signed: true, + }, + "+1,234.57%", + "+1234.567%", + ), + (span, "1,250 wk 3 d", "1250 wk 3 d"), + ( + number_of("1234.5", Some((UnitId::Kilometre, Some(UnitId::Hour)))), + "1,234.5 km/h", + "1234.5 km/h", + ), + ] { + let plain = |text: String| text.replace(NBSP, " "); + let line = self::value(&value, None, Format::plain(Language::En)).text; + assert_eq!(plain(line), shown, "{value:?}"); + assert_eq!(plain(exact(&value, Language::En)), whole, "{value:?}"); + } + } + + /// Two for money; four figures otherwise, two decimals at least; a small value keeps its first. + #[test] + fn a_value_keeps_the_decimals_that_say_it() { + let euro = Some((UnitId::Euro, None)); + let rate = Some((UnitId::Euro, Some(UnitId::Hour))); + for (value, unit, shown, approx) in [ + ("2", euro, "2.00 €", false), + ("2.005", euro, "2.01 €", true), + ("0.045", rate, "0.045 €/h", false), + ("1.23456", None, "1.235", true), + ("12.3456", None, "12.35", true), + ("12345.678", None, "12,345.68", true), + ("0.000123456", None, "0.0001235", true), + ("0.0000000001234", None, "0", true), + ("-0.5", None, "-0.5", false), + ("2.500", None, "2.5", false), + ("0", None, "0", false), + ] { + let value = number_of(value, unit); + let written = self::value(&value, None, Format::plain(Language::En)); + let said = (written.text.replace(NBSP, " "), written.approx); + assert_eq!(said, (shown.to_owned(), approx), "{value:?}"); + } + } + + #[test] + fn a_date_is_written_in_the_style_chosen() { + let date = CalcValue::Date { + date: chrono::NaiveDate::from_ymd_opt(2026, 11, 6).unwrap(), + }; + let written = |dates| { + let format = Format { + dates, + ..Format::plain(Language::En) + }; + self::value(&date, None, format).text + }; + let styles = [CalcDate::Numeric, CalcDate::Short, CalcDate::Long].map(written); + + assert!( + styles.iter().all(|text| text.contains("2026")), + "{styles:?}" + ); + assert!( + styles[2].contains("November") && !styles[1].contains("November"), + "{styles:?}" + ); + assert!(!styles[0].contains("Nov"), "{styles:?}"); + } + + #[test] + fn a_locale_is_the_one_named_or_the_language_s() { + assert_eq!(sample("1234.5", "de-DE", Language::En), "1.234,50"); + assert_eq!(sample("1234.5", "ja-JP", Language::Fr), "1,234.50"); + assert_eq!(sample("1234.5", "", Language::En), "1,234.50"); + let settings = Settings { + calc_number_format: "sv-SE".to_owned(), + calc_decimals: Some(3), + ..Settings::default() + }; + let format = Format::of(&settings, Language::En); + assert_eq!(format.numbers.map(|format| format.id), Some("sv-SE")); + assert_eq!(format.decimals, Some(3)); + } + + /// What is wrong, and what it is wrong about. + #[test] + fn each_error_is_said_in_its_own_words() { + let kilo = CalcUnit { + unit: UnitId::Kilogram, + per: None, + }; + let mismatch = |unit| CalcError::Mismatch { + expected: Dimension::Length, + found: Dimension::Mass, + unit, + }; + let not_convertible = |to| CalcError::NotConvertible { + from: Dimension::Length, + to, + }; + let mut said = Vec::new(); + for (wrong, about) in [ + (CalcError::Unreadable { at: 3 }, vec![]), + ( + CalcError::UnknownName { + name: "prix".to_owned(), + }, + vec!["prix"], + ), + ( + CalcError::Reserved { + word: "en".to_owned(), + }, + vec!["en"], + ), + (mismatch(None), vec!["length", "mass"]), + (mismatch(Some(kilo)), vec!["length", "kg"]), + (CalcError::Currency, vec![]), + (not_convertible(Some(kilo)), vec!["length", "kg"]), + (not_convertible(None), vec!["length", "%"]), + (CalcError::DivisionByZero, vec![]), + (CalcError::NothingAbove, vec![]), + (CalcError::NoPrevious, vec![]), + (CalcError::DateShift, vec![]), + (CalcError::NegativeRoot, vec![]), + (CalcError::LogDomain, vec![]), + (CalcError::NotWhole, vec![]), + (CalcError::NotPositive, vec![]), + (CalcError::RateExpected, vec![]), + (CalcError::Overflow, vec![]), + (CalcError::Unsupported, vec![]), + ] { + let words = error(&wrong, Language::En); + assert!(!words.is_empty(), "{wrong:?}"); + assert!( + about.iter().all(|each| words.contains(each)), + "{wrong:?}: {words:?}" + ); + said.push(words); + } + let count = said.len(); + said.sort(); + said.dedup(); + assert_eq!(said.len(), count, "{said:?}"); + } + + /// The same in both languages: a sheet reads either. + #[test] + fn what_is_after_a_conversion_word_is_a_unit_being_typed() { + for (before, typed) in [ + ("3 km en m", Some("m")), + ("3 km to ", Some("")), + ("3 km EN mi", Some("mi")), + ("en m", Some("m")), + ("3 km", None), + ("chien m", None), + ("", None), + ("3 kmen m", None), + ] { + assert_eq!(conversion_start(before), typed, "{before:?}"); + } + } + + #[test] + fn a_word_is_proposed_in_the_language_on_screen() { + assert!(complete("auj", Language::Fr).contains(&"aujourd'hui".to_owned())); + assert!(complete("AUJOURD’", Language::Fr).contains(&"aujourd'hui".to_owned())); + assert!(complete("auj", Language::En).is_empty()); + } + + #[test] + fn a_unit_is_proposed_by_its_start_whatever_its_case() { + assert_eq!(units_for(Dimension::Length, "K", Language::En), ["km"]); + let all = units_for(Dimension::Length, "", Language::En); + assert!(all.len() > 3 && !all.contains(&"%".to_owned()), "{all:?}"); + } } diff --git a/crates/ui/src/notes/canvas/board/tests.rs b/crates/ui/src/notes/canvas/board/tests.rs index c4a86303f..1778b43c3 100644 --- a/crates/ui/src/notes/canvas/board/tests.rs +++ b/crates/ui/src/notes/canvas/board/tests.rs @@ -606,3 +606,132 @@ fn an_open_folder_s_list_is_named_after_it_until_something_is_searched() { !heading(harness).starts_with("PERF") }); } + +fn present(harness: &Harness<'_, Bench>, author_id: &str) -> bool { + harness + .query_all_by(|node| node.author_id() == Some(author_id)) + .next() + .is_some() +} + +fn a_space_s_board( + backend: crate::backend::Backend, + profile: tempfile::TempDir, + name: &str, +) -> Harness<'static, Bench> { + let mut harness = area(backend, profile); + harness.set_size(egui::vec2(1_600.0, 900.0)); + click(&mut harness, "space-option", name); + click_id(&mut harness, "view-board"); + harness +} + +/// With what it is for, and the page that says how it works. +#[test] +fn a_board_with_nothing_on_it_says_so_and_opens_its_page() { + let (backend, profile) = testing::unlocked(); + space(&backend, "Accueil"); + space(&backend, "Vide"); + let mut harness = a_space_s_board(backend, profile, "Vide"); + assert!(present(&harness, "board-empty")); + + click_id(&mut harness, "board-guide"); + assert!(harness.state().state.dialogs.top().is_some()); +} + +#[test] +fn a_board_that_failed_offers_to_retry() { + let (mut harness, _) = tableau(); + click_id(&mut harness, "view-board"); + testing::close_library(&harness.state().backend); + let bench = harness.state_mut(); + bench.state.apply( + crate::action::Action::Notes(crate::notes::Action::Reload), + &egui::Context::default(), + &bench.backend, + ); + until(&mut harness, "it failed", |harness| { + present(harness, "canvas-error") + }); + let before = harness.state().state.revision; + harness + .get_by(|node| node.author_id() == Some("canvas-retry")) + .click(); + harness.run(); + + assert_ne!(harness.state().state.revision, before); +} + +/// One out of view is not drawn: the ground scrolls to it first. +#[test] +fn a_card_asked_for_is_scrolled_into_view() { + let (backend, profile) = testing::unlocked(); + space(&backend, "Accueil"); + let wide = space(&backend, "Grand"); + let far = folder(&backend, &wide, None, "Loin"); + let filed = note_in(&backend, &wide, "Rangée", Some(&far)); + let loose: Vec = (0..40) + .map(|at| note_in(&backend, &wide, &format!("Libre {at}"), None)) + .collect(); + let mut harness = a_space_s_board(backend, profile, "Grand"); + harness.set_size(egui::vec2(1_100.0, 500.0)); + crate::notes::bench::settle(&mut harness); + let drawn = |harness: &Harness<'_, Bench>, id: &str| { + harness.state().state.notes_view.canvas.focused.as_deref() == Some(id) + }; + for id in [&loose[39], &loose[0], &filed] { + harness.state_mut().state.notes_view.canvas.request = Some(id.clone()); + until(&mut harness, "it has the focus", |harness| { + drawn(harness, id) + }); + } +} + +fn button(pos: egui::Pos2, button: egui::PointerButton, pressed: bool) -> egui::Event { + egui::Event::PointerButton { + pos, + button, + pressed, + modifiers: egui::Modifiers::NONE, + } +} + +/// Nobody chose the place under a pointer that left: the card goes back where it was. +#[test] +fn a_drag_whose_pointer_left_the_window_is_dropped() { + let (mut harness, _) = tableau(); + click_id(&mut harness, "view-board"); + let before = rect_of(&harness, "board-loose-card", "Dump nocturne"); + let from = before.center(); + harness.event(egui::Event::PointerMoved(from)); + harness.event(button(from, egui::PointerButton::Primary, true)); + harness.step(); + for part in 1..=5_u8 { + harness.event(egui::Event::PointerMoved( + from + egui::vec2(20.0 * f32::from(part), 0.0), + )); + harness.step(); + } + let dragging = |harness: &Harness<'_, Bench>| { + harness + .state() + .state + .notes_view + .canvas + .board + .gesture + .is_some() + }; + assert!(dragging(&harness)); + harness.event(egui::Event::PointerGone); + harness.step(); + harness.step(); + assert!(!dragging(&harness)); + harness.event(button(from, egui::PointerButton::Primary, false)); + crate::notes::bench::settle(&mut harness); + + assert_eq!( + rect_of(&harness, "board-loose-card", "Dump nocturne"), + before + ); +} diff --git a/crates/ui/src/notes/canvas/card/actions.rs b/crates/ui/src/notes/canvas/card/actions.rs index 420b12fcf..77cdda41e 100644 --- a/crates/ui/src/notes/canvas/card/actions.rs +++ b/crates/ui/src/notes/canvas/card/actions.rs @@ -526,4 +526,50 @@ mod tests { let (_, said) = harness.state().state.status.latest().unwrap(); assert_eq!(said.key, i18n::keys::notes::COPIED_NOTE); } + + #[test] + fn the_menu_opens_the_note_and_copies_it() { + let (backend, profile) = testing::unlocked(); + testing::note(&backend, "psql"); + let mut harness = area(backend, profile); + open_menu(&mut harness); + click_id(&mut harness, "note-card-copy-menu"); + crate::notes::bench::until(&mut harness, "it is copied", |harness| { + harness.state().state.status.latest().is_some() + }); + + open_menu(&mut harness); + click_id(&mut harness, "note-card-open-menu"); + assert!(harness.state().state.editor.is_open()); + } + + /// A copy of a note with no title has none either, and its options still say whose they are. + #[test] + fn a_note_with_no_title_is_duplicated_without_one() { + let (backend, profile) = testing::unlocked(); + let id = testing::note(&backend, "psql").id.clone(); + let patch = engine::notes::model::NotePatch { + title: Some(String::new()), + content: Some("select 1".to_owned()), + ..Default::default() + }; + engine::db::run_here(backend.engine(), move |engine| { + engine::notes::update_note(engine, &id, &patch) + }) + .unwrap(); + let mut harness = area(backend, profile); + open_menu(&mut harness); + let menu = harness.get_by(|node| node.author_id() == Some("note-card-menu")); + assert!( + menu.accesskit_node() + .label() + .unwrap_or_default() + .contains("Untitled") + ); + click_id(&mut harness, "note-card-duplicate"); + + let view = harness.state().state.notes_query.view().unwrap(); + let titles: Vec<&str> = view.cards().map(|card| card.title.as_str()).collect(); + assert_eq!(titles, ["", ""]); + } } diff --git a/crates/ui/src/notes/canvas/card/body.rs b/crates/ui/src/notes/canvas/card/body.rs index e40691bae..efc8d5100 100644 --- a/crates/ui/src/notes/canvas/card/body.rs +++ b/crates/ui/src/notes/canvas/card/body.rs @@ -406,7 +406,7 @@ fn progress( /// Which items a card shows, in the note's order: the one a search found, then the first /// ones left to do, then the last ones — the top of a finished list says the least. -fn seats(note: &DisplayNote, count: usize) -> Vec { +pub(super) fn seats(note: &DisplayNote, count: usize) -> Vec { let items = ¬e.items; let mut seats = Vec::new(); if let Some(hit) = note diff --git a/crates/ui/src/notes/canvas/card/tests.rs b/crates/ui/src/notes/canvas/card/tests.rs index d4dfb81e8..6d7a0a9f5 100644 --- a/crates/ui/src/notes/canvas/card/tests.rs +++ b/crates/ui/src/notes/canvas/card/tests.rs @@ -503,3 +503,121 @@ fn thumbnail(backend: &crate::backend::Backend, id: &str) -> Option { }) .unwrap() } + +/// A card's corner says when, whatever the footer is of. +#[test] +fn the_corner_says_when_the_note_was_created_once_sorted_by_it() { + use crate::state::notes_query::{Arrangement, natural_order}; + use engine::notes::view::SortKey; + + let (backend, profile) = testing::unlocked(); + write(&backend, |draft| draft.title = "psql".into()); + let mut harness = canvas(backend, profile); + let said = |harness: &Harness<'_, Bench>| label(harness, "note-card-when"); + assert!( + said(&harness).starts_with("Modified") || said(&harness).starts_with("modified"), + "{}", + said(&harness) + ); + let bench = harness.state_mut(); + let arrangement = Arrangement { + order: natural_order(SortKey::Created), + ..bench.state.notes_query.arrangement() + }; + bench.state.apply( + crate::action::Action::Notes(crate::notes::Action::Arrange(arrangement)), + &egui::Context::default(), + &bench.backend, + ); + testing::settle(&mut harness, |bench| &bench.backend); + + assert!( + said(&harness).to_lowercase().starts_with("created"), + "{}", + said(&harness) + ); +} + +/// The one a search found, what is left to do, then the last done. +#[test] +fn a_list_shows_what_is_left_to_do_first_and_what_was_found_always() { + use engine::notes::view::{SearchField, SearchHit}; + + let (backend, _profile) = testing::unlocked(); + let item = |text: &str, done| ChecklistItem { + text: text.to_owned(), + done, + }; + let id = write(&backend, move |draft| { + draft.kind = NoteKind::Checklist; + draft.items = vec![ + item("a", true), + item("b", false), + item("c", true), + item("d", false), + item("e", true), + ]; + }); + let mut note = engine::db::run_here(backend.engine(), move |engine| { + engine::notes::get_note(engine, &id) + }) + .unwrap(); + for (count, seats) in [ + (1, vec![1]), + (2, vec![1, 3]), + (3, vec![1, 3, 4]), + (4, vec![1, 2, 3, 4]), + (9, vec![0, 1, 2, 3, 4]), + ] { + assert_eq!(super::body::seats(¬e, count), seats, "{count}"); + } + let hit = |field, excerpt: &str| { + Some(SearchHit { + field, + excerpt: excerpt.to_owned(), + }) + }; + note.search_hit = hit(SearchField::Item, "a"); + assert_eq!(super::body::seats(¬e, 2), [0, 1]); + note.search_hit = hit(SearchField::Item, "c…"); + assert_eq!(super::body::seats(¬e, 1), [2]); + note.search_hit = hit(SearchField::Body, "a"); + assert_eq!(super::body::seats(¬e, 1), [1], "found elsewhere"); +} + +#[test] +fn a_note_s_lines_are_drawn_with_what_they_are() { + let (backend, profile) = testing::unlocked(); + write(&backend, |draft| { + draft.kind = NoteKind::Note; + draft.content = + "# Titre\n\n- point\n\n1. premier\n\n- [x] fait\n- [ ] reste\n\n```\ncode\n```".into(); + }); + let mut harness = canvas(backend, profile); + let bench = harness.state_mut(); + bench.state.preview_lines = engine::folders::board::PreviewLines::Five; + testing::settle(&mut harness, |bench| &bench.backend); + let outline = label(&harness, "note-card-outline"); + + for words in ["Titre", "• point", "1. premier", "☑ fait", "☐ reste"] { + assert!(outline.contains(words), "{words}: {outline}"); + } +} + +#[test] +fn each_line_of_a_sheet_has_its_result() { + let (backend, profile) = testing::unlocked(); + write(&backend, |draft| { + draft.kind = NoteKind::Calc; + draft.content = "a = 10 / 4 +b = 4 +total" + .into(); + }); + let harness = canvas(backend, profile); + let painted = testing::painted(&harness); + + for words in ["a = 10 / 4", "2.5", "4", "total", "6.5"] { + assert!(painted.contains(&words.to_owned()), "{words}: {painted:?}"); + } +} diff --git a/crates/ui/src/notes/canvas/tests.rs b/crates/ui/src/notes/canvas/tests.rs index 8b8946f23..7a28372a4 100644 --- a/crates/ui/src/notes/canvas/tests.rs +++ b/crates/ui/src/notes/canvas/tests.rs @@ -156,3 +156,156 @@ fn an_empty_folder_offers_the_card_a_note_is_created_from() { .expect("a draft opens"); assert_eq!(draft.folder_id.as_deref(), Some(runbooks.id.as_str())); } + +fn headings(harness: &Harness<'_, Bench>) -> Vec { + harness + .query_all_by(|node| node.author_id() == Some("note-section")) + .map(|node| node.accesskit_node().label().unwrap_or_default()) + .collect() +} + +/// A snippet in SQL, urgent; a todo list with no level. +fn grouped(grouping: engine::notes::view::Grouping) -> Vec { + use engine::notes::kind::NoteKind; + use engine::notes::language::Language; + use engine::notes::model::NotePatch; + + let (backend, profile) = testing::unlocked(); + for (title, patch) in [ + ( + "sql", + NotePatch { + language: Some(Language::Sql), + ..NotePatch::default() + }, + ), + ( + "list", + NotePatch { + kind: Some(NoteKind::Checklist), + ..NotePatch::default() + }, + ), + ] { + let id = testing::note(&backend, title).id.clone(); + engine::db::run_here(backend.engine(), move |engine| { + engine::notes::update_note(engine, &id, &patch)?; + if title == "sql" { + let urgent = engine::notes::priority::Priority::Urgent; + engine::notes::set_priority(engine, &[id], urgent)?; + } + Ok::<_, engine::error::AppError>(()) + }) + .unwrap(); + } + let mut harness = canvas(backend, profile); + let bench = harness.state_mut(); + let arrangement = crate::state::notes_query::Arrangement { + grouping, + ..bench.state.notes_query.arrangement() + }; + bench.state.apply( + Action::Notes(crate::notes::Action::Arrange(arrangement)), + &egui::Context::default(), + &bench.backend, + ); + testing::settle(&mut harness, |bench| &bench.backend); + headings(&harness) +} + +#[test] +fn a_section_is_named_by_what_it_gathers() { + use engine::notes::view::Grouping; + + for (grouping, named) in [ + (Grouping::Format, "SQL"), + (Grouping::Format, "TASKS"), + (Grouping::Priority, "URGENT"), + ] { + let headings = grouped(grouping); + assert!( + headings.iter().any(|heading| heading.contains(named)), + "{grouping:?}: {headings:?}" + ); + } +} + +#[test] +fn a_priority_s_section_wears_its_dot() { + let urgent = palette(&egui::Context::default()).red; + let dotted = |grouping| { + let (backend, profile) = testing::unlocked(); + let id = testing::note(&backend, "sql").id.clone(); + engine::db::run_here(backend.engine(), move |engine| { + engine::notes::set_priority(engine, &[id], engine::notes::priority::Priority::Urgent) + }) + .unwrap(); + let mut harness = canvas(backend, profile); + let bench = harness.state_mut(); + let arrangement = crate::state::notes_query::Arrangement { + grouping, + ..bench.state.notes_query.arrangement() + }; + bench.state.apply( + Action::Notes(crate::notes::Action::Arrange(arrangement)), + &egui::Context::default(), + &bench.backend, + ); + testing::settle(&mut harness, |bench| &bench.backend); + let top = harness + .query_all_by(|node| node.author_id() == Some("note-section")) + .next() + .unwrap() + .rect(); + harness.output().shapes.iter().any(|clipped| { + matches!(&clipped.shape, egui::Shape::Circle(circle) + if circle.fill == urgent && circle.center.y < top.bottom() && circle.center.y > top.top()) + }) + }; + + assert!(dotted(engine::notes::view::Grouping::Priority)); + assert!(!dotted(engine::notes::view::Grouping::None)); +} + +/// What is offered is what gives the cards back. +#[test] +fn nothing_found_offers_the_way_back_from_what_filters() { + use crate::notes::Action as Notes; + + for (facet, label) in [ + (false, keys::notes::CLEAR_SEARCH), + (true, keys::notes::CLEAR_FILTERS), + ] { + let (backend, profile) = testing::unlocked(); + testing::note(&backend, "psql"); + let mut harness = canvas(backend, profile); + let bench = harness.state_mut(); + let (ctx, backend) = (egui::Context::default(), &bench.backend); + if facet { + let kind = + crate::state::notes_query::Facet::Kind(engine::notes::kind::NoteKind::Drawing); + bench + .state + .apply(Action::Notes(Notes::Facet(kind)), &ctx, backend); + } else { + bench.state.apply( + Action::Notes(Notes::Search("nowhere".to_owned())), + &ctx, + backend, + ); + } + for _ in 0..40 { + harness.step(); + } + testing::settle(&mut harness, |bench| &bench.backend); + let button = harness.get_by(|node| node.author_id() == Some("canvas-clear-filters")); + let said = button.accesskit_node().label().unwrap_or_default(); + assert_eq!(said, i18n::translate(i18n::Language::En, label, &[])); + button.click(); + for _ in 0..40 { + harness.step(); + } + testing::settle(&mut harness, |bench| &bench.backend); + assert_eq!(cards(&harness), 1); + } +} diff --git a/crates/ui/src/notes/header/facets.rs b/crates/ui/src/notes/header/facets.rs index 9039f3705..8168e744b 100644 --- a/crates/ui/src/notes/header/facets.rs +++ b/crates/ui/src/notes/header/facets.rs @@ -1093,4 +1093,135 @@ mod tests { let badge = badge.expect("the count sits on a badge of its own"); assert!(badge.left() > name.right(), "{name:?} {badge:?}"); } + + /// Two notes of one tag, language and level each, and one with none; the band open. + fn faceted() -> Harness<'static, Bench> { + use engine::notes::language::Language; + use engine::notes::priority::Priority; + + let (backend, profile) = testing::unlocked(); + for (title, tag, language, priority) in [ + ("a", "ops", Language::Sh, Priority::High), + ("b", "ops", Language::Sh, Priority::High), + ("c", "db", Language::Sql, Priority::Low), + ] { + let id = testing::note(&backend, title).id.clone(); + let patch = NotePatch { + tags: Some(vec![tag.to_owned()]), + language: Some(language), + ..NotePatch::default() + }; + engine::db::run_here(backend.engine(), move |engine| { + engine::notes::update_note(engine, &id, &patch)?; + engine::notes::set_priority(engine, &[id], priority) + }) + .unwrap(); + } + testing::note(&backend, "bare"); + let mut harness = area(backend, profile); + click_id(&mut harness, "facets-toggle"); + harness + } + + /// A value narrows, the two of a group widen, « All » gives every card back. + #[test] + fn each_group_narrows_by_its_values_and_all_undoes_it() { + for (menu, values, every) in [ + ( + "facet-menu-priority", + "priority-chip-high", + "priority-chip-all", + ), + ("facet-menu-tag", "tag-pill", "tag-all"), + ("facet-menu-language", "language-chip", "language-all"), + ] { + let mut harness = faceted(); + assert_eq!(cards(&harness), 4); + click_id(&mut harness, menu); + let value = harness + .query_all_by(|node| node.author_id() == Some(values)) + .last() + .unwrap(); + value.click(); + settle(&mut harness); + let narrowed = cards(&harness); + assert!(narrowed == 1 || narrowed == 2, "{menu}: {narrowed}"); + assert!(has(&harness, every), "{menu} stays open"); + + click_id(&mut harness, every); + assert_eq!(cards(&harness), 4, "{menu}"); + } + } + + #[test] + fn two_levels_ticked_show_the_notes_of_either() { + let mut harness = faceted(); + click_id(&mut harness, "facet-menu-priority"); + click_id(&mut harness, "priority-chip-high"); + assert_eq!(cards(&harness), 2); + click_id(&mut harness, "priority-chip-low"); + assert_eq!(cards(&harness), 3); + click_id(&mut harness, "priority-chip-high"); + assert_eq!(cards(&harness), 1); + } + + /// From the most pressing, each with its count; « none » is no level. + #[test] + fn the_levels_go_from_the_most_pressing_down() { + let mut harness = faceted(); + click_id(&mut harness, "facet-menu-priority"); + let levels: Vec = harness + .query_all_by(|node| { + node.author_id() + .is_some_and(|id| id.starts_with("priority-chip-")) + }) + .filter_map(|node| node.accesskit_node().author_id().map(str::to_owned)) + .collect(); + + assert_eq!( + levels, + [ + "priority-chip-all", + "priority-chip-urgent", + "priority-chip-high", + "priority-chip-medium", + "priority-chip-low", + ] + ); + } + + /// Nothing to narrow by, nothing offered. + #[test] + fn a_group_with_no_value_is_not_offered() { + let (backend, profile) = testing::unlocked(); + testing::note(&backend, "bare"); + let mut harness = area(backend, profile); + click_id(&mut harness, "facets-toggle"); + + assert!(has(&harness, "facet-menu-kind")); + assert!(!has(&harness, "facet-menu-priority") && !has(&harness, "facet-menu-tag")); + } + + #[test] + fn the_arrows_walk_a_menu_up_as_well_as_down() { + let mut harness = faceted(); + click_id(&mut harness, "facet-menu-kind"); + let focused = |harness: &Harness<'_, Bench>| { + harness + .query_all_by(|node| { + node.author_id() + .is_some_and(|id| id.starts_with("kind-chip-")) + }) + .position(|node| node.is_focused()) + }; + harness.key_press(egui::Key::ArrowDown); + settle(&mut harness); + harness.key_press(egui::Key::ArrowDown); + settle(&mut harness); + let down = focused(&harness).unwrap(); + harness.key_press(egui::Key::ArrowUp); + settle(&mut harness); + + assert_eq!(focused(&harness), Some(down - 1)); + } } diff --git a/crates/ui/src/notes/header/selection.rs b/crates/ui/src/notes/header/selection.rs index f1a4c3116..b19190ef0 100644 --- a/crates/ui/src/notes/header/selection.rs +++ b/crates/ui/src/notes/header/selection.rs @@ -401,6 +401,7 @@ fn level_key(level: Priority) -> i18n::Key { #[cfg(test)] mod tests { + use super::*; use egui::Modifiers; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; @@ -605,4 +606,108 @@ mod tests { assert_eq!(stored(&harness, &one).space_id, archive.id); } + + fn more(harness: &mut Harness<'_, Bench>, entry: &str) { + click_id(harness, "selection-more"); + click_id(harness, entry); + } + + /// By its sub-menu: the entry opens it, the rank in it is chosen. + fn more_of(harness: &mut Harness<'_, Bench>, entry: &str, rank: usize) { + click_id(harness, "selection-more"); + harness + .get_by(|node| node.author_id() == Some(entry)) + .focus(); + settle(harness); + harness.key_press(egui::Key::ArrowRight); + settle(harness); + click_id(harness, &format!("{entry}-{rank}")); + } + + #[test] + fn every_ticked_note_takes_the_level_chosen() { + let (mut harness, [one, two, three]) = three(); + ctrl_click(&mut harness, "one"); + ctrl_click(&mut harness, "two"); + for (rank, level) in LEVELS.into_iter().enumerate() { + more_of(&mut harness, "selection-more-priority", rank); + assert_eq!(stored(&harness, &one).priority, level); + assert_eq!(stored(&harness, &two).priority, level); + } + assert_eq!(stored(&harness, &three).priority, Priority::None); + } + + /// The tags any of them carries, each once, in their order. + #[test] + fn a_tag_of_any_ticked_note_can_be_taken_off() { + let (mut harness, [one, two, _]) = three(); + for (id, tags) in [(&one, ["ops", "db"]), (&two, ["ops", "api"])] { + let (id, tags) = (id.clone(), tags.map(str::to_owned).to_vec()); + let patch = engine::notes::model::NotePatch { + tags: Some(tags), + ..Default::default() + }; + engine::db::run_here(harness.state().backend.engine(), move |engine| { + engine::notes::update_note(engine, &id, &patch) + }) + .unwrap(); + } + let bench = harness.state_mut(); + bench.state.apply( + Action::Notes(crate::notes::Action::Reload), + &egui::Context::default(), + &bench.backend, + ); + settle(&mut harness); + ctrl_click(&mut harness, "one"); + ctrl_click(&mut harness, "two"); + more_of(&mut harness, "selection-more-untag", 2); + + assert_eq!(stored(&harness, &one).tags, ["db"]); + assert_eq!(stored(&harness, &two).tags, ["api"]); + } + + #[test] + fn with_no_tag_to_take_off_it_is_not_offered() { + let (mut harness, _) = three(); + ctrl_click(&mut harness, "one"); + click_id(&mut harness, "selection-more"); + + let offered = |id: &str| { + harness + .query_by(|node| node.author_id() == Some(id)) + .is_some() + }; + assert!(offered("selection-more-priority") && !offered("selection-more-untag")); + } + + #[test] + fn the_ticked_notes_are_copied_as_markdown() { + let (mut harness, _) = three(); + ctrl_click(&mut harness, "one"); + more(&mut harness, "selection-more-copy"); + crate::notes::bench::until(&mut harness, "it is copied", |harness| { + harness.state().state.status.latest().is_some() + }); + } + + /// Narrow, the row keeps the count: the rest is asked for under « … ». + #[test] + fn narrow_the_tag_and_the_pin_are_asked_for_under_more() { + let (mut harness, [one, ..]) = three(); + harness.set_size(egui::vec2(640.0, 700.0)); + settle(&mut harness); + ctrl_click(&mut harness, "one"); + more(&mut harness, "selection-more-pin"); + assert!(stored(&harness, &one).pinned); + more(&mut harness, "selection-more-pin"); + assert!(!stored(&harness, &one).pinned); + + // Narrower still: a rail drawn wide leaves the canvas little. + harness.set_size(egui::vec2(500.0, 700.0)); + settle(&mut harness); + more(&mut harness, "selection-more-tag"); + crate::notes::bench::type_and_enter(&mut harness, "selection-tag", "ops"); + assert_eq!(stored(&harness, &one).tags, ["ops"]); + } } diff --git a/crates/ui/src/notes/header/tests.rs b/crates/ui/src/notes/header/tests.rs index 5944da2f5..56579068d 100644 --- a/crates/ui/src/notes/header/tests.rs +++ b/crates/ui/src/notes/header/tests.rs @@ -1,11 +1,14 @@ //! The header over a real core: what it asks changes what the canvas shows. +use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use engine::notes::model::NotePatch; -use engine::notes::view::Grouping; +use engine::notes::view::{Grouping, SortKey}; -use crate::notes::bench::{area, cards, click, click_id, remembered, settle, until}; -use crate::state::notes_query::{ARRANGEMENT_KEY, Arrangement}; +use crate::notes::bench::{Bench, area, cards, click, click_id, remembered, settle, until}; +use crate::state::notes_query::{ + ARRANGEMENT_KEY, Arrangement, DIRECTIONS, SORT_KEYS, natural_order, +}; use crate::testing; fn headings(harness: &egui_kittest::Harness<'_, crate::notes::bench::Bench>) -> usize { @@ -251,3 +254,296 @@ fn a_moved_new_note_key_is_the_one_shown() { bindings.of(action) ); } + +// The order + +fn arrangement(harness: &Harness<'_, Bench>) -> Arrangement { + harness.state().state.notes_query.arrangement() +} + +fn sorting() -> Harness<'static, Bench> { + let (backend, profile) = testing::unlocked(); + testing::note(&backend, "psql prod"); + let mut harness = area(backend, profile); + click_id(&mut harness, "sort-trigger"); + harness +} + +fn choose(harness: &mut Harness<'_, Bench>, author_id: &str, rank: usize) { + harness + .query_all_by(|node| node.author_id() == Some(author_id)) + .nth(rank) + .unwrap() + .click(); + settle(harness); +} + +/// The newest first, the titles from A, the most urgent first. +#[test] +fn a_sort_key_starts_the_way_it_reads_first() { + for (rank, key) in SORT_KEYS.into_iter().enumerate() { + let mut harness = sorting(); + let (grouping, pinned_first) = ( + arrangement(&harness).grouping, + arrangement(&harness).pinned_first, + ); + choose(&mut harness, "sort-key", rank); + + let now = arrangement(&harness); + assert_eq!(now.order, natural_order(key), "{key:?}"); + assert_eq!( + (now.grouping, now.pinned_first), + (grouping, pinned_first), + "{key:?}" + ); + } +} + +#[test] +fn the_direction_turns_round_without_the_key() { + let mut harness = sorting(); + for (rank, direction) in DIRECTIONS.into_iter().enumerate().rev() { + choose(&mut harness, "sort-direction", rank); + let order = arrangement(&harness).order; + assert_eq!((order.direction, order.key), (direction, SortKey::Modified)); + } +} + +#[test] +fn the_pinned_notes_stand_first_or_not() { + let mut harness = sorting(); + let before = arrangement(&harness).pinned_first; + choose(&mut harness, "sort-pinned-first", 0); + assert_eq!(arrangement(&harness).pinned_first, !before); + choose(&mut harness, "sort-pinned-first", 0); + assert_eq!(arrangement(&harness).pinned_first, before); +} + +/// It is a choice of the menu, not a way back to the key's own direction. +#[test] +fn the_key_in_force_chosen_again_changes_nothing() { + let mut harness = sorting(); + choose(&mut harness, "sort-direction", 1); + let before = arrangement(&harness); + let rank = SORT_KEYS + .iter() + .position(|key| *key == before.order.key) + .unwrap(); + choose(&mut harness, "sort-key", rank); + + assert_eq!(arrangement(&harness), before); +} + +#[test] +fn a_wide_window_says_the_order_in_words() { + let mut harness = sorting(); + let said = |harness: &Harness<'_, Bench>| { + harness + .get_by(|node| node.author_id() == Some("sort-trigger")) + .rect() + .width() + }; + assert!(said(&harness) <= 32.0); + harness.set_size(egui::vec2(1_400.0, 700.0)); + settle(&mut harness); + + assert!(said(&harness) > 60.0); +} + +// The switchers + +/// A library of two spaces, the rail put away, the switcher `id` open. +fn switching(id: &str) -> Harness<'static, Bench> { + let (backend, profile) = testing::unlocked(); + testing::note(&backend, "in home"); + crate::notes::bench::space(&backend, "Work"); + let home = crate::notes::bench::spaces_of_backend(&backend)[0].clone(); + crate::notes::bench::folder(&backend, &home, None, "Runbooks"); + let mut harness = area(backend, profile); + hide_the_rail(&mut harness); + click_id(&mut harness, id); + harness +} + +fn present(harness: &Harness<'_, Bench>, author_id: &str) -> bool { + harness + .query_all_by(|node| node.author_id() == Some(author_id)) + .next() + .is_some() +} + +fn retype(harness: &mut Harness<'_, Bench>, author_id: &str, words: &str) { + harness + .get_by(|node| node.author_id() == Some(author_id)) + .focus(); + settle(harness); + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + crate::notes::bench::type_and_enter(harness, author_id, words); +} + +#[test] +fn every_space_is_one_choice_of_the_switcher() { + let mut harness = switching("space-switcher"); + click(&mut harness, "space-option", "Work"); + click_id(&mut harness, "space-switcher"); + click_id(&mut harness, "space-option-all"); + + assert_eq!(harness.state().state.spaces.active_space(), None); + assert!(!present(&harness, "space-option"), "it closed"); +} + +#[test] +fn a_space_is_renamed_and_pinned_from_its_options() { + let mut harness = switching("space-switcher"); + click(&mut harness, "space-edit", "Options for space Work"); + click_id(&mut harness, "space-pin"); + let work = |harness: &Harness<'_, Bench>| { + let spaces = crate::notes::bench::spaces_of(harness); + spaces + .into_iter() + .find(|space| space.name == "Work" || space.name == "Job") + .unwrap() + }; + assert!(work(&harness).pinned); + + retype(&mut harness, "space-rename-input", "Job"); + assert_eq!(work(&harness).name, "Job"); + assert!(!present(&harness, "space-rename-input"), "Enter closed it"); +} + +#[test] +fn a_space_deleted_hands_its_notes_to_the_other_once_confirmed() { + let mut harness = switching("space-switcher"); + let home = crate::notes::bench::spaces_of(&harness) + .into_iter() + .find(|space| space.name != "Work") + .unwrap(); + click( + &mut harness, + "space-edit", + &format!("Options for space {}", home.name), + ); + click_id(&mut harness, "space-delete"); + assert_eq!( + crate::notes::bench::spaces_of(&harness).len(), + 2, + "asked first" + ); + click_id(&mut harness, "space-delete"); + + let spaces = crate::notes::bench::spaces_of(&harness); + assert_eq!( + spaces + .iter() + .map(|space| space.name.as_str()) + .collect::>(), + ["Work"] + ); + assert_eq!(cards(&harness), 1); +} + +/// Opened again, it is the list. +#[test] +fn a_panel_left_open_is_not_there_the_next_time() { + for (switcher, edit, name, field) in [ + ( + "space-switcher", + "space-edit", + "Options for space Work", + "space-rename-input", + ), + ( + "folder-switcher", + "folder-edit", + "Options for folder Runbooks", + "folder-rename-input", + ), + ] { + let mut harness = switching(switcher); + click(&mut harness, edit, name); + assert!(present(&harness, field)); + harness.key_press(egui::Key::Escape); + settle(&mut harness); + click_id(&mut harness, switcher); + assert!( + !present(&harness, field) && present(&harness, edit), + "{switcher}" + ); + } +} + +#[test] +fn a_folder_is_made_in_the_space_shown() { + let mut harness = switching("space-switcher"); + click(&mut harness, "space-option", "Work"); + click_id(&mut harness, "folder-switcher"); + click_id(&mut harness, "folder-create-open"); + crate::notes::bench::type_and_enter(&mut harness, "folder-create-input", "Backlog"); + + let work = harness + .state() + .state + .spaces + .active_space() + .unwrap() + .to_owned(); + let folders = harness.state().state.folders.list(); + let made = folders + .iter() + .find(|folder| folder.name == "Backlog") + .unwrap(); + assert_eq!( + (made.space_id.as_str(), made.parent_id.as_deref()), + (work.as_str(), None) + ); +} + +/// Across every space, nothing says which one it would be in. +#[test] +fn no_folder_is_made_across_every_space() { + let harness = switching("folder-switcher"); + + assert!(present(&harness, "folder-option"), "every folder is listed"); + assert!(present(&harness, "folder-create-blocked")); + assert!(!present(&harness, "folder-create-open")); +} + +#[test] +fn the_folder_switcher_lists_the_folders_of_the_space_shown() { + let mut harness = switching("space-switcher"); + click(&mut harness, "space-option", "Work"); + click_id(&mut harness, "folder-switcher"); + assert!(!present(&harness, "folder-option")); + + click_id(&mut harness, "folder-option-all"); + assert!(!present(&harness, "folder-option-all"), "it closed"); +} + +#[test] +fn a_folder_is_renamed_and_deleted_from_its_options() { + let mut harness = switching("folder-switcher"); + click(&mut harness, "folder-edit", "Options for folder Runbooks"); + retype(&mut harness, "folder-rename-input", "Guides"); + let named = |harness: &Harness<'_, Bench>| -> Vec { + let folders = harness.state().state.folders.list(); + folders.iter().map(|folder| folder.name.clone()).collect() + }; + assert_eq!(named(&harness), ["Guides"]); + + click_id(&mut harness, "folder-switcher"); + click(&mut harness, "folder-edit", "Options for folder Guides"); + click_id(&mut harness, "folder-delete"); + assert_eq!(named(&harness).len(), 1, "asked first"); + click_id(&mut harness, "folder-delete"); + assert!(named(&harness).is_empty()); +} + +#[test] +fn the_folder_open_is_told_from_the_breadcrumb() { + let mut harness = switching("folder-switcher"); + click(&mut harness, "folder-option", "Runbooks"); + click_id(&mut harness, "folder-breadcrumb-menu"); + retype(&mut harness, "folder-rename-input", "Guides"); + + assert_eq!(harness.state().state.folders.list()[0].name, "Guides"); +} diff --git a/crates/ui/src/notes/overlays/editor/calc/tests.rs b/crates/ui/src/notes/overlays/editor/calc/tests.rs index 0fcb7ea82..9315f2623 100644 --- a/crates/ui/src/notes/overlays/editor/calc/tests.rs +++ b/crates/ui/src/notes/overlays/editor/calc/tests.rs @@ -240,3 +240,93 @@ fn where_a_name_is_read_is_said() { assert_eq!(used_on(&[2], Language::En), "used on line 3"); assert_eq!(used_on(&[2, 4], Language::En), "used on lines 3, 5"); } + +fn computed(text: &str) -> engine::notes::calc::CalcSheet { + let today = chrono::NaiveDate::from_ymd_opt(2026, 11, 4).unwrap(); + engine::notes::calc::evaluate(text, today) +} + +fn proposed(text: &str) -> (usize, Vec) { + let sheet = computed(text); + super::completions(text, text.chars().count(), Some(&sheet), i18n::Language::En) +} + +/// The units of the line's kind after a conversion word, the words of the table elsewhere. +#[test] +fn what_is_proposed_follows_what_is_before_the_caret() { + let (from, units) = proposed("a = 1\n3 km in m"); + assert_eq!(from, "a = 1\n3 km in ".len()); + assert!( + units.contains(&"mi".to_owned()) && !units.contains(&"kg".to_owned()), + "{units:?}" + ); + + let (from, words) = proposed("2\ntod"); + assert_eq!((from, words), (2, vec!["today".to_owned()])); + for text in ["# tod", "2 // tod", "2\n"] { + assert!(proposed(text).1.is_empty(), "{text}"); + } + let (_, units) = super::completions("3 km in m", 9, None, i18n::Language::En); + assert!(units.is_empty(), "not computed yet"); +} + +#[test] +fn a_name_hovered_says_its_value_where_it_was_given_and_where_it_is_read() { + let text = "é = 1\nprix = 1234.5 €\nprix × 2\nautre = 3"; + let sheet = computed(text); + let said = |at| super::hovered(text, Some(&sheet), at, i18n::Language::En); + let name = text.find("prix = ").unwrap() - 1; + + for at in [ + name, + name + 4, + text.chars().count() - "prix × 2\nautre = 3".chars().count() + 1, + ] { + let words = said(at).unwrap_or_default().replace('\u{a0}', " "); + assert!( + words.starts_with("prix = 1234.5 €\n") && words.contains('2') && words.contains('3'), + "{at}: {words}" + ); + } + assert_eq!(said(name + 8), None, "a number"); + let unused = said(text.chars().count() - "autre = 3".len()).unwrap(); + assert!( + unused.contains(&used_on(&[], i18n::Language::En)), + "{unused}" + ); + assert_eq!(super::hovered(text, None, name, i18n::Language::En), None); +} + +/// Given twice, the one above. +#[test] +fn a_name_given_again_is_the_last_one_above() { + let text = "a = 1\na\na = 2\na"; + let sheet = computed(text); + let said = |line: usize| { + let at = text.split('\n').take(line).map(|it| it.len() + 1).sum(); + super::hovered(text, Some(&sheet), at, i18n::Language::En).unwrap() + }; + + assert!(said(1).starts_with("a = 1\n")); + assert!(said(3).starts_with("a = 2\n")); +} + +#[test] +fn each_kind_of_word_has_its_colour() { + use engine::notes::calc::TokenKind; + + let p = crate::theme::palette(&egui::Context::default()); + for (kind, colour) in [ + (TokenKind::Number, p.amber_text), + (TokenKind::Unit, p.teal), + (TokenKind::Operator, p.text_1), + (TokenKind::Keyword, p.purple), + (TokenKind::Name, p.blue), + (TokenKind::Date, p.green), + (TokenKind::Comment, p.text_2), + (TokenKind::Heading, p.text_0), + (TokenKind::Error, p.red), + ] { + assert_eq!(super::colour(p, kind), colour); + } +} diff --git a/crates/ui/src/notes/overlays/editor/checklist/tests.rs b/crates/ui/src/notes/overlays/editor/checklist/tests.rs index b6e8856fb..160bd13aa 100644 --- a/crates/ui/src/notes/overlays/editor/checklist/tests.rs +++ b/crates/ui/src/notes/overlays/editor/checklist/tests.rs @@ -265,3 +265,145 @@ fn expanded_the_tasks_shown_narrow_to_those_open_or_done() { "a task added shows them all" ); } + +/// The list, the row and the caret it leaves, and whether there is something to write. +type Done = (Vec<(String, bool)>, Option<(usize, usize)>, bool); + +fn view(items: &[(&str, bool)]) -> super::ChecklistView { + super::ChecklistView { + items: items.iter().map(|(text, done)| item(text, *done)).collect(), + ..super::ChecklistView::default() + } +} + +fn after(items: &[(&str, bool)], index: usize, outcome: super::Outcome) -> Done { + let mut view = view(items); + let written = super::apply(&mut view, index, outcome); + let items = view + .items + .into_iter() + .map(|item| (item.text, item.done)) + .collect(); + (items, view.focus, written) +} + +#[test] +fn each_thing_a_row_asks_is_done_to_the_list() { + use super::{Outcome, RowKey}; + + let two = [("un", false), ("deux", true)]; + let end = usize::MAX; + for (index, outcome, items, focus, written) in [ + ( + 1, + Outcome::Toggled, + vec![("un", false), ("deux", false)], + None, + true, + ), + ( + 1, + Outcome::Removed, + vec![("un", false)], + Some((0, end)), + true, + ), + ( + 0, + Outcome::Removed, + vec![("deux", true)], + Some((0, end)), + true, + ), + (0, Outcome::Left, two.to_vec(), None, true), + ( + 0, + Outcome::Dropped(1), + vec![("deux", true), ("un", false)], + None, + true, + ), + (0, Outcome::Dropped(0), two.to_vec(), None, false), + (0, Outcome::Dropped(2), two.to_vec(), None, false), + (0, Outcome::Key(RowKey::Move(-1)), two.to_vec(), None, false), + ( + 1, + Outcome::Key(RowKey::Split(2)), + vec![("un", false), ("de", true), ("ux", false)], + Some((2, 0)), + true, + ), + ( + 1, + Outcome::Key(RowKey::Split(9)), + vec![("un", false), ("deux", true), ("", false)], + Some((2, 0)), + true, + ), + ( + 1, + Outcome::Key(RowKey::Join), + vec![("undeux", false)], + Some((0, 2)), + true, + ), + (0, Outcome::Key(RowKey::Join), two.to_vec(), None, false), + ( + 1, + Outcome::Key(RowKey::Remove), + vec![("un", false)], + Some((0, end)), + true, + ), + ( + 0, + Outcome::Key(RowKey::Paste(Vec::new())), + two.to_vec(), + None, + true, + ), + ] { + let (list, at, wrote) = after(&two, index, outcome); + assert_eq!(list, owned(&items)); + assert_eq!(wrote, written, "{items:?}"); + if focus.is_some() { + assert_eq!(at, focus, "{items:?}"); + } + } + let (list, focus, _) = after(&[("seul", false)], 0, super::Outcome::Removed); + assert!(list.is_empty() && focus.is_none()); +} + +/// What the row held goes before the first line, its tick with it; on an empty row, the lines alone. +#[test] +fn lines_pasted_follow_what_the_row_held() { + let lines = || super::RowKey::Paste(vec!["- [x] a".to_owned(), "2. b".to_owned()]); + let (list, focus, _) = after( + &[("avant ", false), ("suite", false)], + 0, + super::Outcome::Key(lines()), + ); + assert_eq!( + list, + owned(&[("avant a", false), ("b", false), ("suite", false)]) + ); + assert_eq!(focus, Some((1, 1))); + + let (list, _, _) = after(&[(" ", false)], 0, super::Outcome::Key(lines())); + assert_eq!(list, owned(&[("a", true), ("b", false)])); +} + +/// The drag's keyboard twin, from the grip as from the row. +#[test] +fn the_grip_moves_its_task_with_alt_and_an_arrow() { + let (mut harness, _) = list(&[item("un", false), item("deux", false)]); + harness + .query_all_by(|node| node.author_id() == Some("checklist-grip")) + .next() + .unwrap() + .focus(); + settle(&mut harness); + press(&mut harness, Modifiers::ALT, Key::ArrowDown); + + assert_eq!(rows(&harness), ["deux", "un"]); +} diff --git a/crates/ui/src/notes/overlays/editor/format/tests.rs b/crates/ui/src/notes/overlays/editor/format/tests.rs index 8eed1ff8d..8e692d92e 100644 --- a/crates/ui/src/notes/overlays/editor/format/tests.rs +++ b/crates/ui/src/notes/overlays/editor/format/tests.rs @@ -221,3 +221,105 @@ fn a_body_left_is_formatted_on_save_when_the_library_asks() { stored(harness, &id) == "const b = 1;" }); } + +#[test] +fn what_is_formatted_already_says_so() { + let (mut harness, _) = snippet(TIDY, Language::Ts); + click_id(&mut harness, "editor-format"); + until(&mut harness, "it is said", |harness| { + notice(harness).as_deref() == Some("unchanged") + }); + assert_eq!(code(&harness), TIDY); +} + +#[test] +fn the_notice_goes_once_typed_over() { + let (mut harness, _) = snippet(TIDY, Language::Ts); + click_id(&mut harness, "editor-format"); + until(&mut harness, "it is said", |harness| { + notice(harness).is_some() + }); + click_id(&mut harness, "editor-body"); + harness + .get_by(|node| node.author_id() == Some("editor-body")) + .type_text("x"); + settle(&mut harness); + + assert_eq!(notice(&harness), None); +} + +#[test] +fn the_notice_goes_by_itself() { + let (mut harness, _) = snippet(TIDY, Language::Ts); + click_id(&mut harness, "editor-format"); + until(&mut harness, "it is said", |harness| { + notice(harness).is_some() + }); + for _ in 0..60 { + harness.step(); + } + + assert_eq!(notice(&harness), None); +} + +/// Written so by the core; the field follows rather than writing the older text back. +#[test] +fn the_field_follows_what_was_formatted_on_save() { + let (mut harness, _) = snippet("a", Language::Ts); + click_id(&mut harness, "editor-format-settings"); + click_id(&mut harness, "prettier-formatOnSave"); + harness.key_press(Key::Escape); + settle(&mut harness); + click_id(&mut harness, "editor-body"); + harness.key_press_modifiers(Modifiers::COMMAND, Key::A); + harness + .get_by(|node| node.author_id() == Some("editor-body")) + .type_text("const b=1"); + settle(&mut harness); + click_id(&mut harness, "editor-title"); + + formatted(&mut harness, "const b = 1;"); +} + +/// Within what Prettier takes, and what is not a number is not taken. +#[test] +fn a_width_is_taken_once_its_field_is_left() { + for (typed, width) in [("80", 80), ("9999", 200), ("3", 40), ("wide", 100)] { + let (mut harness, _) = snippet("a", Language::Ts); + click_id(&mut harness, "editor-format-settings"); + let before = harness.state().state.prettier.print_width; + click_id(&mut harness, "prettier-width"); + harness.key_press_modifiers(Modifiers::COMMAND, Key::A); + harness + .get_by(|node| node.author_id() == Some("prettier-width")) + .type_text(typed); + settle(&mut harness); + assert_eq!( + harness.state().state.prettier.print_width, + before, + "not yet" + ); + harness.key_press(Key::Enter); + settle(&mut harness); + assert_eq!(harness.state().state.prettier.print_width, width, "{typed}"); + } +} + +#[test] +fn prettier_s_line_and_column_are_a_place_in_the_text() { + let buffer = text::Buffer::new("ab\ncdé\n"); + for ((line, column), at) in [ + ((1, 1), 0), + ((1, 3), 2), + ((2, 2), 4), + ((2, 99), 6), + ((0, 0), 0), + ((99, 1), 7), + ] { + assert_eq!( + super::offset_of(&buffer, line, column), + at, + "{line}:{column}" + ); + } +} diff --git a/crates/ui/src/notes/overlays/editor/json_view/tests.rs b/crates/ui/src/notes/overlays/editor/json_view/tests.rs index d670ce0b3..7ca203717 100644 --- a/crates/ui/src/notes/overlays/editor/json_view/tests.rs +++ b/crates/ui/src/notes/overlays/editor/json_view/tests.rs @@ -271,3 +271,109 @@ fn a_yaml_snippet_is_explored_and_plain_text_is_not() { }; assert!(!has(&harness, "editor-view-graph")); } + +#[test] +fn another_language_is_another_reader_or_none() { + let mut harness = snippet(EVENT, Language::Json); + graph(&mut harness); + let pick = |harness: &mut Harness<'_>, language: Language| { + let edit = crate::state::editor::Edit { + language: Some(language), + ..Default::default() + }; + let session = harness.state().state.editor.opened().unwrap().session; + let bench = harness.state_mut(); + let save = crate::notes::Action::Editor(crate::notes::Editing::Save { session, edit }); + bench.state.apply( + crate::action::Action::Notes(save), + &egui::Context::default(), + &bench.backend, + ); + settle(harness); + }; + pick(&mut harness, Language::Yml); + assert!(has(&harness, "editor-view-graph")); + assert!(!has(&harness, "json-node-head"), "back to the code"); + pick(&mut harness, Language::Sh); + assert!(!has(&harness, "editor-view-graph")); +} + +/// The code keeps its floor; what is left is said to be too little. +#[test] +fn too_narrow_for_both_it_says_so_and_shows_one_at_a_time() { + let mut harness = snippet(EVENT, Language::Json); + click_id(&mut harness, "editor-side-by-side"); + until(&mut harness, "side by side", |harness| { + has(harness, "side-by-side") + }); + harness.set_size(egui::vec2(760.0, 800.0)); + settle(&mut harness); + + assert!(has(&harness, "editor-side-by-side-narrow")); + assert!(!has(&harness, "side-by-side")); + let toggle = harness.get_by(|node| node.author_id() == Some("editor-side-by-side")); + assert!(toggle.accesskit_node().is_disabled()); +} + +#[test] +fn the_line_between_the_code_and_the_explorer_moves() { + let mut harness = snippet(EVENT, Language::Json); + click_id(&mut harness, "editor-side-by-side"); + until(&mut harness, "side by side", |harness| { + has(harness, "side-by-side") + }); + let left = |harness: &Harness<'_>| { + harness + .get_by(|node| node.author_id() == Some("side-by-side-handle")) + .rect() + .left() + }; + let before = left(&harness); + harness + .get_by(|node| node.author_id() == Some("side-by-side-handle")) + .focus(); + settle(&mut harness); + press(&mut harness, Modifiers::NONE, Key::ArrowRight); + press(&mut harness, Modifiers::NONE, Key::ArrowRight); + + assert!( + (left(&harness) - before - 32.0).abs() < 1.0, + "{before} {}", + left(&harness) + ); +} + +#[test] +fn the_tree_it_proposes_is_the_one_it_shows() { + let objects = vec![r#"{"a":1}"#; 200].join(","); + let arrays: Vec = (0..11).map(|n| format!(r#""k{n}":[{objects}]"#)).collect(); + let mut harness = snippet(&format!("{{{}}}", arrays.join(",")), Language::Json); + graph(&mut harness); + click_id(&mut harness, "json-open-all"); + until(&mut harness, "it is folded", |harness| { + has(harness, "json-show-tree") + }); + click_id(&mut harness, "json-show-tree"); + + assert!(has(&harness, "json-tree")); +} + +/// Explored a moment after the typing, not at each key. +#[test] +fn what_is_typed_is_explored_once_the_keys_rest() { + let mut harness = snippet(r#"{"a":1}"#, Language::Json); + click_id(&mut harness, "editor-body"); + press(&mut harness, Modifiers::COMMAND, Key::A); + harness + .get_by(|node| node.author_id() == Some("editor-body")) + .type_text(r#"{"a":1,"#); + until(&mut harness, "the draft refused", |harness| { + said(harness, "editor-json-validity").contains("line") + }); + harness + .get_by(|node| node.author_id() == Some("editor-body")) + .type_text(r#""b":2}"#); + until(&mut harness, "the draft read", |harness| { + !said(harness, "editor-json-validity").contains("line") + }); +} diff --git a/crates/ui/src/notes/overlays/editor/revisions/tests.rs b/crates/ui/src/notes/overlays/editor/revisions/tests.rs index 641807047..573b7f000 100644 --- a/crates/ui/src/notes/overlays/editor/revisions/tests.rs +++ b/crates/ui/src/notes/overlays/editor/revisions/tests.rs @@ -99,3 +99,84 @@ fn a_new_note_and_a_todo_list_offer_no_history() { .is_none() ); } + +/// A snippet whose body was each of `bodies` in turn, its history open. +fn rewritten(bodies: &[String]) -> Harness { + let (backend, profile) = testing::unlocked(); + let id = testing::note(&backend, "psql").id.clone(); + let bodies = bodies.to_vec(); + engine::db::run_here(backend.engine(), move |engine| { + for body in bodies { + let patch = NotePatch { + content: Some(body), + ..NotePatch::default() + }; + engine::notes::update_note(engine, &id, &patch)?; + } + Ok::<_, engine::error::AppError>(()) + }) + .unwrap(); + let mut harness = expanded_area(backend, profile); + click_id(&mut harness, "note-card-open"); + click_id(&mut harness, "revisions-toggle"); + harness +} + +fn look(harness: &mut Harness, rank: usize) { + harness + .query_all_by(|node| node.author_id() == Some("revision-open")) + .nth(rank) + .unwrap() + .click(); + settle(harness); +} + +fn shown(harness: &Harness, author_id: &str) -> Vec { + use egui_kittest::kittest::NodeT; + + harness + .query_all_by(|node| node.author_id() == Some(author_id)) + .map(|node| { + let node = node.accesskit_node(); + node.value().or_else(|| node.label()).unwrap_or_default() + }) + .collect() +} + +/// The newest kept first; the one before the last edit was the same text. +#[test] +fn a_body_that_is_the_one_on_screen_says_so() { + let mut harness = rewritten(&["B".to_owned(), "A".to_owned(), "B".to_owned()]); + look(&mut harness, 1); + + assert_eq!(shown(&harness, "revision-identical").len(), 1); + assert!(shown(&harness, "diff-kept").is_empty()); +} + +#[test] +fn the_lines_far_from_a_change_are_counted_rather_than_shown() { + let lines: Vec = (0..40).map(|at| format!("line {at}")).collect(); + let mut changed = lines.clone(); + changed[20] = "line twenty".to_owned(); + let mut harness = rewritten(&[lines.join("\n"), changed.join("\n")]); + look(&mut harness, 0); + + assert_eq!(shown(&harness, "diff-restored"), ["+ line 20"]); + assert_eq!(shown(&harness, "diff-dropped"), ["− line twenty"]); + let kept = shown(&harness, "diff-kept"); + assert!(!kept.is_empty() && kept.len() < 10, "{kept:?}"); + assert_eq!(shown(&harness, "diff-skipped").len(), 2, "above and below"); +} + +/// What is put back erases what came after it. +#[test] +fn the_consequence_counts_the_newer_bodies() { + let bodies: Vec = ["B", "C", "D"].map(str::to_owned).to_vec(); + let warned = |rank| { + let mut harness = rewritten(&bodies); + look(&mut harness, rank); + shown(&harness, "revision-consequence").join("") + }; + + assert_ne!(warned(0), warned(2)); +} diff --git a/crates/ui/src/notes/overlays/editor/rich/tests.rs b/crates/ui/src/notes/overlays/editor/rich/tests.rs index 3fc463954..a48db0f94 100644 --- a/crates/ui/src/notes/overlays/editor/rich/tests.rs +++ b/crates/ui/src/notes/overlays/editor/rich/tests.rs @@ -1003,3 +1003,156 @@ abcd abcd|ef" ); } + +/// The whole of `content` selected, then the keys; what is stored. +fn formatted(content: &str, modifiers: Modifiers, key: Key) -> String { + let (mut harness, id) = note(content); + click_id(&mut harness, "editor-rich"); + press(&mut harness, Modifiers::COMMAND, Key::A); + press(&mut harness, modifiers, key); + click_id(&mut harness, "editor-close"); + stored(&harness, &id) +} + +#[test] +fn each_shortcut_formats_what_is_selected() { + let (ctrl, shift, alt) = (Modifiers::COMMAND, Modifiers::SHIFT, Modifiers::ALT); + for (modifiers, key, markdown) in [ + (ctrl, Key::B, "**mot**"), + (ctrl, Key::I, "*mot*"), + (ctrl | shift, Key::S, "~~mot~~"), + (ctrl, Key::E, "`mot`"), + (ctrl | alt, Key::Num1, "# mot"), + (ctrl | alt, Key::Num6, "###### mot"), + (ctrl | shift, Key::Num7, "1. mot"), + (ctrl | shift, Key::Num8, "- mot"), + (ctrl | shift, Key::Num9, "- [ ] mot"), + (ctrl | shift, Key::B, "> mot"), + (ctrl | alt, Key::C, "```\nmot\n```"), + ] { + assert_eq!( + formatted("mot", modifiers, key), + markdown, + "{modifiers:?} {key:?}" + ); + } + assert_eq!(formatted("## mot", ctrl | alt, Key::Num0), "mot"); +} + +/// Nothing selected, it is what is typed next that takes the mark. +#[test] +fn a_mark_asked_with_nothing_selected_is_the_next_word_s() { + for (key, shift, markdown) in [ + (Key::I, false, "un *x*"), + (Key::S, true, "un ~~x~~"), + (Key::E, false, "un `x`"), + ] { + let (mut harness, id) = note("un "); + at_end(&mut harness); + let modifiers = if shift { + Modifiers::COMMAND | Modifiers::SHIFT + } else { + Modifiers::COMMAND + }; + key_by_key(&mut harness, " "); + press(&mut harness, modifiers, key); + type_in(&mut harness, "x"); + click_id(&mut harness, "editor-close"); + assert_eq!(stored(&harness, &id), markdown, "{key:?}"); + } +} + +#[test] +fn a_line_broken_stays_in_its_paragraph() { + for modifiers in [Modifiers::SHIFT, Modifiers::COMMAND] { + let (mut harness, _) = note("un"); + at_end(&mut harness); + press(&mut harness, modifiers, Key::Enter); + type_in(&mut harness, "deux"); + assert_eq!(surface_text(&harness), "un\ndeux", "{modifiers:?}"); + click_id(&mut harness, "editor-close"); + } +} + +/// Its own undo, whatever runs after. +#[test] +fn redo_puts_back_what_undo_took() { + for (modifiers, key) in [ + (Modifiers::COMMAND, Key::Y), + (Modifiers::COMMAND | Modifiers::SHIFT, Key::Z), + ] { + let (mut harness, _) = note("un"); + at_end(&mut harness); + type_in(&mut harness, " deux"); + press(&mut harness, Modifiers::COMMAND, Key::Z); + assert_eq!(surface_text(&harness), "un"); + press(&mut harness, modifiers, key); + assert_eq!(surface_text(&harness), "un deux", "{key:?}"); + } +} + +#[test] +fn a_tab_outside_a_list_is_text_and_shift_tab_takes_it_back() { + let (mut harness, _) = note("mot"); + click_id(&mut harness, "editor-rich"); + press(&mut harness, Modifiers::COMMAND, Key::Home); + press(&mut harness, Modifiers::NONE, Key::Tab); + assert_eq!(surface_text(&harness), "\tmot"); + press(&mut harness, Modifiers::SHIFT, Key::Tab); + assert_eq!(surface_text(&harness), "mot"); + press(&mut harness, Modifiers::SHIFT, Key::Tab); + assert_eq!(surface_text(&harness), "mot", "nothing more to take"); + type_in(&mut harness, "|"); + assert_eq!(surface_text(&harness), "|mot", "the caret stayed"); +} + +#[test] +fn shift_tab_takes_a_level_off_a_line_of_code() { + let (mut harness, _) = note("```rs\n let a = 1;\n```"); + click_id(&mut harness, "editor-rich"); + press(&mut harness, Modifiers::COMMAND, Key::End); + press(&mut harness, Modifiers::SHIFT, Key::Tab); + + assert_eq!(surface_text(&harness), "let a = 1;"); +} + +#[test] +fn the_menu_cuts_what_is_selected_and_asks_for_what_to_paste() { + let (mut harness, _) = note("hello world"); + click_id(&mut harness, "editor-rich"); + press(&mut harness, Modifiers::COMMAND, Key::Home); + press( + &mut harness, + Modifiers::SHIFT | Modifiers::COMMAND, + Key::ArrowRight, + ); + let menu = |harness: &mut Harness<'_>| { + harness + .get_by(|node| node.author_id() == Some("editor-rich")) + .click_secondary(); + settle(harness); + }; + menu(&mut harness); + menu_entry(&harness, "rich-menu-cut"); + assert_eq!(clipboard(&mut harness).as_deref(), Some("hello")); + assert_eq!(surface_text(&harness), " world"); + + menu(&mut harness); + menu_entry(&harness, "rich-menu-paste"); + let mut asked = false; + for _ in 0..4 { + harness.step(); + asked |= harness.output().viewport_output.values().any(|viewport| { + viewport + .commands + .contains(&egui::ViewportCommand::RequestPaste) + }); + } + assert!(asked); + + menu(&mut harness); + menu_entry(&harness, "rich-menu-select-all"); + settle(&mut harness); + type_in(&mut harness, "x"); + assert_eq!(surface_text(&harness), "x"); +} diff --git a/crates/ui/src/notes/overlays/editor/tests.rs b/crates/ui/src/notes/overlays/editor/tests.rs index 04a5c64bc..6ed029b12 100644 --- a/crates/ui/src/notes/overlays/editor/tests.rs +++ b/crates/ui/src/notes/overlays/editor/tests.rs @@ -912,25 +912,42 @@ fn expanded_without_room_for_the_details_the_header_holds_them() { assert!(rect_of(&harness, "editor-space").bottom() < rect_of(&harness, "editor-body").top()); } +#[test] +fn a_tag_is_taken_off_by_its_cross() { + let (backend, profile) = testing::unlocked(); + let id = testing::note(&backend, "psql").id.clone(); + let patch = engine::notes::model::NotePatch { + tags: Some(vec!["db".to_owned(), "ops".to_owned()]), + ..Default::default() + }; + let at = id.clone(); + engine::db::run_here(backend.engine(), move |engine| { + engine::notes::update_note(engine, &at, &patch) + }) + .unwrap(); + let mut harness = crate::notes::bench::expanded_area(backend, profile); + click_id(&mut harness, "note-card-open"); + harness + .query_all_by(|node| node.author_id() == Some("editor-tag-remove")) + .next() + .unwrap() + .click(); + settle(&mut harness); + + assert_eq!(stored(&harness, &id).tags, ["ops"]); +} + /// Enter keeps the field for the next one. #[test] fn tags_are_added_one_after_the_other() { - for expanded in [false, true] { - let (backend, profile) = testing::unlocked(); - let id = testing::note(&backend, "psql").id.clone(); - let mut harness = if expanded { - crate::notes::bench::expanded_area(backend, profile) - } else { - area(backend, profile) - }; - click_id(&mut harness, "note-card-open"); - click_id(&mut harness, "editor-tag-add"); - for tag in ["db", "ops", "api"] { - crate::notes::bench::type_and_enter(&mut harness, "editor-tag-add", tag); - } - - let mut tags = stored(&harness, &id).tags.clone(); - tags.sort(); - assert_eq!(tags, ["api", "db", "ops"], "expanded: {expanded}"); + let (backend, profile) = testing::unlocked(); + let id = testing::note(&backend, "psql").id.clone(); + let mut harness = crate::notes::bench::expanded_area(backend, profile); + click_id(&mut harness, "note-card-open"); + click_id(&mut harness, "editor-tag-add"); + for tag in ["db", "ops"] { + crate::notes::bench::type_and_enter(&mut harness, "editor-tag-add", tag); } + + assert_eq!(stored(&harness, &id).tags, ["db", "ops"]); } diff --git a/crates/ui/src/notes/overlays/tag_manager.rs b/crates/ui/src/notes/overlays/tag_manager.rs index a461ddfb1..8c7b2d48e 100644 --- a/crates/ui/src/notes/overlays/tag_manager.rs +++ b/crates/ui/src/notes/overlays/tag_manager.rs @@ -699,4 +699,45 @@ mod tests { assert_eq!(listed(&harness), ["#preprod", "#staging"]); assert_eq!(crate::notes::bench::cards(&harness), 3); } + + /// Said before: it is the notes of both that end on one name. + #[test] + fn a_merge_is_asked_as_one() { + let mut harness = tagged(); + tick(&mut harness, "staging"); + propose(&mut harness, "preprod"); + let merged = said(&harness); + click_id(&mut harness, "tag-confirm-cancel"); + propose(&mut harness, "validation"); + + assert_ne!(merged, said(&harness)); + assert!(merged.contains("preprod"), "{merged}"); + } + + /// Unticked down to one, it is that one's name that is edited. + #[test] + fn the_last_tag_left_ticked_fills_the_field() { + let mut harness = tagged(); + tick(&mut harness, "staging"); + tick(&mut harness, "urgent"); + tick(&mut harness, "staging"); + + assert_eq!(field(&harness), "urgent"); + } + + #[test] + fn a_library_with_no_tag_says_so() { + let (backend, profile) = testing::unlocked(); + testing::note(&backend, "alpha"); + let mut harness = area(backend, profile); + let bench = harness.state_mut(); + bench.state.apply( + crate::action::Action::Notes(crate::notes::Action::Tags(crate::notes::Tags::Open)), + &egui::Context::default(), + &bench.backend, + ); + settle(&mut harness); + + harness.get_by(|node| node.author_id() == Some("tag-manager-empty")); + } } diff --git a/crates/ui/src/notes/overlays/trash_panel.rs b/crates/ui/src/notes/overlays/trash_panel.rs index 50efe194e..f1b358e7c 100644 --- a/crates/ui/src/notes/overlays/trash_panel.rs +++ b/crates/ui/src/notes/overlays/trash_panel.rs @@ -560,4 +560,36 @@ mod tests { assert_eq!(days_left(now + TimeDelta::hours(5), now), 0); assert_eq!(days_left(now - TimeDelta::hours(5), now), 0); } + + /// A list has no body to preview, a note with no title still has a row of its own. + #[test] + fn what_has_no_title_or_no_body_says_what_it_is() { + let (backend, profile) = testing::unlocked(); + let id = testing::note(&backend, "gone").id.clone(); + let patch = engine::notes::model::NotePatch { + title: Some(String::new()), + kind: Some(engine::notes::kind::NoteKind::Checklist), + content: Some(String::new()), + items: Some(vec![engine::notes::checklist::ChecklistItem { + text: "milk".to_owned(), + done: false, + }]), + ..Default::default() + }; + engine::db::run_here(backend.engine(), move |engine| { + engine::notes::update_note(engine, &id, &patch)?; + engine::notes::delete_notes(engine, &[id]) + }) + .unwrap(); + let mut harness = area(backend, profile); + click_id(&mut harness, "trash-open"); + let tr = |key| i18n::translate(i18n::Language::En, key, &[]); + + assert_eq!(rows(&harness), [tr(i18n::keys::trash::UNTITLED)]); + let painted = testing::painted(&harness); + assert!( + painted.contains(&tr(i18n::keys::trash::CHECKLIST_NOTE)), + "{painted:?}" + ); + } } diff --git a/crates/ui/src/notes/overlays/undo_bar.rs b/crates/ui/src/notes/overlays/undo_bar.rs index e0099f069..8ee4f845a 100644 --- a/crates/ui/src/notes/overlays/undo_bar.rs +++ b/crates/ui/src/notes/overlays/undo_bar.rs @@ -186,6 +186,7 @@ fn restore(ui: &mut Ui, language: i18n::Language, actions: &mut Actions) { #[cfg(test)] mod tests { + use super::*; use egui::{Key, Modifiers}; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; @@ -293,4 +294,57 @@ mod tests { let view = harness.state().state.notes_query.view().unwrap(); assert!(view.cards().all(|card| !card.pinned)); } + + /// « 3 notes deleted » and « 3 notes moved » are not the same sentence. + #[test] + fn each_kind_of_thing_undone_has_its_own_words() { + use engine::notes::convert::NoteBody; + + let pin = |pinned| Reversible::Pin { + ids: Vec::new(), + pinned, + }; + let converted = |into| Reversible::Convert { + id: String::new(), + into, + previous: NoteBody { + kind: NoteKind::Snippet, + language: engine::notes::language::Language::Txt, + content: String::new(), + items: Vec::new(), + }, + }; + let mut words: Vec = [ + Reversible::Deletion { + ids: Vec::new(), + count: 2, + }, + Reversible::Move(Vec::new()), + Reversible::Tag(Vec::new()), + Reversible::Untag(Vec::new()), + pin(true), + pin(false), + Reversible::Priority(Vec::new()), + Reversible::File(Vec::new()), + converted(NoteKind::Snippet), + converted(NoteKind::Note), + converted(NoteKind::Checklist), + converted(NoteKind::Calc), + converted(NoteKind::Drawing), + ] + .iter() + .map(|action| { + i18n::translate( + i18n::Language::En, + super::said(action), + &[("count", 2_u32.into())], + ) + }) + .collect(); + let count = words.len(); + words.sort(); + words.dedup(); + + assert_eq!(words.len(), count, "{words:?}"); + } } diff --git a/crates/ui/src/notes/prettier.rs b/crates/ui/src/notes/prettier.rs index a21cb37c5..7f5c24f38 100644 --- a/crates/ui/src/notes/prettier.rs +++ b/crates/ui/src/notes/prettier.rs @@ -181,4 +181,43 @@ mod tests { assert_eq!(clamp_width(12.4), Some(40)); assert_eq!(clamp_width(f64::NAN), None); } + + #[test] + fn what_is_written_reads_back_the_same() { + for indentation in Indentation::ALL { + for single_quote in [true, false] { + let settings = PrettierSettings { + print_width: 88, + indentation, + single_quote, + semicolons: single_quote, + trailing_commas: !single_quote, + format_on_save: single_quote, + }; + assert_eq!(PrettierSettings::read(Some(&settings.written())), settings); + } + } + } + + #[test] + fn each_indentation_is_what_prettier_is_asked() { + for (indentation, editor, (width, tabs)) in [ + (Indentation::Editor, " ", (3, false)), + (Indentation::Editor, "\t", (TAB_WIDTH, true)), + (Indentation::Two, " ", (2, false)), + (Indentation::Four, " ", (4, false)), + (Indentation::Tab, " ", (TAB_WIDTH, true)), + ] { + let settings = PrettierSettings { + indentation, + ..PrettierSettings::default() + }; + let options = settings.options(editor); + assert_eq!( + (options.tab_width, options.use_tabs), + (width, tabs), + "{indentation:?}" + ); + } + } } diff --git a/crates/ui/src/notes/sidebar/tests.rs b/crates/ui/src/notes/sidebar/tests.rs index ee1fefd50..25ee93e16 100644 --- a/crates/ui/src/notes/sidebar/tests.rs +++ b/crates/ui/src/notes/sidebar/tests.rs @@ -585,3 +585,146 @@ fn a_folder_deleted_with_its_notes_takes_its_sub_folder_and_trashes_them() { Some(i18n::keys::folders::DELETED_TRASHED) ); } + +fn shows(harness: &Harness<'_, Bench>, author_id: &str) -> bool { + harness + .query_all_by(|node| node.author_id() == Some(author_id)) + .next() + .is_some() +} + +fn press(harness: &mut Harness<'_, Bench>, key: egui::Key) { + harness.key_press(key); + settle(harness); +} + +/// A space « Work » beside « Home », which holds a folder « Runbooks ». +fn rail() -> Harness<'static, Bench> { + let (backend, profile) = testing::unlocked(); + let home = space(&backend, "Home"); + space(&backend, "Work"); + folder(&backend, &home, None, "Runbooks"); + area(backend, profile) +} + +const PANELS: [(&str, &str, &str, &str); 2] = [ + ( + "space-edit", + "Options for space Work", + "space-rename-input", + "space-rename-submit", + ), + ( + "folder-edit", + "Options for folder Runbooks", + "folder-rename-input", + "folder-rename-submit", + ), +]; + +/// Its ⋯ again, or Escape in its field. +#[test] +fn a_panel_closes_as_it_opened_or_on_escape() { + for (edit, name, field, _) in PANELS { + let mut harness = rail(); + click(&mut harness, edit, name); + assert!(shows(&harness, field)); + click(&mut harness, edit, name); + assert!(!shows(&harness, field), "{edit}"); + + click(&mut harness, edit, name); + press(&mut harness, egui::Key::Escape); + assert!(!shows(&harness, field), "{edit}"); + } +} + +fn every_name(harness: &Harness<'_, Bench>) -> Vec { + let mut names: Vec = spaces_of(harness) + .into_iter() + .map(|space| space.name) + .collect(); + let folders = harness.state().state.folders.list(); + names.extend(folders.iter().map(|folder| folder.name.clone())); + names +} + +#[test] +fn a_name_is_written_on_enter_and_by_its_button() { + for (edit, name, field, submit) in PANELS { + for by_button in [false, true] { + let mut harness = rail(); + click(&mut harness, edit, name); + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + harness + .get_by(|node| node.author_id() == Some(field)) + .type_text("Renamed"); + settle(&mut harness); + if by_button { + click_id(&mut harness, submit); + } else { + press(&mut harness, egui::Key::Enter); + } + assert!( + every_name(&harness).contains(&"Renamed".to_owned()), + "{edit}" + ); + assert!(!shows(&harness, field), "{edit} closed"); + } + } +} + +#[test] +fn escape_drops_the_name_of_what_was_being_made() { + for open in ["space-create-open", "folder-create-open"] { + let mut harness = rail(); + if open == "folder-create-open" { + click(&mut harness, "space-option", "Home"); + } + let before = every_name(&harness); + if !shows(&harness, open) { + continue; + } + click_id(&mut harness, open); + let input = open.replace("open", "input"); + harness + .get_by(|node| node.author_id() == Some(input.as_str())) + .type_text("Dropped"); + settle(&mut harness); + press(&mut harness, egui::Key::Escape); + + assert_eq!(every_name(&harness), before, "{open}"); + assert!(!shows(&harness, &input), "{open}"); + } +} + +/// Nothing to move, it is said rather than counted. +#[test] +fn a_space_with_no_note_says_so_before_it_goes() { + let mut harness = rail(); + click(&mut harness, "space-edit", "Options for space Work"); + crate::notes::bench::until(&mut harness, "it is counted", |harness| { + shows(harness, "space-delete-consequence") + }); + let said = said_by(&harness, "space-delete-consequence"); + let none = i18n::translate( + i18n::Language::En, + i18n::keys::notes::DELETE_SPACE_NO_NOTES, + &[], + ); + + assert!(said.starts_with(&none), "{said}"); +} + +#[test] +fn the_rail_s_width_is_kept_once_its_edge_rests() { + let mut harness = rail(); + harness + .get_by(|node| node.author_id() == Some("library-rail-edge")) + .focus(); + settle(&mut harness); + let before = harness.state().state.settings.rail_width; + press(&mut harness, egui::Key::ArrowRight); + press(&mut harness, egui::Key::ArrowRight); + + assert!(harness.state().state.settings.rail_width > before); +} From 91608ddcba43729592319cec97179e85ee683f03 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:55:01 +0100 Subject: [PATCH 87/95] HTTP: unit tests rewritten for the request, answer and dialogs (#1850) * HTTP: an inherited auth set to None says so Co-Authored-By: Claude Opus 5.5 * Interface: unit tests rewritten for the HTTP area Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/ui/src/http/code_tests.rs | 56 ++++++ crates/ui/src/http/console.rs | 3 + crates/ui/src/http/console/tests.rs | 178 +++++++++++++++++++ crates/ui/src/http/cookie_jar.rs | 3 + crates/ui/src/http/cookie_jar/tests.rs | 50 ++++++ crates/ui/src/http/dialogs_tests.rs | 74 ++++++++ crates/ui/src/http/environments.rs | 2 +- crates/ui/src/http/environments_tests.rs | 89 ++++++++++ crates/ui/src/http/history.rs | 3 + crates/ui/src/http/history/tests.rs | 20 +++ crates/ui/src/http/history_tests.rs | 55 ++++++ crates/ui/src/http/leave_tests.rs | 46 +++++ crates/ui/src/http/rail/forms.rs | 3 + crates/ui/src/http/rail/forms/tests.rs | 17 ++ crates/ui/src/http/request/auth/tests.rs | 156 ++++++++++++++++ crates/ui/src/http/request/settings_tests.rs | 52 ++++++ crates/ui/src/http/request/tests.rs | 145 +++++++++++++++ crates/ui/src/http/request/url.rs | 3 + crates/ui/src/http/request/url/tests.rs | 31 ++++ crates/ui/src/http/response/mod.rs | 2 + crates/ui/src/http/response/pane_tests.rs | 79 ++++++++ crates/ui/src/http/runner_tests.rs | 55 ++++++ crates/ui/src/http/save_request.rs | 3 + crates/ui/src/http/save_request/tests.rs | 65 +++++++ crates/ui/src/http/socket_log.rs | 3 + crates/ui/src/http/socket_log/tests.rs | 30 ++++ crates/ui/src/http/socket_tests.rs | 45 +++++ crates/ui/src/http/variables_table.rs | 3 + crates/ui/src/http/variables_table/tests.rs | 48 +++++ crates/ui/src/testing.rs | 8 +- 30 files changed, 1325 insertions(+), 2 deletions(-) create mode 100644 crates/ui/src/http/console/tests.rs create mode 100644 crates/ui/src/http/cookie_jar/tests.rs create mode 100644 crates/ui/src/http/history/tests.rs create mode 100644 crates/ui/src/http/rail/forms/tests.rs create mode 100644 crates/ui/src/http/request/url/tests.rs create mode 100644 crates/ui/src/http/response/pane_tests.rs create mode 100644 crates/ui/src/http/save_request/tests.rs create mode 100644 crates/ui/src/http/socket_log/tests.rs create mode 100644 crates/ui/src/http/variables_table/tests.rs diff --git a/crates/ui/src/http/code_tests.rs b/crates/ui/src/http/code_tests.rs index f21f2de2f..46a85ea10 100644 --- a/crates/ui/src/http/code_tests.rs +++ b/crates/ui/src/http/code_tests.rs @@ -228,3 +228,59 @@ fn active_key(harness: &Harness<'_, Bench>) -> String { .key .clone() } + +#[test] +fn each_switch_turns_its_own_option() { + for (switch, of) in [ + ("http-code-resolve", 0), + ("http-code-multiline", 1), + ("http-code-follow", 2), + ] { + let mut harness = dialog(); + let options = |harness: &Harness<'_, Bench>| { + let options = harness.state().state.http.code().options(); + [ + options.resolve_variables, + options.multiline, + options.follow_redirects, + ] + }; + let before = options(&harness); + click_id(&mut harness, switch); + let after = options(&harness); + for (at, (was, is)) in before.into_iter().zip(after).enumerate() { + assert_eq!(was != is, at == of, "{switch}, option {at}"); + } + } +} + +#[test] +fn what_no_target_is_called_is_said() { + let mut harness = dialog(); + harness + .get_by(|node| node.author_id() == Some("http-code-filter")) + .focus(); + settle(&mut harness); + harness + .get_by(|node| node.author_id() == Some("http-code-filter")) + .type_text("zzz"); + settle(&mut harness); + let none = i18n::translate(i18n::Language::En, i18n::keys::http::code::NO_TARGET, &[]); + + assert!(testing::painted(&harness).contains(&none)); + assert!(!has(&harness, "http-code-target")); +} + +/// Named after the request and the target, in the code's language. +#[test] +fn the_code_is_kept_as_a_note() { + let mut harness = dialog(); + click_id(&mut harness, "http-code-save"); + until(&mut harness, "its form is there", |harness| { + has(harness, "save-as-note-title") + }); + let title = harness.get_by(|node| node.author_id() == Some("save-as-note-title")); + let title = title.accesskit_node().value().unwrap_or_default(); + + assert!(title.contains("Login") && title.contains("cURL"), "{title}"); +} diff --git a/crates/ui/src/http/console.rs b/crates/ui/src/http/console.rs index e4e522c26..a861f9137 100644 --- a/crates/ui/src/http/console.rs +++ b/crates/ui/src/http/console.rs @@ -449,3 +449,6 @@ fn row(ui: &mut Ui, (event, headers): (&ConsoleEvent, bool), of: Of<'_>, languag ui.painter_at(clip).galley(at, galley, ink); widgets::tooltip(response, &words); } + +#[cfg(test)] +mod tests; diff --git a/crates/ui/src/http/console/tests.rs b/crates/ui/src/http/console/tests.rs new file mode 100644 index 000000000..c2a5e8e0c --- /dev/null +++ b/crates/ui/src/http/console/tests.rs @@ -0,0 +1,178 @@ +//! What a line of the console says, who it comes from, and its colour. + +use engine::error::ErrorCode; +use engine::http::scripts::model::{FailureKind, LogLevel, ScriptKind, ScriptLevel, ScriptStop}; +use i18n::Language; + +use super::*; + +fn by(kind: ScriptKind) -> ConsoleOrigin { + ConsoleOrigin { + level: ScriptLevel::Collection, + kind, + name: "API".to_owned(), + } +} + +fn out(by: Option) -> ConsoleLine { + ConsoleLine::Out { + method: "GET".to_owned(), + url: "https://a.fr".to_owned(), + headers: Vec::new(), + by, + } +} + +fn got(status: u16, by: Option) -> ConsoleLine { + ConsoleLine::In { + status, + reason: "Why".to_owned(), + millis: 12, + size: 34, + by, + } +} + +fn failed(code: ErrorCode) -> ConsoleLine { + ConsoleLine::Failed { + code, + params: std::collections::BTreeMap::default(), + by: None, + } +} + +fn log(text: &str, by: Option) -> ConsoleLine { + ConsoleLine::Log { + level: LogLevel::Log, + text: text.to_owned(), + by, + } +} + +fn test(expected: Option<&str>, actual: Option<&str>) -> ConsoleLine { + ConsoleLine::Test { + name: "is fast".to_owned(), + expected: expected.map(str::to_owned), + actual: actual.map(str::to_owned), + message: Some("too slow".to_owned()), + by: Some(by(ScriptKind::Tests)), + } +} + +fn stopped() -> ConsoleLine { + ConsoleLine::Stopped { + stop: ScriptStop { + kind: FailureKind::Error, + level: Some(ScriptLevel::Request), + script: None, + name: None, + owner: None, + line: None, + message: "x is not defined".to_owned(), + }, + } +} + +fn missed() -> ConsoleLine { + ConsoleLine::Missed { + path: "$.token".to_owned(), + variable: "token".to_owned(), + } +} + +#[test] +fn a_line_says_what_it_has_to_say() { + for (line, holds) in [ + (out(None), vec!["GET https://a.fr"]), + (got(200, None), vec!["200", "Why", "12", "34"]), + (log("hello", None), vec!["hello"]), + (test(Some("1"), Some("2")), vec!["is fast", "1", "2"]), + (test(Some("1"), None), vec!["is fast", "1", "—"]), + (test(None, None), vec!["is fast", "too slow"]), + (stopped(), vec!["x is not defined"]), + (missed(), vec!["$.token", "token"]), + ] { + let words = sentence(&line, Language::En); + assert!( + holds.iter().all(|each| words.contains(each)), + "{line:?}: {words}" + ); + } +} + +/// The code's own sentence, or that the send failed. +#[test] +fn a_failure_is_said_by_its_code() { + let timeout = sentence(&failed(ErrorCode::HttpTimeout), Language::En); + let network = sentence(&failed(ErrorCode::HttpNetwork), Language::En); + + assert!(!timeout.is_empty() && !network.is_empty()); + assert_ne!(timeout, network); +} + +/// A script's own request is said as sent by it, whatever phase it is of. +#[test] +fn a_line_is_signed_by_its_script_or_by_the_request() { + let signed = |line: ConsoleLine, request: &str| { + let event = ConsoleEvent { + id: "1".to_owned(), + at: chrono::Utc::now(), + request: request.to_owned(), + iteration: None, + line, + }; + let of = Of { + key: "key", + name: "Login", + }; + origin(&event, of, Language::En) + }; + let scripts: Vec = [ScriptKind::Before, ScriptKind::After, ScriptKind::Tests] + .into_iter() + .map(|kind| signed(log("x", Some(by(kind))), "")) + .collect(); + let sent: Vec = [ + out(Some(by(ScriptKind::Before))), + got(200, Some(by(ScriptKind::Tests))), + ] + .into_iter() + .map(|line| signed(line, "")) + .collect(); + + assert!( + scripts.iter().all(|words| words.contains("API")), + "{scripts:?}" + ); + assert!( + scripts[0] != scripts[1] && scripts[1] != scripts[2], + "{scripts:?}" + ); + assert!( + sent[0] == sent[1] && !scripts.contains(&sent[0]), + "{sent:?}" + ); + for (line, request, name) in [ + (out(None), "", "Login"), + (stopped(), "", "Login"), + (missed(), "Ping", "Ping"), + ] { + assert!(signed(line, request).contains(name), "{name}"); + } +} + +#[test] +fn what_went_wrong_is_red() { + let p = palette(&egui::Context::default()); + for (line, ink) in [ + (out(None), p.text_0), + (got(399, None), p.text_0), + (got(400, None), p.red), + (log("x", None), p.text_0), + (failed(ErrorCode::HttpTimeout), p.red), + (test(None, None), p.red), + (stopped(), p.red), + (missed(), p.red), + ] { + assert_eq!(ink_of(&line, p), ink, "{line:?}"); + } +} diff --git a/crates/ui/src/http/cookie_jar.rs b/crates/ui/src/http/cookie_jar.rs index 339d72f8a..db379448b 100644 --- a/crates/ui/src/http/cookie_jar.rs +++ b/crates/ui/src/http/cookie_jar.rs @@ -233,3 +233,6 @@ fn flags(cookie: &JarCookie, language: i18n::Language) -> String { } flags.join(" · ") } + +#[cfg(test)] +mod tests; diff --git a/crates/ui/src/http/cookie_jar/tests.rs b/crates/ui/src/http/cookie_jar/tests.rs new file mode 100644 index 000000000..7804c2a07 --- /dev/null +++ b/crates/ui/src/http/cookie_jar/tests.rs @@ -0,0 +1,50 @@ +//! What a cookie of the jar is said to be. + +use i18n::Language; + +use super::*; + +fn cookie() -> JarCookie { + JarCookie { + name: "session".to_owned(), + value: "abc".to_owned(), + domain: "a.fr".to_owned(), + host_only: false, + path: "/".to_owned(), + expires: None, + secure: false, + http_only: false, + same_site: None, + created: None, + } +} + +#[test] +fn a_cookie_s_flags_are_those_it_was_set_with() { + assert_eq!(flags(&cookie(), Language::En), ""); + let all = JarCookie { + secure: true, + http_only: true, + same_site: Some("Lax".to_owned()), + host_only: true, + ..cookie() + }; + let words = flags(&all, Language::En); + + assert!( + words.starts_with("Secure · HttpOnly · SameSite=Lax · "), + "{words}" + ); +} + +#[test] +fn a_cookie_lasts_the_session_or_until_its_date() { + let until = chrono::DateTime::from_timestamp(1_800_000_000, 0); + let dated = JarCookie { + expires: until, + ..cookie() + }; + + assert_eq!(expiry(&dated, Language::En), "2027-01-15 08:00"); + assert_ne!(expiry(&cookie(), Language::En), ""); +} diff --git a/crates/ui/src/http/dialogs_tests.rs b/crates/ui/src/http/dialogs_tests.rs index 3ba4c8158..fc3443afa 100644 --- a/crates/ui/src/http/dialogs_tests.rs +++ b/crates/ui/src/http/dialogs_tests.rs @@ -135,3 +135,77 @@ fn a_folder_may_inherit_and_a_collection_may_not() { assert!(!has(&harness, "http-auth-kind-4"), "four kinds, no inherit"); assert!(!has(&harness, "http-auth-inherited"), "nothing is above it"); } + +#[test] +fn a_domain_s_cookies_go_together() { + let mut harness = jar(); + click_id(&mut harness, "http-cookies-domain-remove"); + until(&mut harness, "the jar is empty", |harness| { + has(harness, "http-cookies-empty") + }); +} + +fn type_first(harness: &mut Harness<'_, Bench>, author_id: &str, words: &str) { + let first = |harness: &mut Harness<'_, Bench>| { + harness + .query_all_by(|node| node.author_id() == Some(author_id)) + .next() + .unwrap() + .focus(); + }; + first(harness); + settle(harness); + harness + .query_all_by(|node| node.author_id() == Some(author_id)) + .next() + .unwrap() + .type_text(words); + settle(harness); +} + +fn whole_settings(harness: &Harness<'_, Bench>) -> engine::http::model::ContainerSettings { + let item = HttpItem { + kind: HttpItemKind::Collection, + id: collection_id(harness), + }; + engine::db::run_here(harness.state().backend.engine(), move |engine| { + engine::http::http_settings(engine, &item) + }) + .unwrap() +} + +/// Every part of a container is one form, written by one button. +#[test] +fn each_part_of_a_collection_s_settings_is_written() { + let mut harness = paiements(); + harness.set_size(egui::vec2(1_200.0, 2_600.0)); + open_settings(&mut harness, "Paiements"); + type_first(&mut harness, "http-variable-name", "host"); + type_first(&mut harness, "http-kv-key", "X-Trace"); + type_first(&mut harness, "http-transport-timeoutMs", "900"); + harness.key_press(egui::Key::Tab); + settle(&mut harness); + click_id(&mut harness, "http-settings-save"); + until(&mut harness, "the dialog closes", |harness| { + !has(harness, "http-settings-dialog") + }); + + let written = whole_settings(&harness); + assert_eq!(written.variables[0].name, "host"); + assert_eq!(written.headers[0].key, "X-Trace"); + assert_eq!(written.transport.timeout_ms, Some(900)); +} + +#[test] +fn escape_leaves_a_container_as_it_was() { + let mut harness = paiements(); + open_settings(&mut harness, "Paiements"); + click_id(&mut harness, "http-auth-kind"); + click_id(&mut harness, "http-auth-kind-2"); + let before = whole_settings(&harness); + harness.key_press(egui::Key::Escape); + settle(&mut harness); + + assert!(!has(&harness, "http-settings-dialog")); + assert_eq!(whole_settings(&harness), before); +} diff --git a/crates/ui/src/http/environments.rs b/crates/ui/src/http/environments.rs index c9dc68354..8724ab8de 100644 --- a/crates/ui/src/http/environments.rs +++ b/crates/ui/src/http/environments.rs @@ -153,7 +153,7 @@ fn create(ui: &mut Ui, language: i18n::Language, view: &mut PageView, actions: & } } -fn count_words(rows: &[Variable], language: i18n::Language) -> String { +pub(super) fn count_words(rows: &[Variable], language: i18n::Language) -> String { let counts = variable_counts(rows); let count = i18n::translate( language, diff --git a/crates/ui/src/http/environments_tests.rs b/crates/ui/src/http/environments_tests.rs index 57734de95..5295473c4 100644 --- a/crates/ui/src/http/environments_tests.rs +++ b/crates/ui/src/http/environments_tests.rs @@ -237,3 +237,92 @@ fn a_request_opened_from_the_rail_leaves_the_page() { }); assert_eq!(harness.state().state.http.page(), Page::Requests); } + +#[test] +fn a_name_typed_is_taken_on_enter_and_dropped_on_escape() { + let mut harness = page(); + let before = listed(&harness).len(); + click_id(&mut harness, "http-environment-create-open"); + type_in(&mut harness, "http-environment-create-input", "Staging"); + harness.key_press(egui::Key::Escape); + settle(&mut harness); + assert_eq!(listed(&harness).len(), before); + assert!(!has(&harness, "http-environment-create-input")); + + click_id(&mut harness, "http-environment-create-open"); + type_in(&mut harness, "http-environment-create-input", "Staging"); + harness.key_press(egui::Key::Enter); + until(&mut harness, "it is made", |harness| { + listed(harness).len() > before + }); +} + +#[test] +fn an_environment_wears_the_colour_chosen() { + let mut harness = page(); + create(&mut harness, "Staging"); + let colour = |harness: &Harness<'_, Bench>| environments(harness).all()[0].colour; + let before = colour(&harness); + let swatches = harness + .query_all_by(|node| node.author_id() == Some("http-environment-colour")) + .count(); + assert!(swatches > 1); + for rank in 0..swatches { + harness + .query_all_by(|node| node.author_id() == Some("http-environment-colour")) + .nth(rank) + .unwrap() + .click(); + settle(&mut harness); + if colour(&harness) != before { + return; + } + } + panic!("no colour changed"); +} + +#[test] +fn the_one_chosen_in_the_list_is_the_one_shown() { + let mut harness = page(); + create(&mut harness, "Staging"); + create(&mut harness, "Production"); + let shown = |harness: &Harness<'_, Bench>| values(harness, "http-environment-name").join(""); + assert_eq!(shown(&harness), "Production"); + harness + .get_by(|node| { + node.author_id() == Some("http-environment-entry") + && node.label().is_some_and(|label| label.contains("Staging")) + }) + .click(); + settle(&mut harness); + + assert_eq!(shown(&harness), "Staging"); +} + +#[test] +fn the_rail_is_put_away_from_the_page() { + let mut harness = page(); + click_id(&mut harness, "http-rail-toggle"); + + assert!(!harness.state().state.settings.rail_shown); +} + +#[test] +fn a_set_counts_its_variables_and_its_secrets() { + let variable = |kind| engine::http::environments::Variable { + name: "a".to_owned(), + kind, + ..engine::http::environments::Variable::default() + }; + let words = |rows: &[engine::http::environments::Variable]| { + super::environments::count_words(rows, i18n::Language::En) + }; + let plain = words(&[variable(VariableKind::Text)]); + let both = words(&[variable(VariableKind::Text), variable(VariableKind::Secret)]); + + assert!(plain.contains('1') && !plain.contains('·'), "{plain}"); + assert!( + both.contains('2') && both.contains(" · ") && both.contains('1'), + "{both}" + ); +} diff --git a/crates/ui/src/http/history.rs b/crates/ui/src/http/history.rs index a182fcd7a..e67f83b3c 100644 --- a/crates/ui/src/http/history.rs +++ b/crates/ui/src/http/history.rs @@ -498,3 +498,6 @@ fn entry_head(ui: &mut Ui, state: &AppState, entry: &HistoryEntry, actions: &mut }); }); } + +#[cfg(test)] +mod tests; diff --git a/crates/ui/src/http/history/tests.rs b/crates/ui/src/http/history/tests.rs new file mode 100644 index 000000000..1699b085d --- /dev/null +++ b/crates/ui/src/http/history/tests.rs @@ -0,0 +1,20 @@ +//! What the list of the sends says. + +use chrono::NaiveDate; +use i18n::Language; + +use super::*; + +#[test] +fn a_day_is_named_by_how_near_it_is() { + let today = NaiveDate::from_ymd_opt(2026, 3, 1).unwrap(); + for (day, words) in [ + ("2026-03-01", "Today"), + ("2026-02-28", "Yesterday"), + ("2026-02-27", "2026-02-27"), + ("2026-03-02", "2026-03-02"), + ("else", "else"), + ] { + assert_eq!(day_label(day, today, Language::En), words); + } +} diff --git a/crates/ui/src/http/history_tests.rs b/crates/ui/src/http/history_tests.rs index fb87ec543..54c89e141 100644 --- a/crates/ui/src/http/history_tests.rs +++ b/crates/ui/src/http/history_tests.rs @@ -158,3 +158,58 @@ fn active_request(harness: &Harness<'_, Bench>) -> String { let tabs = harness.state().state.http.tabs(); tabs.active().unwrap().request_id.clone().unwrap() } + +#[test] +fn a_send_that_had_no_answer_says_why() { + let mut harness = sending_to("/json"); + let tabs = harness.state_mut().state.http.tabs_mut(); + let key = tabs.active().unwrap().key.clone(); + tabs.edit(&key, |draft| { + draft.apply(DraftEdit::Url("http://127.0.0.1:1/".to_owned())); + }); + settle(&mut harness); + click_id(&mut harness, "http-send"); + until(&mut harness, "it failed", |harness| { + has(harness, "http-response-failure") + }); + click_id(&mut harness, "http-history-open"); + until(&mut harness, "the send is listed", |harness| { + has(harness, "http-history-item") + }); + let status = said_by(&harness, "http-history-status").unwrap_or_default(); + assert_eq!( + status, + i18n::translate( + i18n::Language::En, + i18n::keys::http::history::NO_ANSWER, + &[] + ) + ); + + read_it(&mut harness); + assert!(said_by(&harness, "http-history-failure").is_some_and(|words| !words.is_empty())); +} + +#[test] +fn delete_takes_the_send_that_has_the_keys_and_its_bar_can_be_dismissed() { + let mut harness = sent(); + harness + .get_by(|node| node.author_id() == Some("http-history-item")) + .focus(); + settle(&mut harness); + harness.key_press(egui::Key::Delete); + until(&mut harness, "it went", |harness| { + has(harness, "http-history-undo") + }); + click_id(&mut harness, "http-history-undo-dismiss"); + + assert!(!has(&harness, "http-history-undo") && !has(&harness, "http-history-item")); +} + +#[test] +fn the_rail_is_put_away_from_the_page() { + let mut harness = sent(); + click_id(&mut harness, "http-rail-toggle"); + + assert!(!harness.state().state.settings.rail_shown); +} diff --git a/crates/ui/src/http/leave_tests.rs b/crates/ui/src/http/leave_tests.rs index 06dcd3c3b..847759ce0 100644 --- a/crates/ui/src/http/leave_tests.rs +++ b/crates/ui/src/http/leave_tests.rs @@ -130,3 +130,49 @@ fn a_write_queued_just_before_the_exit_is_written() { let tree = engine::db::run_here(backend.engine(), engine::http::http_tree).unwrap(); assert_eq!(tree.collections.len(), 1); } + +/// Each reason has its own sentence and its own word for going on. +#[test] +fn the_question_is_put_by_what_asks_it() { + use crate::state::http::leave::Reason; + + let mut words: Vec = [ + Reason::Quit, + Reason::Switch, + Reason::Restore, + Reason::Update, + ] + .into_iter() + .map(|reason| { + let mut harness = modified(); + assert!(!harness.state_mut().state.http.ask_leave(reason)); + settle(&mut harness); + let discard = harness.get_by(|node| node.author_id() == Some("http-leave-discard")); + discard.accesskit_node().label().unwrap_or_default() + }) + .collect(); + let count = words.len(); + words.sort(); + words.dedup(); + + assert_eq!(words.len(), count, "{words:?}"); +} + +/// The place of a draft is asked over whatever area is shown. +#[test] +fn a_draft_s_place_is_asked_from_another_area() { + let mut harness = paiements(); + click_id(&mut harness, "http-workspace-new-http"); + let tabs = harness.state_mut().state.http.tabs_mut(); + let key = tabs.active().unwrap().key.clone(); + tabs.edit(&key, |draft| { + draft.apply(DraftEdit::Url("https://api.test/new".to_owned())); + }); + settle(&mut harness); + ask(&mut harness); + stand_still(&mut harness); + click_id(&mut harness, "http-leave-save"); + until(&mut harness, "its place is asked", |harness| { + has(harness, "http-save-dialog") + }); +} diff --git a/crates/ui/src/http/rail/forms.rs b/crates/ui/src/http/rail/forms.rs index 6fb42865a..5d591235d 100644 --- a/crates/ui/src/http/rail/forms.rs +++ b/crates/ui/src/http/rail/forms.rs @@ -238,3 +238,6 @@ fn noun(contents: HttpContents, language: i18n::Language) -> String { ], ) } + +#[cfg(test)] +mod tests; diff --git a/crates/ui/src/http/rail/forms/tests.rs b/crates/ui/src/http/rail/forms/tests.rs new file mode 100644 index 000000000..4e17ef1bd --- /dev/null +++ b/crates/ui/src/http/rail/forms/tests.rs @@ -0,0 +1,17 @@ +//! What a deletion says it takes. + +use super::*; + +/// « no folder » is noise in a sentence about loss. +#[test] +fn only_what_is_there_is_counted() { + let said = |folders, requests| noun(HttpContents { folders, requests }, i18n::Language::En); + let (folders, requests, both) = (said(2, 0), said(0, 3), said(2, 3)); + + assert!(folders.contains('2') && !folders.contains('0'), "{folders}"); + assert!( + requests.contains('3') && !requests.contains('0'), + "{requests}" + ); + assert!(both.contains('2') && both.contains('3'), "{both}"); +} diff --git a/crates/ui/src/http/request/auth/tests.rs b/crates/ui/src/http/request/auth/tests.rs index 22065a74b..753101e78 100644 --- a/crates/ui/src/http/request/auth/tests.rs +++ b/crates/ui/src/http/request/auth/tests.rs @@ -74,3 +74,159 @@ fn what_is_inherited_is_said_with_where_from() { "Nothing above sets an auth: none is sent." ); } + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; + +struct Screen { + auth: RequestAuth, + allow_inherit: bool, + above: Option, + revealed: bool, +} + +fn screen(auth: RequestAuth) -> Harness<'static, Screen> { + let state = Screen { + auth, + allow_inherit: true, + above: None, + revealed: false, + }; + let mut harness = crate::testing::harness() + .with_size(egui::vec2(700.0, 500.0)) + .build_ui_state( + |ui, screen: &mut Screen| { + let field = AuthField { + auth: &screen.auth, + above: screen.above.as_ref(), + allow_inherit: screen.allow_inherit, + }; + if let Some(auth) = show(ui, &field, &mut screen.revealed, Language::En) { + screen.auth = auth; + } + }, + state, + ); + harness.run(); + harness +} + +fn click(harness: &mut Harness<'_, Screen>, author_id: &str) { + harness + .get_by(|node| node.author_id() == Some(author_id)) + .click(); + harness.run(); + harness.run(); +} + +fn type_in(harness: &mut Harness<'_, Screen>, author_id: &str, words: &str) { + click(harness, author_id); + harness + .get_by(|node| node.author_id() == Some(author_id)) + .type_text(words); + harness.run(); +} + +fn basic(username: &str, password: &str) -> RequestAuth { + RequestAuth::Basic { + username: username.to_owned(), + password: password.to_owned(), + } +} + +fn key(name: &str, value: &str, place: KeyPlace) -> RequestAuth { + RequestAuth::ApiKey { + name: name.to_owned(), + value: value.to_owned(), + place, + } +} + +/// In the menu's order. +fn kinds() -> [RequestAuth; 5] { + let bearer = RequestAuth::Bearer { + token: String::new(), + }; + [ + RequestAuth::Inherit, + RequestAuth::None, + basic("", ""), + bearer, + key("", "", KeyPlace::Header), + ] +} + +#[test] +fn a_kind_chosen_starts_empty() { + for (rank, auth) in kinds().into_iter().enumerate() { + let from = if rank == 0 { + kinds()[1].clone() + } else { + RequestAuth::Inherit + }; + let mut harness = screen(from); + click(&mut harness, "http-auth-kind"); + click(&mut harness, &format!("http-auth-kind-{rank}")); + assert_eq!(harness.state().auth, auth); + } +} + +/// A filled auth is not lost to its own name in the menu. +#[test] +fn the_kind_in_force_chosen_again_keeps_what_it_holds() { + let mut harness = screen(basic("ada", "s3cret")); + click(&mut harness, "http-auth-kind"); + click(&mut harness, "http-auth-kind-2"); + + assert_eq!(harness.state().auth, basic("ada", "s3cret")); +} + +#[test] +fn each_kind_s_fields_are_typed_into() { + let mut harness = screen(basic("", "")); + type_in(&mut harness, "http-auth-username", "ada"); + type_in(&mut harness, "http-auth-secret", "s3cret"); + assert_eq!(harness.state().auth, basic("ada", "s3cret")); + + let mut harness = screen(key("", "", KeyPlace::Header)); + type_in(&mut harness, "http-auth-key-name", "X-Key"); + type_in(&mut harness, "http-auth-secret", "v"); + click(&mut harness, "http-auth-place"); + click(&mut harness, "http-auth-place-1"); + assert_eq!(harness.state().auth, key("X-Key", "v", KeyPlace::Query)); +} + +#[test] +fn nothing_to_inherit_from_yet_is_said() { + let harness = screen(RequestAuth::Inherit); + let words = i18n::translate(Language::En, keys::http::auth::PLACE_FIRST, &[]); + + assert!( + crate::testing::painted(&harness) + .iter() + .any(|text| words.starts_with(text.as_str()) || text.contains(&words)) + ); +} + +/// A collection's « inherited » is none at all, and is not offered. +#[test] +fn with_nothing_above_there_is_nothing_to_inherit() { + let mut harness = screen(RequestAuth::Inherit); + harness.state_mut().allow_inherit = false; + harness.run(); + let kind = harness.get_by(|node| node.author_id() == Some("http-auth-kind")); + let shown = kind.accesskit_node(); + let words = [shown.value(), shown.label()] + .map(Option::unwrap_or_default) + .join(" "); + assert!(words.contains("None"), "{words}"); + click(&mut harness, "http-auth-kind"); + let offered = harness + .query_all_by(|node| { + node.author_id() + .is_some_and(|id| id.starts_with("http-auth-kind-")) + }) + .count(); + + assert_eq!(offered, 4); +} diff --git a/crates/ui/src/http/request/settings_tests.rs b/crates/ui/src/http/request/settings_tests.rs index d787ee0ce..47ef27002 100644 --- a/crates/ui/src/http/request/settings_tests.rs +++ b/crates/ui/src/http/request/settings_tests.rs @@ -280,3 +280,55 @@ fn a_request_offers_its_parts() { assert!(has(&harness, &format!("http-section-{part}")), "{part}"); } } + +#[test] +fn a_switch_is_above_on_or_off() { + for (words, value) in [("Yes", Some(true)), ("No", Some(false))] { + let mut harness = section("settings"); + pick(&mut harness, "http-transport-followRedirects", words); + assert_eq!(active(&harness).document.transport.follow_redirects, value); + let first = harness + .query_all_by(|node| node.author_id() == Some("http-transport-followRedirects")) + .next() + .unwrap(); + first.click(); + settle(&mut harness); + click_id(&mut harness, "http-transport-followRedirects-0"); + assert_eq!( + active(&harness).document.transport.follow_redirects, + None, + "{words}" + ); + } +} + +#[test] +fn an_extraction_given_up_adds_no_rule() { + for by_escape in [false, true] { + let mut harness = sending_to("/json"); + click_id(&mut harness, "http-send"); + answered(&mut harness); + click_id(&mut harness, "http-response-view-3"); + until(&mut harness, "the tree is shown", |harness| { + has(harness, "json-line") + }); + harness + .query_all_by(|node| node.author_id() == Some("json-line")) + .nth(1) + .unwrap() + .click(); + settle(&mut harness); + click_id(&mut harness, "json-extract"); + if by_escape { + harness.key_press(egui::Key::Escape); + settle(&mut harness); + } else { + click_id(&mut harness, "http-extract-cancel"); + } + assert!(active(&harness).document.extractions.is_empty()); + assert!( + !has(&harness, "http-extract-dialog"), + "by Escape: {by_escape}" + ); + } +} diff --git a/crates/ui/src/http/request/tests.rs b/crates/ui/src/http/request/tests.rs index 7fdf27108..9bf190f34 100644 --- a/crates/ui/src/http/request/tests.rs +++ b/crates/ui/src/http/request/tests.rs @@ -434,3 +434,148 @@ fn a_name_set_nowhere_says_so() { let harness = pointed_at("user"); assert_eq!(card(&harness), ["not found"]); } + +/// Where it breaks, and what it lacks. +#[test] +fn each_fault_of_a_query_has_its_own_words() { + let mut said: Vec = ["{ a", "query Q(", "{ a(b: \"c) }", "{ a } }", "{ a) }"] + .into_iter() + .map(|query| { + let mut harness = graphql(); + edit( + &mut harness, + DraftEdit::Graphql(GraphqlDocument { + query: query.to_owned(), + ..GraphqlDocument::default() + }), + ); + until(&mut harness, query, |harness| { + has(harness, "http-graphql-query-problem") + }); + let words = said_by(&harness, "http-graphql-query-problem").unwrap_or_default(); + words + .split_once(' ') + .map_or(words.clone(), |(_, rest)| rest.to_owned()) + }) + .collect(); + let count = said.len(); + said.sort(); + said.dedup(); + + assert_eq!(said.len(), count, "{said:?}"); +} + +#[test] +fn the_variables_are_json_and_those_the_query_lacks_are_named() { + let mut harness = graphql(); + let query = "query One($code: ID!) { product(code: $code) { id } }".to_owned(); + let of = |variables: &str| { + DraftEdit::Graphql(GraphqlDocument { + query: query.clone(), + variables: variables.to_owned(), + ..GraphqlDocument::default() + }) + }; + edit(&mut harness, of("{")); + until(&mut harness, "the fault is said", |harness| { + has(harness, "http-graphql-problem") + }); + edit(&mut harness, of(r#"{"code":1,"other":2}"#)); + until(&mut harness, "the other is named", |harness| { + has(harness, "http-graphql-unknown") + }); + assert!(!has(&harness, "http-graphql-problem")); +} + +#[test] +fn the_query_and_its_variables_are_formatted_by_their_buttons() { + let mut harness = graphql(); + edit( + &mut harness, + DraftEdit::Graphql(GraphqlDocument { + query: "query One($code:ID!){a(code:$code)}".to_owned(), + variables: r#"{"code":1}"#.to_owned(), + ..GraphqlDocument::default() + }), + ); + until(&mut harness, "the query is formatted", |harness| { + let button = harness.get_by(|node| node.author_id() == Some("http-graphql-format-query")); + !button.accesskit_node().is_disabled() + }); + click_id(&mut harness, "http-graphql-format-query"); + until(&mut harness, "the query is laid out", |harness| { + graphql_of(harness).query.contains('\n') + }); + click_id(&mut harness, "http-graphql-format-variables"); + until(&mut harness, "the variables are laid out", |harness| { + graphql_of(harness).variables.contains(": 1") + }); +} + +#[test] +fn the_operation_chosen_is_the_one_sent() { + let mut harness = graphql(); + edit( + &mut harness, + DraftEdit::Graphql(GraphqlDocument { + query: "query One { a } query Two { b }".to_owned(), + ..GraphqlDocument::default() + }), + ); + until(&mut harness, "the operations are offered", |harness| { + has(harness, "http-graphql-operation") + }); + click_id(&mut harness, "http-graphql-operation"); + click_id(&mut harness, "http-graphql-operation-1"); + + assert_eq!(graphql_of(&harness).operation_name.as_deref(), Some("Two")); +} + +#[test] +fn a_form_s_row_is_typed_and_taken_out() { + let mut harness = body(FORM); + type_in(&mut harness, "http-kv-key", "name"); + let fields = |harness: &Harness<'_, Bench>| match body_of(harness) { + RequestBody::Form { fields } => fields, + other => panic!("{other:?}"), + }; + assert_eq!(fields(&harness)[0].key, "name"); + click_id(&mut harness, "http-kv-remove"); + + assert!(fields(&harness).is_empty()); +} + +#[test] +fn a_name_set_nowhere_is_given_a_row_where_the_card_says() { + let mut harness = pointed_at("user"); + harness + .get_by(|node| node.author_id() == Some("http-used-variable-define")) + .click(); + until(&mut harness, "the page is shown", |harness| { + harness.state().state.http.page() == crate::state::http::Page::Environments + }); +} + +/// A secret shown is masked again once its card is left. +#[test] +fn a_card_left_forgets_what_it_showed() { + let mut harness = pointed_at("token"); + harness + .get_by(|node| node.author_id() == Some("http-used-variable-reveal")) + .click(); + harness.run(); + harness.hover_at(egui::pos2(900.0, 1_100.0)); + for _ in 0..10 { + harness.step(); + } + assert!(card(&harness).is_empty(), "{:?}", card(&harness)); + harness + .get_by(|node| { + node.author_id() == Some("http-used-variable") + && node.label().or_else(|| node.value()).as_deref() == Some("{{token}}") + }) + .hover(); + harness.run(); + + assert_eq!(card(&harness), ["globals · secret", "••••••••"]); +} diff --git a/crates/ui/src/http/request/url.rs b/crates/ui/src/http/request/url.rs index 3ba26ca3b..05d23aeda 100644 --- a/crates/ui/src/http/request/url.rs +++ b/crates/ui/src/http/request/url.rs @@ -100,3 +100,6 @@ fn lit(text: &str, scopes: &HashMap>, p: &Palette) job.append(&text[last..], 0.0, plain); job } + +#[cfg(test)] +mod tests; diff --git a/crates/ui/src/http/request/url/tests.rs b/crates/ui/src/http/request/url/tests.rs new file mode 100644 index 000000000..2332e22a4 --- /dev/null +++ b/crates/ui/src/http/request/url/tests.rs @@ -0,0 +1,31 @@ +//! What a variable of the address wears. + +use super::*; + +#[test] +fn each_scope_has_its_hue_and_nothing_set_is_red() { + let p = palette(&egui::Context::default()); + let hues = [ + None, + Some(VariableScope::Request), + Some(VariableScope::Folder), + Some(VariableScope::Collection), + Some(VariableScope::Environment), + Some(VariableScope::Globals), + Some(VariableScope::Dynamic), + ] + .map(|scope| hue(p, scope)); + + assert_eq!( + hues, + [ + p.red, + p.green, + p.teal, + p.blue, + p.amber_text, + p.pink, + p.purple + ] + ); +} diff --git a/crates/ui/src/http/response/mod.rs b/crates/ui/src/http/response/mod.rs index 681f1fe2c..117bee400 100644 --- a/crates/ui/src/http/response/mod.rs +++ b/crates/ui/src/http/response/mod.rs @@ -3,6 +3,8 @@ //! a failure or a cancelled send stays on screen as an answer does, and goes the same way. pub(crate) mod body; +#[cfg(test)] +mod pane_tests; mod stop; mod tests_view; diff --git a/crates/ui/src/http/response/pane_tests.rs b/crates/ui/src/http/response/pane_tests.rs new file mode 100644 index 000000000..87b80e962 --- /dev/null +++ b/crates/ui/src/http/response/pane_tests.rs @@ -0,0 +1,79 @@ +//! What an answer shows, part by part. + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; + +use crate::http::tests::{answered, click_id, said_by, sending_to}; +use crate::notes::bench::{Bench, until}; + +fn has(harness: &Harness<'_, Bench>, author_id: &str) -> bool { + harness + .query_all_by(|node| node.author_id() == Some(author_id)) + .next() + .is_some() +} + +fn sent(path: &str) -> Harness<'static, Bench> { + let mut harness = sending_to(path); + click_id(&mut harness, "http-send"); + answered(&mut harness); + harness +} + +#[test] +fn an_answer_with_no_body_says_so() { + let mut harness = sent("/empty"); + until(&mut harness, "it is said", |harness| { + has(harness, "http-response-empty") + }); + let copy = harness.get_by(|node| node.author_id() == Some("http-response-copy")); + assert!(copy.accesskit_node().is_disabled()); +} + +/// Counted on the tab, then each with its status. +#[test] +fn the_redirects_followed_are_in_the_timeline() { + let mut harness = sent("/redirect"); + let tab = said_by(&harness, "http-response-section-timeline").unwrap_or_default(); + assert!(tab.contains('1'), "{tab}"); + click_id(&mut harness, "http-response-section-timeline"); + let painted = crate::testing::painted(&harness); + + assert!( + painted.iter().any(|text| text.contains("302")), + "{painted:?}" + ); +} + +#[test] +fn the_view_of_a_json_answer_is_kept_for_the_next_and_leaves_with_it() { + let mut harness = sent("/json"); + click_id(&mut harness, "http-response-view-3"); + until(&mut harness, "the tree is shown", |harness| { + has(harness, "json-line") + }); + click_id(&mut harness, "http-response-view-2"); + until(&mut harness, "the graph is shown", |harness| { + has(harness, "json-node-head") + }); +} + +#[test] +fn a_picture_answered_is_drawn() { + let mut harness = sent("/image"); + until(&mut harness, "it is drawn", |harness| { + has(harness, "http-response-image") + }); +} + +#[test] +fn a_size_is_written_in_the_unit_it_reaches() { + for (bytes, words) in [ + (12, "12 B"), + (1_023, "1,023 B"), + (1_536, "1.5 KB"), + (1_572_864, "1.5 MB"), + ] { + assert_eq!(super::size_of(bytes, i18n::Language::En), words); + } +} diff --git a/crates/ui/src/http/runner_tests.rs b/crates/ui/src/http/runner_tests.rs index 990d8181b..b3732bb44 100644 --- a/crates/ui/src/http/runner_tests.rs +++ b/crates/ui/src/http/runner_tests.rs @@ -494,3 +494,58 @@ fn a_summary_counts_what_ran() { } ); } + +/// Let go a row further, or back: the keys' twin. +#[test] +fn a_row_dragged_by_its_grip_lands_where_it_is_let_go() { + let mut harness = runner("/json"); + let grip = |harness: &Harness<'_, Bench>, rank: usize| { + harness + .query_all_by(|node| node.author_id() == Some("http-runner-row-grip")) + .nth(rank) + .unwrap() + .rect() + .center() + }; + let drag = |harness: &mut Harness<'_, Bench>, from: egui::Pos2, to: egui::Pos2| { + let button = |pos, pressed| egui::Event::PointerButton { + pos, + button: egui::PointerButton::Primary, + pressed, + modifiers: egui::Modifiers::NONE, + }; + harness.event(egui::Event::PointerMoved(from)); + harness.event(button(from, true)); + harness.step(); + for part in 1..=4_u8 { + harness.event(egui::Event::PointerMoved( + from.lerp(to, f32::from(part) / 4.0), + )); + harness.step(); + } + harness.event(button(to, false)); + settle(harness); + }; + let (first, second) = (grip(&harness, 0), grip(&harness, 1)); + drag(&mut harness, first, second); + assert_eq!(labels(&harness, "http-runner-row"), ["Orders", "Login"]); + drag(&mut harness, second, first); + assert_eq!(labels(&harness, "http-runner-row"), ["Login", "Orders"]); + drag(&mut harness, first, first + egui::vec2(3.0, 2.0)); + assert_eq!(labels(&harness, "http-runner-row"), ["Login", "Orders"]); +} + +#[test] +fn alt_and_up_moves_a_row_back() { + let mut harness = runner("/json"); + harness + .get_by(|node| { + node.author_id() == Some("http-runner-row") && node.label().as_deref() == Some("Orders") + }) + .focus(); + settle(&mut harness); + harness.key_press_modifiers(egui::Modifiers::ALT, egui::Key::ArrowUp); + settle(&mut harness); + + assert_eq!(labels(&harness, "http-runner-row"), ["Orders", "Login"]); +} diff --git a/crates/ui/src/http/save_request.rs b/crates/ui/src/http/save_request.rs index f9b7e8546..b81c97949 100644 --- a/crates/ui/src/http/save_request.rs +++ b/crates/ui/src/http/save_request.rs @@ -212,3 +212,6 @@ fn place(ui: &mut Ui, form: &mut SaveForm, places: &[SavePlace], language: i18n: form.folder = None; } } + +#[cfg(test)] +mod tests; diff --git a/crates/ui/src/http/save_request/tests.rs b/crates/ui/src/http/save_request/tests.rs new file mode 100644 index 000000000..e22b35e58 --- /dev/null +++ b/crates/ui/src/http/save_request/tests.rs @@ -0,0 +1,65 @@ +//! What a first save asks for, or lacks. + +use super::*; + +fn form(name: &str, place: usize) -> SaveForm { + SaveForm { + key: "key".to_owned(), + name: name.to_owned(), + place, + collection: String::new(), + folder: None, + missing: None, + } +} + +fn places() -> Vec { + let place = |folder: Option<&str>| SavePlace { + collection_id: "c".to_owned(), + folder_id: folder.map(str::to_owned), + path: "API".to_owned(), + }; + vec![place(None), place(Some("f"))] +} + +#[test] +fn a_request_needs_a_name_and_a_place_that_has_one() { + let new = places().len(); + let blank = SaveForm { + folder: Some(" ".to_owned()), + ..form("Login", 0) + }; + for (form, missing) in [ + (form(" ", 0), Missing::Name), + (form("Login", new), Missing::Collection), + (blank, Missing::Folder), + ] { + assert_eq!(form.target(&places()).err(), Some(missing)); + } +} + +#[test] +fn it_goes_where_the_form_says_under_its_name_trimmed() { + let target = |form: SaveForm| form.target(&places()).ok().unwrap(); + let in_folder = target(form(" Login ", 1)); + assert_eq!(in_folder.name, "Login"); + assert_eq!( + ( + in_folder.collection_id.as_str(), + in_folder.folder_id.as_deref() + ), + ("c", Some("f")) + ); + assert!(matches!(in_folder.create, ToCreate::Nothing)); + + let made = target(SaveForm { + folder: Some(" Auth ".to_owned()), + ..form("Login", 0) + }); + assert!(matches!(made.create, ToCreate::Folder(name) if name == "Auth")); + let first = target(SaveForm { + collection: " API ".to_owned(), + ..form("Login", 2) + }); + assert!(matches!(first.create, ToCreate::Collection(name) if name == "API")); +} diff --git a/crates/ui/src/http/socket_log.rs b/crates/ui/src/http/socket_log.rs index 17001b9d1..d9577cdc4 100644 --- a/crates/ui/src/http/socket_log.rs +++ b/crates/ui/src/http/socket_log.rs @@ -309,3 +309,6 @@ fn row(ui: &mut Ui, entry: &SocketEntry, language: i18n::Language) { ui.painter_at(clip).galley(at, galley, ink); widgets::tooltip(response, &words); } + +#[cfg(test)] +mod tests; diff --git a/crates/ui/src/http/socket_log/tests.rs b/crates/ui/src/http/socket_log/tests.rs new file mode 100644 index 000000000..0a2143e6a --- /dev/null +++ b/crates/ui/src/http/socket_log/tests.rs @@ -0,0 +1,30 @@ +//! What a line of a socket's log says. + +use super::*; + +fn entry(event: SocketEvent) -> SocketEntry { + SocketEntry { + event, + at: chrono::Utc::now(), + } +} + +#[test] +fn each_event_says_what_happened() { + let got = |text: &str, binary| SocketEvent::Received { + text: text.to_owned(), + binary, + cut: false, + size: 4, + }; + let closed = |code, reason: &str| SocketEvent::Closed { + code, + reason: reason.to_owned(), + }; + let words = |event| words_of(&entry(event), i18n::Language::En); + assert_eq!(words(got("hello", false)), "hello"); + assert_ne!(words(got("hello", true)), "hello"); + assert!(words(closed(Some(1_000), "bye")).ends_with("1000 bye")); + let bare = words(closed(None, "")); + assert_eq!(bare, bare.trim_end()); +} diff --git a/crates/ui/src/http/socket_tests.rs b/crates/ui/src/http/socket_tests.rs index e09d1a884..6859a8830 100644 --- a/crates/ui/src/http/socket_tests.rs +++ b/crates/ui/src/http/socket_tests.rs @@ -230,3 +230,48 @@ fn a_log_keeps_the_last_entries_and_an_old_socket_s_events_are_dropped() { assert_eq!(state.log.len(), LOG_KEPT); assert_eq!(state.phase, Phase::Open); } + +#[test] +fn a_kept_message_is_put_back_in_the_box() { + let mut harness = socket(); + type_message(&mut harness, "ping"); + click_id(&mut harness, "http-socket-keep"); + click_id(&mut harness, "http-socket-message"); + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + harness + .get_by(|node| node.author_id() == Some("http-socket-message")) + .type_text("other"); + settle(&mut harness); + click_id(&mut harness, "http-socket-saved"); + + let text = harness + .get_by(|node| node.author_id() == Some("http-socket-message")) + .value(); + assert_eq!(text.as_deref(), Some("ping")); +} + +/// Written once the field is left, the blanks between two names left out. +#[test] +fn the_subprotocols_asked_for_are_written_once_left() { + let mut harness = socket(); + click_id(&mut harness, "http-section-protocols"); + let field = |harness: &Harness<'_, Bench>| { + harness + .query_by(|node| node.author_id() == Some("http-socket-protocols")) + .is_some() + }; + assert!(field(&harness)); + click_id(&mut harness, "http-socket-protocols"); + harness + .get_by(|node| node.author_id() == Some("http-socket-protocols")) + .type_text("chat, , json "); + settle(&mut harness); + assert!(active(&harness).document.websocket.protocols.is_empty()); + harness.key_press(egui::Key::Enter); + settle(&mut harness); + + assert_eq!( + active(&harness).document.websocket.protocols, + ["chat", "json"] + ); +} diff --git a/crates/ui/src/http/variables_table.rs b/crates/ui/src/http/variables_table.rs index b33b3a221..f16063d9c 100644 --- a/crates/ui/src/http/variables_table.rs +++ b/crates/ui/src/http/variables_table.rs @@ -310,3 +310,6 @@ fn said(ui: &mut Ui, faults: &[Option], language: i18n::Language) widgets::address(ui, &shown, "http-variable-fault"); } } + +#[cfg(test)] +mod tests; diff --git a/crates/ui/src/http/variables_table/tests.rs b/crates/ui/src/http/variables_table/tests.rs new file mode 100644 index 000000000..951ed55ea --- /dev/null +++ b/crates/ui/src/http/variables_table/tests.rs @@ -0,0 +1,48 @@ +//! What an edit of the table makes of its rows. + +use super::*; + +fn row(name: &str) -> Variable { + Variable { + name: name.to_owned(), + ..Variable::default() + } +} + +fn names(changed: Changed) -> Vec { + match changed { + Changed::Rows(rows) => rows.into_iter().map(|row| row.name).collect(), + Changed::Filler(filler) => vec![format!("filled by {}", filler.name)], + } +} + +#[test] +fn an_edit_lands_on_its_row_and_the_blank_one_becomes_a_row() { + let rows = [row("a"), row("b")]; + for (at, edited, after) in [ + (0, Row::Edited(row("x")), vec!["x", "b"]), + (2, Row::Edited(row("x")), vec!["a", "b", "x"]), + (1, Row::Removed, vec!["a"]), + ] { + assert_eq!( + names(applied(&rows, at, edited, &mut Revealed::default())), + after + ); + } +} + +#[test] +fn the_request_that_filled_a_row_is_answered_as_such() { + let filler = FilledBy { + request_id: Some("id".to_owned()), + name: "Login".to_owned(), + }; + let changed = applied( + &[row("a")], + 0, + Row::Filler(filler), + &mut Revealed::default(), + ); + + assert_eq!(names(changed), ["filled by Login"]); +} diff --git a/crates/ui/src/testing.rs b/crates/ui/src/testing.rs index e503a6577..5de7f91dd 100644 --- a/crates/ui/src/testing.rs +++ b/crates/ui/src/testing.rs @@ -174,7 +174,7 @@ pub(crate) fn slow_arrived(port: u16) -> bool { } /// A server on this machine for the sends of a test: `/json` answers a small JSON, `/slow` the -/// same after five seconds, anything else a 404. Each connection is answered once, then closed. +/// same after five seconds, `/empty` no body, anything else a 404. Each connection is answered once, then closed. pub(crate) fn serve() -> u16 { use std::io::{Read, Write}; let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).expect("a local port is free"); @@ -224,6 +224,12 @@ pub(crate) fn serve() -> u16 { } else { ("404 Not Found", "missing".to_owned()) }; + if path.starts_with("/empty") { + let answer = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\ + Content-Length: 0\r\nConnection: close\r\n\r\n"; + let _ = stream.write_all(answer.as_bytes()); + return; + } if path.starts_with("/redirect") { let answer = "HTTP/1.1 302 Found\r\nLocation: /json\r\n\ Content-Length: 0\r\nConnection: close\r\n\r\n"; From 97af2e0fd1f0dd5a07bf0b9b69811e6778ea6d73 Mon Sep 17 00:00:00 2001 From: Valentin MILLET <34792012+vmillet-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:56:40 +0100 Subject: [PATCH 88/95] Repository: code formatted at 110 columns, with editor settings (#1851) Co-authored-by: Claude Opus 5.5 --- .editorconfig | 38 + crates/app/build.rs | 6 +- crates/app/examples/icons.rs | 26 +- crates/app/examples/tours.rs | 17 +- crates/app/src/arguments.rs | 26 +- crates/app/src/desktop.rs | 16 +- crates/app/src/logging.rs | 46 +- crates/app/src/main.rs | 74 +- crates/app/src/renderer.rs | 20 +- crates/app/src/sight.rs | 13 +- crates/app/src/unpainted.rs | 13 +- crates/app/tests/windows_resources.rs | 4 +- crates/drawing/src/edit.rs | 176 +---- crates/drawing/src/edit/tests.rs | 137 +--- crates/drawing/src/geometry.rs | 161 +--- crates/drawing/src/marks.rs | 136 +--- crates/drawing/src/picture.rs | 64 +- crates/drawing/src/picture/tests.rs | 70 +- crates/drawing/src/scene.rs | 81 +- crates/drawing/src/scene/tests.rs | 70 +- crates/drawing/src/text.rs | 9 +- crates/drawing/src/text/tests.rs | 8 +- crates/engine/benches/commands.rs | 92 +-- crates/engine/benches/corpus.rs | 49 +- crates/engine/benches/corpus_size.rs | 10 +- crates/engine/benches/index.rs | 38 +- crates/engine/benches/reference.rs | 47 +- crates/engine/benches/reference_profile.rs | 6 +- crates/engine/build.rs | 18 +- crates/engine/src/attachments.rs | 15 +- crates/engine/src/attachments/files.rs | 55 +- crates/engine/src/attachments/model.rs | 76 +- crates/engine/src/attachments/sealed.rs | 17 +- crates/engine/src/attachments/store.rs | 70 +- crates/engine/src/backup.rs | 6 +- crates/engine/src/backup/copies.rs | 165 +--- crates/engine/src/changelog.rs | 41 +- crates/engine/src/changelog/model.rs | 69 +- crates/engine/src/closed_enum.rs | 10 +- crates/engine/src/db.rs | 54 +- crates/engine/src/db/migration.rs | 8 +- crates/engine/src/db/queue.rs | 10 +- crates/engine/src/docs.rs | 42 +- crates/engine/src/docs/model.rs | 132 +--- crates/engine/src/docs/search.rs | 33 +- crates/engine/src/error.rs | 173 +--- crates/engine/src/folders.rs | 65 +- crates/engine/src/folders/board.rs | 294 ++----- crates/engine/src/folders/model.rs | 111 +-- crates/engine/src/folders/store.rs | 113 +-- crates/engine/src/folders/store/board.rs | 110 +-- crates/engine/src/host.rs | 11 +- crates/engine/src/http.rs | 334 ++------ crates/engine/src/http/codegen.rs | 273 ++----- crates/engine/src/http/codegen/angular.rs | 22 +- crates/engine/src/http/codegen/axios.rs | 10 +- crates/engine/src/http/codegen/csharp.rs | 14 +- crates/engine/src/http/codegen/curl.rs | 25 +- crates/engine/src/http/codegen/dart.rs | 27 +- crates/engine/src/http/codegen/fetch.rs | 6 +- crates/engine/src/http/codegen/go.rs | 28 +- crates/engine/src/http/codegen/guzzle.rs | 26 +- crates/engine/src/http/codegen/httpie.rs | 16 +- crates/engine/src/http/codegen/java.rs | 47 +- crates/engine/src/http/codegen/javascript.rs | 33 +- crates/engine/src/http/codegen/okhttp.rs | 41 +- crates/engine/src/http/codegen/powershell.rs | 20 +- crates/engine/src/http/codegen/python.rs | 24 +- crates/engine/src/http/codegen/req.rs | 16 +- crates/engine/src/http/codegen/reqwest.rs | 29 +- crates/engine/src/http/codegen/ruby.rs | 11 +- crates/engine/src/http/codegen/source.rs | 8 +- crates/engine/src/http/codegen/swift.rs | 27 +- crates/engine/src/http/codegen/wget.rs | 10 +- crates/engine/src/http/collection_run.rs | 23 +- crates/engine/src/http/console.rs | 145 +--- crates/engine/src/http/cookies.rs | 215 ++--- crates/engine/src/http/cookies/store.rs | 99 +-- crates/engine/src/http/environments.rs | 54 +- crates/engine/src/http/environments/store.rs | 45 +- crates/engine/src/http/error.rs | 57 +- crates/engine/src/http/extract.rs | 6 +- crates/engine/src/http/flight.rs | 195 +---- crates/engine/src/http/graphql.rs | 121 +-- crates/engine/src/http/history.rs | 448 +++-------- crates/engine/src/http/history/store.rs | 124 +-- crates/engine/src/http/model.rs | 151 +--- crates/engine/src/http/query.rs | 84 +- crates/engine/src/http/response.rs | 31 +- crates/engine/src/http/runner.rs | 256 ++---- crates/engine/src/http/scripts/around.rs | 262 ++---- crates/engine/src/http/scripts/child.rs | 95 +-- crates/engine/src/http/scripts/engine.rs | 491 +++--------- crates/engine/src/http/scripts/libraries.rs | 11 +- crates/engine/src/http/scripts/model.rs | 242 ++---- crates/engine/src/http/scripts/network.rs | 84 +- crates/engine/src/http/scripts/process.rs | 28 +- crates/engine/src/http/scripts/session.rs | 6 +- crates/engine/src/http/search.rs | 32 +- crates/engine/src/http/send.rs | 743 ++++-------------- crates/engine/src/http/settings.rs | 149 +--- crates/engine/src/http/store.rs | 235 ++---- crates/engine/src/http/transport.rs | 11 +- crates/engine/src/http/variables.rs | 253 ++---- crates/engine/src/http/websocket.rs | 76 +- crates/engine/src/index.rs | 248 ++---- crates/engine/src/index/oracle.rs | 99 +-- crates/engine/src/json/layout.rs | 8 +- crates/engine/src/json/model.rs | 314 ++------ crates/engine/src/json/parse.rs | 54 +- crates/engine/src/json/position.rs | 11 +- crates/engine/src/json/read.rs | 16 +- crates/engine/src/json/toml.rs | 49 +- crates/engine/src/json/xml.rs | 161 +--- crates/engine/src/json/yaml.rs | 137 +--- crates/engine/src/layout.rs | 25 +- crates/engine/src/lib.rs | 7 +- crates/engine/src/libraries.rs | 3 +- crates/engine/src/libraries/registry.rs | 57 +- crates/engine/src/name.rs | 5 +- crates/engine/src/notes.rs | 103 +-- crates/engine/src/notes/calc.rs | 450 ++--------- crates/engine/src/notes/calc/eval.rs | 445 +++-------- crates/engine/src/notes/calc/lexer.rs | 76 +- crates/engine/src/notes/calc/maths.rs | 59 +- crates/engine/src/notes/calc/summary.rs | 40 +- crates/engine/src/notes/calc/units.rs | 357 ++------- crates/engine/src/notes/calc/words.rs | 103 +-- crates/engine/src/notes/checklist.rs | 15 +- crates/engine/src/notes/convert.rs | 96 +-- crates/engine/src/notes/drawing.rs | 50 +- crates/engine/src/notes/duplicate.rs | 52 +- crates/engine/src/notes/kind.rs | 5 +- crates/engine/src/notes/language.rs | 499 +++--------- crates/engine/src/notes/markdown.rs | 116 +-- crates/engine/src/notes/model.rs | 420 ++-------- crates/engine/src/notes/placeholder.rs | 117 +-- crates/engine/src/notes/priority.rs | 9 +- crates/engine/src/notes/revision.rs | 57 +- crates/engine/src/notes/store.rs | 156 +--- crates/engine/src/notes/store/pictures.rs | 80 +- crates/engine/src/notes/store/related.rs | 87 +- crates/engine/src/notes/store/revisions.rs | 17 +- crates/engine/src/notes/store/trash.rs | 26 +- crates/engine/src/notes/trash.rs | 37 +- crates/engine/src/notes/view.rs | 659 +++------------- crates/engine/src/recovery.rs | 27 +- crates/engine/src/spaces/model.rs | 10 +- crates/engine/src/spaces/store.rs | 35 +- crates/engine/src/tools.rs | 8 +- crates/engine/src/tools/bases.rs | 325 ++------ crates/engine/src/tools/check_numbers.rs | 83 +- crates/engine/src/tools/checks.rs | 172 +--- crates/engine/src/tools/cidr.rs | 216 +---- crates/engine/src/tools/cidr/forms.rs | 55 +- crates/engine/src/tools/cidr/masks.rs | 25 +- crates/engine/src/tools/cidr/plan.rs | 120 +-- crates/engine/src/tools/cidr/summary.rs | 55 +- crates/engine/src/tools/colour.rs | 249 ++---- crates/engine/src/tools/convert.rs | 145 +--- crates/engine/src/tools/convert/xml.rs | 58 +- crates/engine/src/tools/cron.rs | 501 +++--------- crates/engine/src/tools/dates.rs | 203 +---- crates/engine/src/tools/diff.rs | 428 ++-------- crates/engine/src/tools/durations.rs | 238 ++---- crates/engine/src/tools/encoding.rs | 43 +- crates/engine/src/tools/files.rs | 17 +- crates/engine/src/tools/generate.rs | 178 +---- crates/engine/src/tools/generate/lorem.rs | 87 +- crates/engine/src/tools/generate/schema.rs | 207 ++--- crates/engine/src/tools/hash.rs | 231 ++---- crates/engine/src/tools/identifiers.rs | 179 +---- crates/engine/src/tools/identity.rs | 467 +++-------- crates/engine/src/tools/identity/data.rs | 69 +- crates/engine/src/tools/identity/numbers.rs | 71 +- crates/engine/src/tools/identity/papers.rs | 192 +---- crates/engine/src/tools/identity/profile.rs | 74 +- crates/engine/src/tools/image.rs | 102 +-- crates/engine/src/tools/jwt.rs | 199 +---- crates/engine/src/tools/numbers.rs | 33 +- crates/engine/src/tools/permissions.rs | 162 +--- crates/engine/src/tools/printed.rs | 5 +- crates/engine/src/tools/qr.rs | 285 ++----- crates/engine/src/tools/random.rs | 59 +- crates/engine/src/tools/sizes.rs | 105 +-- crates/engine/src/tools/stats.rs | 99 +-- crates/engine/src/tools/text.rs | 237 ++---- crates/engine/src/tools/text_diff.rs | 192 +---- crates/engine/src/tools/transfer.rs | 112 +-- crates/engine/src/tools/url_parts.rs | 43 +- crates/engine/src/tools/zones.rs | 196 +---- crates/engine/src/transfer.rs | 6 +- crates/engine/src/transfer/bundle.rs | 54 +- crates/engine/src/transfer/file.rs | 252 ++---- crates/engine/src/transfer/model.rs | 147 +--- crates/engine/src/transfer/protect.rs | 17 +- crates/engine/src/vault.rs | 8 +- crates/engine/src/vault/file.rs | 76 +- crates/engine/src/vault/gate.rs | 19 +- crates/engine/src/vault/key.rs | 40 +- crates/engine/tests/commands/attachments.rs | 85 +- crates/engine/tests/commands/backups.rs | 28 +- crates/engine/tests/commands/concurrency.rs | 73 +- crates/engine/tests/commands/folders.rs | 155 +--- crates/engine/tests/commands/http.rs | 146 +--- crates/engine/tests/commands/http_cookies.rs | 15 +- .../tests/commands/http_environments.rs | 110 +-- crates/engine/tests/commands/http_runner.rs | 141 +--- crates/engine/tests/commands/http_scripts.rs | 154 +--- crates/engine/tests/commands/http_send.rs | 235 ++---- crates/engine/tests/commands/index.rs | 41 +- crates/engine/tests/commands/main.rs | 21 +- crates/engine/tests/commands/notes.rs | 242 ++---- crates/engine/tests/commands/profile.rs | 42 +- crates/engine/tests/commands/recovery.rs | 23 +- crates/engine/tests/commands/spaces.rs | 94 +-- crates/engine/tests/commands/transfer.rs | 87 +- crates/engine/tests/commands/websocket.rs | 121 +-- crates/engine/tests/folders/board.rs | 167 +--- crates/engine/tests/folders/main.rs | 16 +- crates/engine/tests/folders/nesting.rs | 44 +- crates/engine/tests/folders/store.rs | 126 +-- crates/engine/tests/formats.rs | 42 +- crates/engine/tests/http.rs | 372 ++------- crates/engine/tests/http_environments.rs | 66 +- crates/engine/tests/language_corpus.rs | 5 +- crates/engine/tests/notes/batches.rs | 194 +---- crates/engine/tests/notes/checklists.rs | 65 +- crates/engine/tests/notes/exchange.rs | 20 +- crates/engine/tests/notes/fields.rs | 82 +- crates/engine/tests/notes/main.rs | 36 +- crates/engine/tests/notes/queries.rs | 315 ++------ crates/engine/tests/notes/revisions.rs | 60 +- crates/engine/tests/notes/seeding.rs | 67 +- crates/engine/tests/notes/storage.rs | 79 +- crates/engine/tests/notes/tags.rs | 69 +- crates/engine/tests/notes/trash.rs | 47 +- crates/engine/tests/notes/writes.rs | 76 +- crates/engine/tests/scripts.rs | 66 +- crates/engine/tests/spaces.rs | 74 +- crates/engine/tests/transfer.rs | 174 +--- crates/i18n/build.rs | 33 +- crates/i18n/src/format.rs | 131 +-- crates/i18n/src/lib.rs | 84 +- crates/i18n/src/plural.rs | 60 +- crates/i18n/src/time.rs | 71 +- crates/platform/examples/update.rs | 6 +- crates/platform/src/autostart/system.rs | 14 +- crates/platform/src/dialog.rs | 5 +- crates/platform/src/dialog/system.rs | 16 +- crates/platform/src/instance.rs | 57 +- crates/platform/src/links.rs | 9 +- crates/platform/src/notify/system.rs | 10 +- crates/platform/src/paths.rs | 18 +- crates/platform/src/shortcuts.rs | 24 +- crates/platform/src/shortcuts/notation.rs | 10 +- crates/platform/src/shortcuts/system/gnome.rs | 7 +- .../platform/src/shortcuts/system/portal.rs | 56 +- .../platform/src/shortcuts/system/wayland.rs | 11 +- crates/platform/src/tray.rs | 13 +- crates/platform/src/tray/system.rs | 15 +- crates/platform/src/updater/system.rs | 28 +- crates/platform/src/updater/tests.rs | 66 +- crates/platform/src/window.rs | 17 +- crates/richtext/src/edit.rs | 181 +---- crates/richtext/src/edit/tests.rs | 161 +--- crates/richtext/src/escape.rs | 14 +- crates/richtext/src/history.rs | 19 +- crates/richtext/src/html.rs | 146 +--- crates/richtext/src/inlines.rs | 73 +- crates/richtext/src/model.rs | 15 +- crates/richtext/src/picture.rs | 77 +- crates/richtext/src/read.rs | 169 +--- crates/richtext/src/rules.rs | 40 +- crates/richtext/src/rules/tests.rs | 56 +- crates/richtext/src/table.rs | 66 +- crates/richtext/src/tree.rs | 94 +-- crates/richtext/src/write.rs | 169 +--- crates/richtext/tests/golden.rs | 3 +- crates/richtext/tests/past_the_end.rs | 5 +- crates/text/src/buffer.rs | 119 +-- crates/text/src/buffer/tests.rs | 164 +--- crates/text/src/diff.rs | 10 +- crates/text/src/format.rs | 10 +- crates/text/src/format/host.rs | 36 +- crates/text/src/format/tests.rs | 15 +- crates/text/src/highlight.rs | 144 +--- crates/text/src/indent.rs | 78 +- crates/text/src/search.rs | 47 +- crates/text/src/shield.rs | 34 +- crates/text/src/words.rs | 31 +- crates/ui/src/action.rs | 8 +- crates/ui/src/api/attachments.rs | 11 +- crates/ui/src/api/board.rs | 6 +- crates/ui/src/api/folders.rs | 14 +- crates/ui/src/api/http.rs | 63 +- crates/ui/src/api/notes.rs | 68 +- crates/ui/src/api/preferences.rs | 8 +- crates/ui/src/api/tools.rs | 10 +- crates/ui/src/api/transfer.rs | 11 +- crates/ui/src/api/undo.rs | 8 +- crates/ui/src/api/vault.rs | 20 +- crates/ui/src/app.rs | 172 ++-- crates/ui/src/app/about_link_tests.rs | 5 +- crates/ui/src/app/area_switch_tests.rs | 38 +- crates/ui/src/app/captures.rs | 440 +++-------- crates/ui/src/app/docs_tests.rs | 13 +- crates/ui/src/app/gate_update_tests.rs | 15 +- crates/ui/src/app/global_key_tests.rs | 5 +- crates/ui/src/app/library_panel_tests.rs | 11 +- crates/ui/src/app/modal_tests.rs | 27 +- crates/ui/src/app/palette_copy_tests.rs | 8 +- crates/ui/src/app/perf.rs | 100 +-- crates/ui/src/app/preferences_tests.rs | 44 +- crates/ui/src/app/prompt_tests.rs | 6 +- crates/ui/src/app/rail_toggle_tests.rs | 34 +- crates/ui/src/app/screens.rs | 111 +-- crates/ui/src/app/titlebar_tests.rs | 18 +- crates/ui/src/app/update_prompt_tests.rs | 24 +- crates/ui/src/app/window_tests.rs | 51 +- crates/ui/src/backend.rs | 39 +- crates/ui/src/banners/toasts.rs | 52 +- crates/ui/src/banners/update_prompt.rs | 33 +- crates/ui/src/gate/draw.rs | 130 +-- crates/ui/src/gate/mod.rs | 21 +- crates/ui/src/gate/passphrase.rs | 65 +- crates/ui/src/gate/prompt.rs | 99 +-- crates/ui/src/gate/tests.rs | 127 +-- crates/ui/src/http/close.rs | 24 +- crates/ui/src/http/code.rs | 81 +- crates/ui/src/http/code_tests.rs | 86 +- crates/ui/src/http/console.rs | 119 +-- crates/ui/src/http/console/tests.rs | 84 +- crates/ui/src/http/container_settings.rs | 80 +- crates/ui/src/http/cookie_jar.rs | 65 +- crates/ui/src/http/cookie_jar/tests.rs | 10 +- crates/ui/src/http/dialogs_tests.rs | 50 +- crates/ui/src/http/environment_picker.rs | 98 +-- crates/ui/src/http/environments.rs | 157 +--- crates/ui/src/http/environments_tests.rs | 64 +- crates/ui/src/http/extract.rs | 43 +- crates/ui/src/http/history.rs | 187 +---- crates/ui/src/http/history_tests.rs | 77 +- crates/ui/src/http/kept_tests.rs | 61 +- crates/ui/src/http/leave.rs | 47 +- crates/ui/src/http/leave_tests.rs | 37 +- crates/ui/src/http/mod.rs | 56 +- crates/ui/src/http/rail/forms.rs | 78 +- crates/ui/src/http/rail/forms/tests.rs | 5 +- crates/ui/src/http/rail/mod.rs | 209 +---- crates/ui/src/http/rail/row.rs | 92 +-- crates/ui/src/http/request/auth.rs | 72 +- crates/ui/src/http/request/auth/tests.rs | 149 +--- crates/ui/src/http/request/body.rs | 103 +-- crates/ui/src/http/request/chips.rs | 58 +- crates/ui/src/http/request/composer.rs | 55 +- crates/ui/src/http/request/extractions.rs | 17 +- crates/ui/src/http/request/graphql.rs | 107 +-- crates/ui/src/http/request/mod.rs | 290 ++----- crates/ui/src/http/request/parts.rs | 80 +- crates/ui/src/http/request/settings_tests.rs | 88 +-- crates/ui/src/http/request/table.rs | 157 +--- crates/ui/src/http/request/tests.rs | 183 +---- crates/ui/src/http/request/transport.rs | 42 +- crates/ui/src/http/request/url.rs | 13 +- crates/ui/src/http/request/url/tests.rs | 13 +- crates/ui/src/http/response/body.rs | 149 +--- crates/ui/src/http/response/mod.rs | 268 ++----- crates/ui/src/http/response/pane_tests.rs | 28 +- crates/ui/src/http/response/stop.rs | 33 +- crates/ui/src/http/response/tests_view.rs | 78 +- crates/ui/src/http/runner/mod.rs | 100 +-- crates/ui/src/http/runner/order.rs | 105 +-- crates/ui/src/http/runner/results.rs | 214 ++--- crates/ui/src/http/runner_tests.rs | 126 +-- crates/ui/src/http/save_as_note.rs | 47 +- crates/ui/src/http/save_request.rs | 23 +- crates/ui/src/http/save_request/tests.rs | 31 +- crates/ui/src/http/scripts.rs | 111 +-- crates/ui/src/http/scripts_tests.rs | 55 +- crates/ui/src/http/socket_log.rs | 100 +-- crates/ui/src/http/socket_log/tests.rs | 18 +- crates/ui/src/http/socket_tests.rs | 79 +- crates/ui/src/http/tabs.rs | 157 +--- crates/ui/src/http/tests.rs | 491 +++--------- crates/ui/src/http/variables_table.rs | 68 +- crates/ui/src/http/variables_table/tests.rs | 22 +- crates/ui/src/inputs.rs | 10 +- crates/ui/src/keys.rs | 128 +-- crates/ui/src/notes/bench.rs | 146 ++-- crates/ui/src/notes/calc.rs | 310 ++------ crates/ui/src/notes/canvas/board/gesture.rs | 88 +-- crates/ui/src/notes/canvas/board/mod.rs | 263 ++----- crates/ui/src/notes/canvas/board/tests.rs | 230 ++---- crates/ui/src/notes/canvas/board/tidy.rs | 92 +-- crates/ui/src/notes/canvas/board/zone.rs | 247 ++---- crates/ui/src/notes/canvas/card/actions.rs | 153 +--- crates/ui/src/notes/canvas/card/bands.rs | 108 +-- crates/ui/src/notes/canvas/card/body.rs | 168 +--- crates/ui/src/notes/canvas/card/mod.rs | 57 +- crates/ui/src/notes/canvas/card/tests.rs | 161 +--- crates/ui/src/notes/canvas/grid.rs | 26 +- crates/ui/src/notes/canvas/mod.rs | 109 +-- crates/ui/src/notes/canvas/rows.rs | 55 +- crates/ui/src/notes/canvas/shortcuts.rs | 44 +- crates/ui/src/notes/canvas/tests.rs | 151 ++-- crates/ui/src/notes/destinations.rs | 30 +- crates/ui/src/notes/header/facets.rs | 647 +++++---------- crates/ui/src/notes/header/layout.rs | 26 +- crates/ui/src/notes/header/mod.rs | 186 +---- crates/ui/src/notes/header/new_note.rs | 80 +- crates/ui/src/notes/header/selection.rs | 156 +--- crates/ui/src/notes/header/sort.rs | 102 +-- crates/ui/src/notes/header/switchers.rs | 241 ++---- crates/ui/src/notes/header/tests.rs | 158 +--- crates/ui/src/notes/language.rs | 20 +- crates/ui/src/notes/mod.rs | 74 +- .../src/notes/overlays/editor/attachments.rs | 28 +- .../overlays/editor/attachments/tests.rs | 21 +- crates/ui/src/notes/overlays/editor/body.rs | 23 +- crates/ui/src/notes/overlays/editor/calc.rs | 190 +---- .../src/notes/overlays/editor/calc/tests.rs | 84 +- .../ui/src/notes/overlays/editor/checklist.rs | 158 +--- .../notes/overlays/editor/checklist/tests.rs | 158 +--- crates/ui/src/notes/overlays/editor/code.rs | 40 +- .../src/notes/overlays/editor/code/tests.rs | 68 +- .../ui/src/notes/overlays/editor/drawing.rs | 200 +---- .../notes/overlays/editor/drawing/camera.rs | 37 +- .../src/notes/overlays/editor/drawing/look.rs | 19 +- .../notes/overlays/editor/drawing/tests.rs | 61 +- .../ui/src/notes/overlays/editor/expanded.rs | 102 +-- crates/ui/src/notes/overlays/editor/fields.rs | 142 +--- .../src/notes/overlays/editor/fields/tests.rs | 25 +- crates/ui/src/notes/overlays/editor/format.rs | 136 +--- .../src/notes/overlays/editor/format/tests.rs | 130 +-- .../src/notes/overlays/editor/go_to_line.rs | 28 +- crates/ui/src/notes/overlays/editor/header.rs | 129 +-- .../ui/src/notes/overlays/editor/json_view.rs | 115 +-- .../notes/overlays/editor/json_view/tests.rs | 110 +-- crates/ui/src/notes/overlays/editor/mod.rs | 194 +---- .../ui/src/notes/overlays/editor/revisions.rs | 96 +-- .../notes/overlays/editor/revisions/tests.rs | 54 +- crates/ui/src/notes/overlays/editor/rich.rs | 218 ++--- .../src/notes/overlays/editor/rich/images.rs | 29 +- .../src/notes/overlays/editor/rich/search.rs | 39 +- .../notes/overlays/editor/rich/shortcuts.rs | 21 +- .../src/notes/overlays/editor/rich/tests.rs | 227 ++---- .../src/notes/overlays/editor/rich/toolbar.rs | 175 +---- .../src/notes/overlays/editor/search_bar.rs | 100 +-- crates/ui/src/notes/overlays/editor/tests.rs | 156 +--- crates/ui/src/notes/overlays/folder_prompt.rs | 36 +- .../ui/src/notes/overlays/image_lightbox.rs | 13 +- .../ui/src/notes/overlays/placeholder_form.rs | 106 +-- crates/ui/src/notes/overlays/presentation.rs | 97 +-- .../notes/overlays/presentation/mind_map.rs | 66 +- .../src/notes/overlays/presentation/tests.rs | 62 +- crates/ui/src/notes/overlays/tag_manager.rs | 192 +---- crates/ui/src/notes/overlays/trash_panel.rs | 180 +---- crates/ui/src/notes/overlays/undo_bar.rs | 86 +- crates/ui/src/notes/panel.rs | 226 +----- crates/ui/src/notes/parity_tests.rs | 105 +-- crates/ui/src/notes/pointer_tests.rs | 20 +- crates/ui/src/notes/prettier.rs | 53 +- crates/ui/src/notes/sidebar/mod.rs | 148 +--- crates/ui/src/notes/sidebar/row.rs | 47 +- crates/ui/src/notes/sidebar/tests.rs | 210 ++--- crates/ui/src/notes/sidebar/tree.rs | 51 +- crates/ui/src/notes/ui.rs | 55 +- crates/ui/src/palette/list_tests.rs | 74 +- crates/ui/src/palette/mod.rs | 305 ++----- crates/ui/src/palette/options.rs | 113 +-- crates/ui/src/services/autostart.rs | 16 +- crates/ui/src/services/docs_quotes.rs | 37 +- crates/ui/src/services/errors.rs | 65 +- crates/ui/src/services/global_keys.rs | 19 +- crates/ui/src/services/highlight.rs | 6 +- crates/ui/src/services/preferences.rs | 19 +- crates/ui/src/services/samples.rs | 20 +- crates/ui/src/services/settings.rs | 152 +--- crates/ui/src/services/shortcuts.rs | 185 +---- crates/ui/src/services/time.rs | 26 +- crates/ui/src/services/updates.rs | 30 +- crates/ui/src/state/apply_http.rs | 27 +- crates/ui/src/state/apply_notes.rs | 243 ++---- crates/ui/src/state/apply_window.rs | 38 +- crates/ui/src/state/attachments.rs | 62 +- crates/ui/src/state/backups.rs | 12 +- crates/ui/src/state/board.rs | 217 ++--- crates/ui/src/state/drawing_pictures.rs | 34 +- crates/ui/src/state/editor.rs | 159 +--- crates/ui/src/state/explored.rs | 3 +- crates/ui/src/state/folders.rs | 54 +- crates/ui/src/state/formatting.rs | 33 +- crates/ui/src/state/held.rs | 17 +- crates/ui/src/state/http/area_tests.rs | 316 ++------ crates/ui/src/state/http/bodies.rs | 41 +- crates/ui/src/state/http/code.rs | 7 +- crates/ui/src/state/http/containers.rs | 5 +- crates/ui/src/state/http/cookies.rs | 3 +- crates/ui/src/state/http/environments.rs | 74 +- crates/ui/src/state/http/history.rs | 40 +- crates/ui/src/state/http/mod.rs | 181 ++--- crates/ui/src/state/http/moves.rs | 165 +--- crates/ui/src/state/http/runner.rs | 51 +- crates/ui/src/state/http/send.rs | 14 +- crates/ui/src/state/http/sockets.rs | 26 +- crates/ui/src/state/http/tabs.rs | 115 +-- crates/ui/src/state/http/tree.rs | 87 +- crates/ui/src/state/libraries.rs | 26 +- crates/ui/src/state/mod.rs | 129 +-- crates/ui/src/state/note_revisions.rs | 21 +- crates/ui/src/state/notes.rs | 61 +- crates/ui/src/state/notes_query.rs | 74 +- crates/ui/src/state/notes_tests.rs | 174 +--- crates/ui/src/state/palette.rs | 36 +- crates/ui/src/state/placeholder_fill.rs | 24 +- crates/ui/src/state/presentation.rs | 26 +- crates/ui/src/state/query.rs | 13 +- crates/ui/src/state/refused_tests.rs | 146 +--- crates/ui/src/state/security.rs | 30 +- crates/ui/src/state/selection.rs | 3 +- crates/ui/src/state/spaces.rs | 42 +- crates/ui/src/state/tags.rs | 26 +- crates/ui/src/state/tools.rs | 18 +- crates/ui/src/state/transfer.rs | 166 +--- crates/ui/src/state/undo.rs | 30 +- crates/ui/src/state/window_tests.rs | 119 +-- crates/ui/src/testing.rs | 39 +- crates/ui/src/theme/focus.rs | 7 +- crates/ui/src/theme/fonts.rs | 34 +- crates/ui/src/theme/icons.rs | 96 +-- crates/ui/src/theme/literals.rs | 38 +- crates/ui/src/theme/mod.rs | 40 +- crates/ui/src/theme/motion.rs | 49 +- crates/ui/src/theme/tokens.rs | 60 +- crates/ui/src/titlebar/about_menu/card.rs | 52 +- crates/ui/src/titlebar/about_menu/docs/mod.rs | 133 +--- .../ui/src/titlebar/about_menu/docs/page.rs | 117 +-- .../ui/src/titlebar/about_menu/docs/text.rs | 49 +- crates/ui/src/titlebar/about_menu/mod.rs | 64 +- crates/ui/src/titlebar/about_menu/sheet.rs | 39 +- .../ui/src/titlebar/about_menu/whats_new.rs | 31 +- crates/ui/src/titlebar/area_switch.rs | 20 +- crates/ui/src/titlebar/file_menu.rs | 56 +- crates/ui/src/titlebar/libraries.rs | 46 +- crates/ui/src/titlebar/mod.rs | 74 +- crates/ui/src/titlebar/preferences/general.rs | 177 +---- crates/ui/src/titlebar/preferences/mod.rs | 98 +-- .../ui/src/titlebar/preferences/security.rs | 83 +- .../ui/src/titlebar/preferences/shortcuts.rs | 92 +-- .../ui/src/titlebar/preferences/variables.rs | 36 +- crates/ui/src/titlebar/window.rs | 37 +- crates/ui/src/tools/catalogue.rs | 180 +---- .../ui/src/tools/catalogue/answers_tests.rs | 404 ++-------- crates/ui/src/tools/catalogue/ascii.rs | 46 +- crates/ui/src/tools/catalogue/base64.rs | 111 +-- crates/ui/src/tools/catalogue/calc_tests.rs | 140 +--- crates/ui/src/tools/catalogue/case.rs | 29 +- crates/ui/src/tools/catalogue/checks.rs | 155 +--- crates/ui/src/tools/catalogue/cidr.rs | 103 +-- crates/ui/src/tools/catalogue/colour.rs | 47 +- crates/ui/src/tools/catalogue/convert.rs | 24 +- crates/ui/src/tools/catalogue/cron.rs | 151 +--- .../ui/src/tools/catalogue/cron/sentence.rs | 53 +- crates/ui/src/tools/catalogue/data_tests.rs | 96 +-- crates/ui/src/tools/catalogue/dates.rs | 204 ++--- crates/ui/src/tools/catalogue/diff.rs | 78 +- .../ui/src/tools/catalogue/diff/structured.rs | 136 +--- crates/ui/src/tools/catalogue/diff/text.rs | 137 +--- .../ui/src/tools/catalogue/encoding_tests.rs | 56 +- crates/ui/src/tools/catalogue/hash.rs | 121 +-- crates/ui/src/tools/catalogue/http_headers.rs | 27 +- crates/ui/src/tools/catalogue/http_status.rs | 71 +- crates/ui/src/tools/catalogue/identifiers.rs | 108 +-- crates/ui/src/tools/catalogue/identity.rs | 215 +---- .../ui/src/tools/catalogue/json_generator.rs | 38 +- crates/ui/src/tools/catalogue/jwt.rs | 51 +- crates/ui/src/tools/catalogue/line_breaks.rs | 46 +- crates/ui/src/tools/catalogue/lorem.rs | 24 +- .../ui/src/tools/catalogue/markdown_sheet.rs | 15 +- crates/ui/src/tools/catalogue/mime_types.rs | 47 +- .../ui/src/tools/catalogue/mustache_sheet.rs | 11 +- crates/ui/src/tools/catalogue/password.rs | 62 +- crates/ui/src/tools/catalogue/permissions.rs | 74 +- crates/ui/src/tools/catalogue/ports.rs | 16 +- crates/ui/src/tools/catalogue/qr.rs | 95 +-- crates/ui/src/tools/catalogue/reference.rs | 29 +- .../ui/src/tools/catalogue/reference_tests.rs | 21 +- crates/ui/src/tools/catalogue/regex_sheet.rs | 22 +- crates/ui/src/tools/catalogue/signals.rs | 27 +- crates/ui/src/tools/catalogue/sizes.rs | 138 +--- crates/ui/src/tools/catalogue/text_stats.rs | 103 +-- crates/ui/src/tools/catalogue/text_tests.rs | 41 +- crates/ui/src/tools/catalogue/time_tests.rs | 58 +- crates/ui/src/tools/catalogue/url_codec.rs | 54 +- crates/ui/src/tools/catalogue/zones.rs | 108 +-- crates/ui/src/tools/frame.rs | 35 +- crates/ui/src/tools/home.rs | 224 +----- crates/ui/src/tools/home/hits.rs | 23 +- crates/ui/src/tools/live.rs | 11 +- crates/ui/src/tools/mod.rs | 47 +- crates/ui/src/tools/rail.rs | 77 +- crates/ui/src/tools/tests.rs | 17 +- crates/ui/src/tools/ui/copy_value.rs | 69 +- crates/ui/src/tools/ui/mod.rs | 97 +-- crates/ui/src/tools/ui/note_import.rs | 14 +- crates/ui/src/tools/ui/note_picker.rs | 42 +- crates/ui/src/tools/ui/output_row.rs | 26 +- crates/ui/src/tools/ui/reference_table.rs | 96 +-- crates/ui/src/tools/ui/result_row.rs | 82 +- crates/ui/src/tools/ui/tests.rs | 137 ++-- crates/ui/src/tools/ui/text_table.rs | 7 +- crates/ui/src/widgets/badge.rs | 58 +- crates/ui/src/widgets/button.rs | 124 +-- crates/ui/src/widgets/date.rs | 194 ++--- crates/ui/src/widgets/dialog.rs | 116 +-- crates/ui/src/widgets/editor/bubbles.rs | 11 +- crates/ui/src/widgets/editor/bubbles/tests.rs | 81 +- crates/ui/src/widgets/editor/geometry.rs | 46 +- crates/ui/src/widgets/editor/input.rs | 94 +-- crates/ui/src/widgets/editor/mod.rs | 125 +-- crates/ui/src/widgets/editor/tests.rs | 198 ++--- crates/ui/src/widgets/empty.rs | 32 +- crates/ui/src/widgets/field.rs | 99 +-- crates/ui/src/widgets/in_place.rs | 9 +- crates/ui/src/widgets/json_explorer/graph.rs | 274 ++----- crates/ui/src/widgets/json_explorer/mod.rs | 243 ++---- crates/ui/src/widgets/json_explorer/reads.rs | 24 +- crates/ui/src/widgets/json_explorer/tests.rs | 30 +- crates/ui/src/widgets/json_explorer/tree.rs | 51 +- .../src/widgets/json_explorer/view_tests.rs | 202 +---- crates/ui/src/widgets/layout.rs | 117 ++- crates/ui/src/widgets/list.rs | 95 +-- crates/ui/src/widgets/menu.rs | 368 +++------ crates/ui/src/widgets/mod.rs | 63 +- crates/ui/src/widgets/picker.rs | 85 +- crates/ui/src/widgets/release_notes.rs | 6 +- crates/ui/src/widgets/rich.rs | 164 +--- crates/ui/src/widgets/rich/tests.rs | 282 ++----- crates/ui/src/widgets/segmented.rs | 57 +- crates/ui/src/widgets/split.rs | 81 +- crates/ui/src/widgets/tests.rs | 125 +-- docs/architecture.md | 3 +- e2e/examples/footprint.rs | 15 +- e2e/src/lib.rs | 133 +--- e2e/src/server.rs | 33 +- e2e/tests/01_first_launch.rs | 70 +- e2e/tests/02_note_lifecycle.rs | 125 ++- e2e/tests/03_editing_a_note.rs | 335 ++++---- e2e/tests/04_trash_and_undo.rs | 108 ++- e2e/tests/05_spaces.rs | 142 ++-- e2e/tests/06_search_and_filters.rs | 234 ++---- e2e/tests/07_checklists.rs | 83 +- e2e/tests/08_placeholder_fields.rs | 81 +- e2e/tests/09_quick_palette.rs | 71 +- e2e/tests/10_library_transfer.rs | 71 +- e2e/tests/12_preferences.rs | 67 +- e2e/tests/13_multiple_selection.rs | 19 +- e2e/tests/14_tag_manager.rs | 96 +-- e2e/tests/15_preferences_on_disk.rs | 15 +- e2e/tests/16_passphrase_change.rs | 80 +- e2e/tests/17_folders.rs | 343 ++++---- e2e/tests/18_board.rs | 281 +++---- e2e/tests/19_board_gesture.rs | 333 ++++---- e2e/tests/20_folder_descent.rs | 152 ++-- e2e/tests/21_folders_travel.rs | 16 +- e2e/tests/22_note_history.rs | 25 +- e2e/tests/23_backups.rs | 25 +- e2e/tests/24_forgotten_passphrase.rs | 13 +- e2e/tests/25_libraries.rs | 55 +- e2e/tests/26_formatting.rs | 67 +- e2e/tests/27_json_explorer.rs | 101 +-- e2e/tests/28_areas.rs | 118 ++- e2e/tests/29_tools.rs | 58 +- e2e/tests/30_http.rs | 358 ++++----- e2e/tests/31_http_environments.rs | 131 ++- e2e/tests/32_http_code.rs | 8 +- e2e/tests/33_calc.rs | 61 +- e2e/tests/34_http_scripts.rs | 87 +- e2e/tests/35_http_runner.rs | 28 +- e2e/tests/36_recette_libraries.rs | 47 +- e2e/tests/37_recette_socle.rs | 261 +++--- e2e/tests/38_recette_notes.rs | 303 +++---- e2e/tests/39_recette_tools.rs | 165 +--- e2e/tests/40_recette_http.rs | 112 +-- e2e/tests/41_note_fullscreen.rs | 94 +-- e2e/tests/43_close_to_tray.rs | 104 +-- e2e/tests/44_window_controls.rs | 17 +- rustfmt.toml | 3 + 689 files changed, 14605 insertions(+), 49704 deletions(-) create mode 100644 .editorconfig create mode 100644 rustfmt.toml diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..94341586d --- /dev/null +++ b/.editorconfig @@ -0,0 +1,38 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_style = space +indent_size = 2 +insert_final_newline = true +trim_trailing_whitespace = true + +# As `rustfmt.toml` writes it. +[*.rs] +indent_size = 4 +max_line_length = 110 + +[*.{toml,sql,py}] +indent_size = 4 + +# Two spaces at the end of a line break it. +[*.md] +trim_trailing_whitespace = false + +# Compared byte for byte, or kept as published. +[{golden,crates/engine/tests/corpus,crates/engine/sandbox/dist,crates/text/prettier,docs/recette}/**] +charset = unset +end_of_line = unset +indent_size = unset +indent_style = unset +insert_final_newline = unset +trim_trailing_whitespace = unset + +[.claude/skills/{accessibility,core-web-vitals,frontend-design,rust-guidelines,seo,webapp-testing}/**] +charset = unset +end_of_line = unset +indent_size = unset +indent_style = unset +insert_final_newline = unset +trim_trailing_whitespace = unset diff --git a/crates/app/build.rs b/crates/app/build.rs index 8e6f5a095..3e0e32594 100644 --- a/crates/app/build.rs +++ b/crates/app/build.rs @@ -18,8 +18,7 @@ mod windows { if env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { return; } - let manifest_dir = - env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set by cargo"); + let manifest_dir = env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set by cargo"); let manifest_dir = Path::new(&manifest_dir); let name = product_name(manifest_dir); let icon = manifest_dir.join("icons/icon.ico"); @@ -34,8 +33,7 @@ mod windows { /// The name the packages give the application, `[package.metadata.packager] product-name`; /// the version is the workspace's, which `winresource` reads from Cargo itself. fn product_name(manifest_dir: &Path) -> String { - let text = - fs::read_to_string(manifest_dir.join("Cargo.toml")).expect("Cargo.toml is readable"); + let text = fs::read_to_string(manifest_dir.join("Cargo.toml")).expect("Cargo.toml is readable"); let manifest: toml::Table = toml::from_str(&text).expect("Cargo.toml is valid TOML"); manifest .get("package") diff --git a/crates/app/examples/icons.rs b/crates/app/examples/icons.rs index 9136547be..814204797 100644 --- a/crates/app/examples/icons.rs +++ b/crates/app/examples/icons.rs @@ -17,11 +17,7 @@ fn main() { let icons = Path::new(env!("CARGO_MANIFEST_DIR")).join("icons"); let master = icons.join("devnotes.svg"); for (name, size) in PNGS { - let source = if HINTED.contains(&size) { - hinted(&icons, size) - } else { - master.clone() - }; + let source = if HINTED.contains(&size) { hinted(&icons, size) } else { master.clone() }; write(&icons.join(name), &render(&source, size)); } let entries: Vec<(u32, Vec)> = HINTED @@ -38,21 +34,13 @@ fn hinted(icons: &Path, size: u32) -> PathBuf { /// The drawing at `size` × `size` px, as a PNG. fn render(source: &Path, size: u32) -> Vec { - let data = - std::fs::read(source).unwrap_or_else(|error| panic!("{}: {error}", source.display())); + let data = std::fs::read(source).unwrap_or_else(|error| panic!("{}: {error}", source.display())); let tree = usvg::Tree::from_data(&data, &usvg::Options::default()) .unwrap_or_else(|error| panic!("{}: {error}", source.display())); let mut pixmap = tiny_skia::Pixmap::new(size, size).expect("a non-empty size"); - #[allow( - clippy::cast_precision_loss, - reason = "an icon is a few hundred pixels wide" - )] + #[allow(clippy::cast_precision_loss, reason = "an icon is a few hundred pixels wide")] let scale = size as f32 / tree.size().width().max(tree.size().height()); - resvg::render( - &tree, - tiny_skia::Transform::from_scale(scale, scale), - &mut pixmap.as_mut(), - ); + resvg::render(&tree, tiny_skia::Transform::from_scale(scale, scale), &mut pixmap.as_mut()); pixmap.encode_png().expect("a PNG of a pixmap") } @@ -70,11 +58,7 @@ fn ico(entries: &[(u32, Vec)]) -> Vec { header.extend_from_slice(&[side, side, 0, 0]); header.extend_from_slice(&1u16.to_le_bytes()); header.extend_from_slice(&32u16.to_le_bytes()); - header.extend_from_slice( - &u32::try_from(data.len()) - .expect("a small PNG") - .to_le_bytes(), - ); + header.extend_from_slice(&u32::try_from(data.len()).expect("a small PNG").to_le_bytes()); header.extend_from_slice(&u32::try_from(offset).expect("a small file").to_le_bytes()); offset += data.len(); } diff --git a/crates/app/examples/tours.rs b/crates/app/examples/tours.rs index 7cd776ca3..e23c5dee0 100644 --- a/crates/app/examples/tours.rs +++ b/crates/app/examples/tours.rs @@ -54,14 +54,7 @@ const TOURS: [(&str, &[&str]); 3] = [ ), ( "http", - &[ - "http-home", - "http-request", - "http-graphql", - "http-websocket", - "http-environments", - "http-code", - ], + &["http-home", "http-request", "http-graphql", "http-websocket", "http-environments", "http-code"], ), ]; @@ -99,14 +92,10 @@ fn write(path: &Path, frames: &[RgbaImage]) { for frame in frames { let mut reduced = frame.clone(); for pixel in reduced.pixels_mut() { - *pixel = *nearest - .entry(*pixel) - .or_insert_with(|| closest(&palette, *pixel)); + *pixel = *nearest.entry(*pixel).or_insert_with(|| closest(&palette, *pixel)); } let delay = Delay::from_saturating_duration(SHOWN); - encoder - .encode_frame(Frame::from_parts(reduced, 0, 0, delay)) - .expect("a frame"); + encoder.encode_frame(Frame::from_parts(reduced, 0, 0, delay)).expect("a frame"); } } diff --git a/crates/app/src/arguments.rs b/crates/app/src/arguments.rs index 3498d80ac..64bf68574 100644 --- a/crates/app/src/arguments.rs +++ b/crates/app/src/arguments.rs @@ -36,10 +36,7 @@ mod tests { #[test] fn a_profile_directory_is_read_after_its_flag() { - assert_eq!( - of(&["--profile", "/tmp/run-1"]).profile, - Some(PathBuf::from("/tmp/run-1")) - ); + assert_eq!(of(&["--profile", "/tmp/run-1"]).profile, Some(PathBuf::from("/tmp/run-1"))); } #[test] @@ -50,32 +47,17 @@ mod tests { #[test] fn an_action_is_read_after_its_flag() { - assert_eq!( - of(&["--action", "palette"]).action, - Some("palette".to_string()) - ); + assert_eq!(of(&["--action", "palette"]).action, Some("palette".to_string())); } #[test] fn an_unknown_argument_is_left_alone() { - assert_eq!( - of(&["--minimized", "--profile", "p"]).profile, - Some(PathBuf::from("p")) - ); + assert_eq!(of(&["--minimized", "--profile", "p"]).profile, Some(PathBuf::from("p"))); } #[test] fn both_are_read_in_any_order_and_the_last_of_each_wins() { - let read = of(&[ - "--action", - "quit", - "--profile", - "a", - "--profile", - "b", - "--action", - "palette", - ]); + let read = of(&["--action", "quit", "--profile", "a", "--profile", "b", "--action", "palette"]); assert_eq!(read.profile, Some(PathBuf::from("b"))); assert_eq!(read.action.as_deref(), Some("palette")); diff --git a/crates/app/src/desktop.rs b/crates/app/src/desktop.rs index 85dc6668c..b06ffc46d 100644 --- a/crates/app/src/desktop.rs +++ b/crates/app/src/desktop.rs @@ -46,19 +46,11 @@ fn start_tray(preferences: &Preferences, inbox: Inbox) -> Box { let Ok(icon) = eframe::icon_data::from_png_bytes(include_bytes!("../icons/32x32.png")) else { return Box::new(NoTray); }; - let picture = Picture { - rgba: icon.rgba, - width: icon.width, - height: icon.height, - }; + let picture = Picture { rgba: icon.rgba, width: icon.width, height: icon.height }; let language = Settings::read(preferences).locale.language(); - platform::tray::system( - picture, - &ui::services::tray::labels(language), - move |asked| { - inbox.post(ui::inputs::Input::Tray(asked)); - }, - ) + platform::tray::system(picture, &ui::services::tray::labels(language), move |asked| { + inbox.post(ui::inputs::Input::Tray(asked)); + }) } /// Named in the language of the launch where a Wayland desktop lists them. diff --git a/crates/app/src/logging.rs b/crates/app/src/logging.rs index 705fd8060..276635cb1 100644 --- a/crates/app/src/logging.rs +++ b/crates/app/src/logging.rs @@ -24,11 +24,7 @@ pub(crate) fn start(directory: &Path) -> Option { logger .log_to_file(file) .append() - .rotate( - Criterion::Size(5_000_000), - Naming::Numbers, - Cleanup::KeepLogFiles(3), - ) + .rotate(Criterion::Size(5_000_000), Naming::Numbers, Cleanup::KeepLogFiles(3)) .duplicate_to_stderr(Duplicate::Error) .start() }) @@ -74,11 +70,7 @@ fn notice(language: i18n::Language, logs: &Path) -> (String, String) { let app = || Value::from(engine::app_info::METADATA.name.to_owned()); let title = i18n::translate(language, keys::crash::TITLE, &[("app", app())]); let folder = Value::from(logs.display().to_string()); - let words = i18n::translate( - language, - keys::crash::BODY, - &[("app", app()), ("folder", folder)], - ); + let words = i18n::translate(language, keys::crash::BODY, &[("app", app()), ("folder", folder)]); (title, words) } @@ -87,12 +79,7 @@ fn report(info: &PanicHookInfo<'_>) -> String { let thread = std::thread::current(); let name = thread.name().unwrap_or("unnamed"); match info.location() { - Some(at) => format!( - "Panicked at {}:{}:{} on thread {name}", - at.file(), - at.line(), - at.column() - ), + Some(at) => format!("Panicked at {}:{}:{} on thread {name}", at.file(), at.line(), at.column()), None => format!("Panicked on thread {name}"), } } @@ -182,9 +169,7 @@ mod tests { logger(); let profile = tempfile::tempdir().unwrap(); let runtime = tokio::runtime::Runtime::new().unwrap(); - let paths = engine::Paths { - profile: profile.path().to_path_buf(), - }; + let paths = engine::Paths { profile: profile.path().to_path_buf() }; let sink = Arc::new(engine::RecordingSink::default()); let closed = engine::Engine::new(paths, sink, runtime.handle().clone()); let patch = NotePatch { @@ -193,9 +178,8 @@ mod tests { ..Default::default() }; - let failed = engine::db::run_here(&closed, |engine| { - engine::notes::update_note(engine, "note-id", &patch) - }); + let failed = + engine::db::run_here(&closed, |engine| engine::notes::update_note(engine, "note-id", &patch)); ui::services::errors::ErrorNotifier::default() .report(i18n::keys::errors::NOTE_GONE, &failed.unwrap_err()); @@ -210,14 +194,10 @@ mod tests { logger(); let profile = tempfile::tempdir().unwrap(); let runtime = tokio::runtime::Runtime::new().unwrap(); - let paths = engine::Paths { - profile: profile.path().to_path_buf(), - }; + let paths = engine::Paths { profile: profile.path().to_path_buf() }; let sink = Arc::new(engine::RecordingSink::default()); let engine = engine::Engine::new(paths, sink, runtime.handle().clone()); - let draft = || engine::spaces::model::SpaceDraft { - name: "Clients Dupont-Aignan".to_owned(), - }; + let draft = || engine::spaces::model::SpaceDraft { name: "Clients Dupont-Aignan".to_owned() }; let duplicate = engine::db::run_here(&engine, |engine| { let phrase = engine::vault::secret("correct horse battery staple".to_owned()); engine::vault::create_vault(engine, phrase)?; @@ -275,10 +255,7 @@ mod tests { assert!(title.contains(engine::app_info::METADATA.name), "{title}"); assert!(words.contains("C:/profil/logs"), "{words}"); assert_ne!(words, english); - assert!( - !words.contains("{{") && !english.contains("{{"), - "{words} {english}" - ); + assert!(!words.contains("{{") && !english.contains("{{"), "{words} {english}"); } /// Where the process that panics for the test below writes its log. @@ -295,10 +272,7 @@ mod tests { let directory = tempfile::tempdir().unwrap(); let ended = std::process::Command::new(std::env::current_exe().unwrap()) - .args([ - "--exact", - "logging::tests::a_panic_ends_the_process_once_its_place_is_in_the_log", - ]) + .args(["--exact", "logging::tests::a_panic_ends_the_process_once_its_place_is_in_the_log"]) .env(PANIC_IN, directory.path()) .output() .unwrap(); diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 782050d68..fa9ddfd81 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -34,10 +34,7 @@ fn main() -> ExitCode { // First, for the script host too: it logs nothing there, and exits the same. logging::install_panic_hook(); // A script host opens no window and writes no log. - if std::env::args_os() - .nth(1) - .is_some_and(|arg| arg == engine::SCRIPT_HOST_ARG) - { + if std::env::args_os().nth(1).is_some_and(|arg| arg == engine::SCRIPT_HOST_ARG) { std::process::exit(engine::serve_scripts()); } @@ -81,9 +78,8 @@ fn main() -> ExitCode { #[cfg(target_os = "linux")] fn missing_library() -> Option<&'static str> { let x11 = std::env::var_os("DISPLAY").is_some(); - (x11 && xkbcommon_dl::x11::xkbcommon_x11_option().is_none()).then_some( - "libxkbcommon-x11 (libxkbcommon-x11-0 on Debian and Ubuntu, libxkbcommon-x11 on Fedora)", - ) + (x11 && xkbcommon_dl::x11::xkbcommon_x11_option().is_none()) + .then_some("libxkbcommon-x11 (libxkbcommon-x11-0 on Debian and Ubuntu, libxkbcommon-x11 on Fedora)") } #[cfg(not(target_os = "linux"))] @@ -98,9 +94,9 @@ fn not_opened(error: &eframe::Error) -> String { use eframe::egui_wgpu::WgpuError; match error { - eframe::Error::Wgpu( - WgpuError::CreateSurfaceError(_) | WgpuError::RequestAdapterError(_), - ) if cfg!(target_os = "linux") => { + eframe::Error::Wgpu(WgpuError::CreateSurfaceError(_) | WgpuError::RequestAdapterError(_)) + if cfg!(target_os = "linux") => + { format!( "The window did not open: no graphics driver answered, neither Vulkan nor OpenGL \ ({error}). Install your graphics card's drivers, or Mesa's: mesa-vulkan-drivers \ @@ -127,23 +123,17 @@ fn hand_over(profile: &Path, action: Option) -> ExitCode { fn run(locations: Locations, instance: Instance) -> eframe::Result { let restored = platform::window::read(&locations.window); let preferences = Preferences::read(&locations.profile.join(engine::layout::PREFERENCES)); - let language = ui::services::settings::Settings::read(&preferences) - .locale - .language(); + let language = ui::services::settings::Settings::read(&preferences).locale.language(); logging::tell_when_stopped(language, &locations.logs); let (inbox, waker, inputs) = ui::inputs::channel(); let heard = inbox.clone(); - if let Err(error) = - instance.serve(move |message| heard.post(ui::inputs::Input::Instance(message))) - { + if let Err(error) = instance.serve(move |message| heard.post(ui::inputs::Input::Instance(message))) { log::warn!("Second launches will not be heard: {error}"); } // ⚠️ Called with the event loop running: macOS makes no tray icon before. let startup = move || ui::Startup { desktop: desktop::start(&preferences, &inbox), - paths: engine::Paths { - profile: locations.profile, - }, + paths: engine::Paths { profile: locations.profile }, window_file: locations.window, geometry: restored, reduced_motion: platform::motion::system_prefers_reduced(), @@ -264,22 +254,14 @@ mod tests { panic!("the profile was taken"); }; let (heard, hearing) = mpsc::channel(); - first - .serve(move |message| heard.send(message).unwrap()) - .unwrap(); + first.serve(move |message| heard.send(message).unwrap()).unwrap(); assert_eq!(hand_over(profile.path(), None), ExitCode::SUCCESS); - assert_eq!( - hand_over(profile.path(), Some("palette".to_string())), - ExitCode::SUCCESS - ); + assert_eq!(hand_over(profile.path(), Some("palette".to_string())), ExitCode::SUCCESS); let wait = Duration::from_secs(10); assert_eq!(hearing.recv_timeout(wait).unwrap(), Message::Reveal); - assert_eq!( - hearing.recv_timeout(wait).unwrap(), - Message::Action("palette".to_string()) - ); + assert_eq!(hearing.recv_timeout(wait).unwrap(), Message::Action("palette".to_string())); } #[test] @@ -297,21 +279,14 @@ mod tests { let said = not_opened(&no_adapter); - assert_eq!( - said.contains("neither Vulkan nor OpenGL"), - cfg!(target_os = "linux") - ); - assert_eq!( - said.contains("mesa-vulkan-drivers"), - cfg!(target_os = "linux") - ); + assert_eq!(said.contains("neither Vulkan nor OpenGL"), cfg!(target_os = "linux")); + assert_eq!(said.contains("mesa-vulkan-drivers"), cfg!(target_os = "linux")); assert!(!said.contains('\n'), "{said}"); } #[test] fn another_renderer_error_is_said_as_it_is() { - let no_format = - eframe::Error::Wgpu(eframe::egui_wgpu::WgpuError::NoSurfaceFormatsAvailable); + let no_format = eframe::Error::Wgpu(eframe::egui_wgpu::WgpuError::NoSurfaceFormatsAvailable); let said = not_opened(&no_format); @@ -324,14 +299,8 @@ mod tests { let options = options(None); assert_eq!(options.viewport.visible, Some(false)); - assert_eq!( - options.viewport.inner_size, - Some(egui::vec2(1_100.0, 720.0)) - ); - assert_eq!( - options.viewport.min_inner_size, - Some(egui::vec2(640.0, 480.0)) - ); + assert_eq!(options.viewport.inner_size, Some(egui::vec2(1_100.0, 720.0))); + assert_eq!(options.viewport.min_inner_size, Some(egui::vec2(640.0, 480.0))); assert!(options.viewport.icon.is_some()); assert!(options.centered); assert!(!options.persist_window); @@ -339,13 +308,8 @@ mod tests { #[test] fn a_later_launch_opens_where_the_window_was() { - let options = options(Some(Geometry { - x: 40.0, - y: 30.0, - width: 900.0, - height: 600.0, - maximized: true, - })); + let options = + options(Some(Geometry { x: 40.0, y: 30.0, width: 900.0, height: 600.0, maximized: true })); assert_eq!(options.viewport.visible, Some(false)); assert_eq!(options.viewport.inner_size, Some(egui::vec2(900.0, 600.0))); diff --git a/crates/app/src/renderer.rs b/crates/app/src/renderer.rs index c2aeb3dc5..ca27ac774 100644 --- a/crates/app/src/renderer.rs +++ b/crates/app/src/renderer.rs @@ -15,9 +15,8 @@ pub(crate) fn options() -> WgpuConfiguration { } let mut setup = WgpuSetupCreateNew::without_display_handle(); setup.native_adapter_selector = Some(std::sync::Arc::new(|adapters, surface| { - let draws_here = |adapter: &&wgpu::Adapter| { - surface.is_none_or(|surface| adapter.is_surface_supported(surface)) - }; + let draws_here = + |adapter: &&wgpu::Adapter| surface.is_none_or(|surface| adapter.is_surface_supported(surface)); adapters .iter() .filter(draws_here) @@ -26,10 +25,7 @@ pub(crate) fn options() -> WgpuConfiguration { .cloned() .ok_or_else(|| "no adapter draws on this window".to_string()) })); - WgpuConfiguration { - wgpu_setup: WgpuSetup::CreateNew(setup), - ..Default::default() - } + WgpuConfiguration { wgpu_setup: WgpuSetup::CreateNew(setup), ..Default::default() } } #[cfg(not(feature = "e2e"))] @@ -40,10 +36,7 @@ pub(crate) fn options() -> WgpuConfiguration { } let device = std::sync::Arc::clone(&setup.device_descriptor); setup.device_descriptor = std::sync::Arc::new(move |adapter| sparing(device(adapter))); - WgpuConfiguration { - wgpu_setup: WgpuSetup::CreateNew(setup), - ..Default::default() - } + WgpuConfiguration { wgpu_setup: WgpuSetup::CreateNew(setup), ..Default::default() } } /// The one API to open, or `None` for eframe's choice: `WGPU_BACKEND` when it is set, and every @@ -109,10 +102,7 @@ mod tests { fn the_device_is_asked_to_reserve_memory_by_small_blocks() { let device = sparing(wgpu::DeviceDescriptor::default()); - assert!(matches!( - device.memory_hints, - wgpu::MemoryHints::MemoryUsage - )); + assert!(matches!(device.memory_hints, wgpu::MemoryHints::MemoryUsage)); } #[test] diff --git a/crates/app/src/sight.rs b/crates/app/src/sight.rs index 2c5e9da36..030dca0ea 100644 --- a/crates/app/src/sight.rs +++ b/crates/app/src/sight.rs @@ -19,12 +19,7 @@ pub(crate) struct Watched { impl Watched { pub(crate) fn new(app: ui::DevNotesApp) -> Self { - Watched { - app, - hidden: false, - put_away: 0, - read: 0, - } + Watched { app, hidden: false, put_away: 0, read: 0 } } fn follow(&mut self, ctx: &Context) { @@ -55,11 +50,7 @@ impl eframe::App for Watched { fn ui(&mut self, ui: &mut Ui, frame: &mut eframe::Frame) { self.app.ui(ui, frame); self.follow(ui.ctx()); - let said = if self.hidden { - "window-hidden" - } else { - "window-shown" - }; + let said = if self.hidden { "window-hidden" } else { "window-shown" }; mark(ui, said, said); mark(ui, "window-put-away", &self.put_away.to_string()); } diff --git a/crates/app/src/unpainted.rs b/crates/app/src/unpainted.rs index 9a1316284..7a1011669 100644 --- a/crates/app/src/unpainted.rs +++ b/crates/app/src/unpainted.rs @@ -32,12 +32,9 @@ impl egui::Plugin for Unpainted { } fn asks_for_capture(output: &FullOutput) -> bool { - output - .viewport_output - .get(&ViewportId::ROOT) - .is_some_and(|root| { - root.commands - .iter() - .any(|command| matches!(command, ViewportCommand::Screenshot(_))) - }) + output.viewport_output.get(&ViewportId::ROOT).is_some_and(|root| { + root.commands + .iter() + .any(|command| matches!(command, ViewportCommand::Screenshot(_))) + }) } diff --git a/crates/app/tests/windows_resources.rs b/crates/app/tests/windows_resources.rs index 5f9d37b22..a91f846f0 100644 --- a/crates/app/tests/windows_resources.rs +++ b/crates/app/tests/windows_resources.rs @@ -42,7 +42,5 @@ fn resource_types(file: &[u8]) -> Vec { let named = u16_at(root + 12); let numbered = u16_at(root + 14); - (named..named + numbered) - .map(|entry| u32_at(root + 16 + 8 * entry)) - .collect() + (named..named + numbered).map(|entry| u32_at(root + 16 + 8 * entry)).collect() } diff --git a/crates/drawing/src/edit.rs b/crates/drawing/src/edit.rs index 18ac5dbca..ef2de9e7a 100644 --- a/crates/drawing/src/edit.rs +++ b/crates/drawing/src/edit.rs @@ -103,10 +103,7 @@ impl Frame { /// A point of the frame's own plane, in the scene's. fn on_scene(&self, x: f64, y: f64) -> Point { let (sin, cos) = self.angle.to_radians().sin_cos(); - Point { - x: self.centre.x + x * cos - y * sin, - y: self.centre.y + x * sin + y * cos, - } + Point { x: self.centre.x + x * cos - y * sin, y: self.centre.y + x * sin + y * cos } } fn on_frame(&self, at: Point) -> (f64, f64) { @@ -117,11 +114,7 @@ impl Frame { pub fn grip(&self, grip: Grip) -> Point { let (x, y) = grip.place(); - let reach = if grip == Grip::Rotate { - self.reach - } else { - 0.0 - }; + let reach = if grip == Grip::Rotate { self.reach } else { 0.0 }; self.on_scene(x * self.width / 2.0, y * self.height / 2.0 - reach) } @@ -136,13 +129,7 @@ impl Frame { } pub fn corners(&self) -> [Point; 4] { - [ - Grip::TopLeft, - Grip::TopRight, - Grip::BottomRight, - Grip::BottomLeft, - ] - .map(|corner| self.grip(corner)) + [Grip::TopLeft, Grip::TopRight, Grip::BottomRight, Grip::BottomLeft].map(|corner| self.grip(corner)) } } @@ -416,10 +403,7 @@ impl Editor { let mut step = 1.0; while step <= steps { let part = step / steps; - let at = Point { - x: from.x + (to.x - from.x) * part, - y: from.y + (to.y - from.y) * part, - }; + let at = Point { x: from.x + (to.x - from.x) * part, y: from.y + (to.y - from.y) * part }; let come_onto = |object: &Object| object.contains(at) && !object.contains(last); let gone: Vec = (0..self.drawing.objects.len()) .filter(|&index| come_onto(&self.drawing.objects[index])) @@ -498,17 +482,13 @@ impl Editor { let reach = GRIP_REACH / self.scale; let near = |end: Point| (end.x - at.x).abs() <= reach && (end.y - at.y).abs() <= reach; let ends = self.arrow_ends()?; - ends.into_iter() - .find(|(_, place)| near(*place)) - .map(|(end, _)| end) + ends.into_iter().find(|(_, place)| near(*place)).map(|(end, _)| end) } /// Asked while the arrow tool is in hand or an end is dragged. pub fn attaching(&self, at: Point) -> Option { let kept = match &self.gesture { - Some(Gesture::MovingEnd { index, end, .. }) => { - end.other_bound(&self.drawing.objects[*index]) - } + Some(Gesture::MovingEnd { index, end, .. }) => end.other_bound(&self.drawing.objects[*index]), Some(Gesture::Arrow { held, .. }) => held.as_ref().map(|hold| hold.id.as_str()), None if self.tool == Tool::Arrow => None, _ => return None, @@ -588,10 +568,7 @@ impl Editor { /// The topmost object under a point. fn object_at(&self, at: Point) -> Option { - self.drawing - .objects - .iter() - .rposition(|object| object.contains(at)) + self.drawing.objects.iter().rposition(|object| object.contains(at)) } /// A pointer pressed. `adding` is Shift: an object joins the selection or leaves it. @@ -634,11 +611,7 @@ impl Editor { && let Some(end) = self.end_at(at) && let [index] = self.selected[..] { - self.gesture = Some(Gesture::MovingEnd { - index, - end, - from: at, - }); + self.gesture = Some(Gesture::MovingEnd { index, end, from: at }); return; } if let Some(grip) = self.grip_at(at).filter(|_| !adding) @@ -646,17 +619,9 @@ impl Editor { { let before = self.selection(); self.gesture = Some(if grip == Grip::Rotate { - Gesture::Rotating { - frame, - from: bearing(frame.centre, at), - before, - } + Gesture::Rotating { frame, from: bearing(frame.centre, at), before } } else { - Gesture::Scaling { - grip, - frame, - before, - } + Gesture::Scaling { grip, frame, before } }); return; } @@ -679,11 +644,7 @@ impl Editor { self.selected = vec![index]; } let before = self.selection(); - self.gesture = Some(Gesture::Moving { - from: at, - before, - reselected, - }); + self.gesture = Some(Gesture::Moving { from: at, before, reselected }); } fn selection(&self) -> Selected { @@ -720,16 +681,8 @@ impl Editor { move_to(self, before, *from, to); } } - Gesture::Scaling { - grip, - frame, - before, - } => scale_to(self, before, *grip, *frame, to), - Gesture::Rotating { - frame, - from, - before, - } => { + Gesture::Scaling { grip, frame, before } => scale_to(self, before, *grip, *frame, to), + Gesture::Rotating { frame, from, before } => { rotate_to(self, before, *frame, bearing(frame.centre, to) - *from); } Gesture::Marquee { to: end, .. } => *end = to, @@ -747,16 +700,7 @@ impl Editor { let least = CLICKED / self.scale; let clicked = dragged.width < least && dragged.height < least; let (width, height) = CLICK_SIZE; - let bounds = if clicked { - Box { - left: from.x, - top: from.y, - width, - height, - } - } else { - dragged - }; + let bounds = if clicked { Box { left: from.x, top: from.y, width, height } } else { dragged }; self.reshape_last(tool, bounds); self.finish(); } @@ -766,9 +710,7 @@ impl Editor { return; }; let kept = held.map(|hold| hold.id); - let hold = self - .hold_at(at) - .filter(|hold| Some(&hold.id) != kept.as_ref()); + let hold = self.hold_at(at).filter(|hold| Some(&hold.id) != kept.as_ref()); End::To.hold(&mut arrow, hold.as_ref()); self.drawing.objects.push(arrow); let last = self.drawing.objects.len() - 1; @@ -780,16 +722,12 @@ impl Editor { Some(Gesture::MovingEnd { from, .. }) if from == at => {} Some(Gesture::MovingEnd { index, end, .. }) => { let kept = end.other_bound(&self.drawing.objects[index]); - let hold = self - .hold_at(at) - .filter(|hold| Some(hold.id.as_str()) != kept); + let hold = self.hold_at(at).filter(|hold| Some(hold.id.as_str()) != kept); self.move_end(index, end, hold.as_ref(), at); self.keep(); } Some(Gesture::Marquee { from, to }) => self.select_within(drag_box(from, to)), - Some(Gesture::Moving { - from, reselected, .. - }) => { + Some(Gesture::Moving { from, reselected, .. }) => { if from != at { self.settle(); } else if reselected { @@ -834,12 +772,7 @@ impl Editor { let Some(index) = self.editing.take() else { return; }; - if self.drawing.objects[index] - .text() - .unwrap_or_default() - .trim() - .is_empty() - { + if self.drawing.objects[index].text().unwrap_or_default().trim().is_empty() { self.drawing.objects.remove(index); self.selected.clear(); } @@ -881,10 +814,7 @@ impl Editor { text.put("fontFamily", TEXT_FONT); text.put_number("strokeWidth", 0.0); text.set_size(TEXT_WIDTH, text_height(1, TEXT_SIZE, text.line_height())); - text.set_centre(Point { - x: at.x + TEXT_WIDTH / 2.0, - y: at.y, - }); + text.set_centre(Point { x: at.x + TEXT_WIDTH / 2.0, y: at.y }); self.drawing.objects.push(text); self.tool = Tool::Select; self.kept.clear(); @@ -918,18 +848,13 @@ impl Editor { } fn select_within(&mut self, marquee: Box) { - let touched = self - .drawing - .objects - .iter() - .enumerate() - .filter(|(_, object)| { - let bounds = object.bounds(); - bounds.left < marquee.left + marquee.width - && marquee.left < bounds.left + bounds.width - && bounds.top < marquee.top + marquee.height - && marquee.top < bounds.top + bounds.height - }); + let touched = self.drawing.objects.iter().enumerate().filter(|(_, object)| { + let bounds = object.bounds(); + bounds.left < marquee.left + marquee.width + && marquee.left < bounds.left + bounds.width + && bounds.top < marquee.top + marquee.height + && marquee.top < bounds.top + bounds.height + }); let touched: Vec = touched.map(|(index, _)| index).collect(); if marquee.width > 0.0 || marquee.height > 0.0 { for index in touched { @@ -945,12 +870,10 @@ impl Editor { /// it: a shape does, under the text or the arrow over it. fn holder_at(&self, at: Point) -> Option<(usize, Option)> { let objects = self.drawing.objects.iter().enumerate().rev(); - objects - .filter(|(_, object)| holds_arrows(object)) - .find_map(|(index, object)| { - let side = self.side_at(object, at); - (side.is_some() || object.contains(at)).then_some((index, side)) - }) + objects.filter(|(_, object)| holds_arrows(object)).find_map(|(index, object)| { + let side = self.side_at(object, at); + (side.is_some() || object.contains(at)).then_some((index, side)) + }) } fn side_at(&self, object: &Object, at: Point) -> Option { @@ -992,10 +915,7 @@ impl Editor { let arrow = &self.drawing.objects[index]; let from = self.held_by(arrow, End::From); let to = self.held_by(arrow, End::To); - set_arrow( - &mut self.drawing.objects[index], - bound_ends(drawn, from.as_ref(), to.as_ref()), - ); + set_arrow(&mut self.drawing.objects[index], bound_ends(drawn, from.as_ref(), to.as_ref())); } /// The arrows bound to anything take their place from it. @@ -1060,10 +980,7 @@ fn move_to(editor: &mut Editor, before: &Selected, from: Point, to: Point) { for (index, object) in before { let centre = object.centre(); let moved = &mut editor.drawing.objects[*index]; - moved.set_centre(Point { - x: centre.x + dx, - y: centre.y + dy, - }); + moved.set_centre(Point { x: centre.x + dx, y: centre.y + dy }); if let Some([x1, y1, x2, y2]) = object.ends() { moved.set_ends([x1 + dx, y1 + dy, x2 + dx, y2 + dy]); } @@ -1077,11 +994,7 @@ fn scale_to(editor: &mut Editor, before: &Selected, grip: Grip, frame: Frame, to // From the handle's opposite, which stays where it is. let anchor = (-place_x * frame.width / 2.0, -place_y * frame.height / 2.0); let along = |place: f64, size: f64, at: f64, from: f64| { - if place == 0.0 { - 1.0 - } else { - ((at - from) * place / size).max(LEAST_SCALE) - } + if place == 0.0 { 1.0 } else { ((at - from) * place / size).max(LEAST_SCALE) } }; let mut scale_x = along(place_x, frame.width, x, anchor.0); let mut scale_y = along(place_y, frame.height, y, anchor.1); @@ -1092,20 +1005,13 @@ fn scale_to(editor: &mut Editor, before: &Selected, grip: Grip, frame: Frame, to } for (index, object) in before { let (cx, cy) = frame.on_frame(object.centre()); - let centre = frame.on_scene( - anchor.0 + (cx - anchor.0) * scale_x, - anchor.1 + (cy - anchor.1) * scale_y, - ); + let centre = + frame.on_scene(anchor.0 + (cx - anchor.0) * scale_x, anchor.1 + (cy - anchor.1) * scale_y); let scaled = &mut editor.drawing.objects[*index]; scaled.set_centre(centre); if object.kind() == Kind::Textbox && place_y == 0.0 { let width = (object.width() * scale_x).max(TEXT_MIN_WIDTH); - let lines = wrap( - object.text().unwrap_or_default(), - width, - object.font_size(), - &editor.fonts, - ); + let lines = wrap(object.text().unwrap_or_default(), width, object.font_size(), &editor.fonts); let height = text_height(lines.len(), object.font_size(), object.line_height()); scaled.set_size(width, height); } else { @@ -1116,14 +1022,8 @@ fn scale_to(editor: &mut Editor, before: &Selected, grip: Grip, frame: Frame, to } fn rotate_to(editor: &mut Editor, before: &Selected, frame: Frame, degrees: f64) { - let turned = Frame { - angle: degrees, - ..frame - }; - let still = Frame { - angle: 0.0, - ..frame - }; + let turned = Frame { angle: degrees, ..frame }; + let still = Frame { angle: 0.0, ..frame }; for (index, object) in before { let (x, y) = still.on_frame(object.centre()); let rotated = &mut editor.drawing.objects[*index]; diff --git a/crates/drawing/src/edit/tests.rs b/crates/drawing/src/edit/tests.rs index 9e00068be..ec51012a6 100644 --- a/crates/drawing/src/edit/tests.rs +++ b/crates/drawing/src/edit/tests.rs @@ -71,11 +71,7 @@ fn a_new_drawing_is_written_as_a_scene_read_back() { let read = Drawing::read(&editor.body()).unwrap(); assert_eq!(read.objects.len(), 1); - assert!( - editor - .body() - .starts_with(r#"{"version":1,"scene":{"version":"7.4.0""#) - ); + assert!(editor.body().starts_with(r#"{"version":1,"scene":{"version":"7.4.0""#)); } #[test] @@ -256,10 +252,7 @@ fn a_text_is_typed_where_clicked_its_left_edge_there() { assert_eq!(editor.tool(), Tool::Select); assert_eq!(text.centre(), at(100.0, 20.0)); - assert_eq!( - (text.text(), text.font_size(), text.stroke_width()), - (Some(""), 18.0, 0.0) - ); + assert_eq!((text.text(), text.font_size(), text.stroke_width()), (Some(""), 18.0, 0.0)); assert_eq!(text.font_family(), "Inter Variable, sans-serif"); assert!(editor.editing().is_some_and(|(index, _)| index == 0)); assert_eq!(editor.frame(), None, "typed into, it has no handles"); @@ -430,10 +423,7 @@ fn a_marquee_is_shown_while_it_is_dragged() { editor.drag(at(50.0, 300.0)); let shown = editor.marquee().unwrap(); - assert_eq!( - (shown.left, shown.top, shown.width, shown.height), - (50.0, 250.0, 70.0, 50.0) - ); + assert_eq!((shown.left, shown.top, shown.width, shown.height), (50.0, 250.0, 70.0, 50.0)); editor.release(at(50.0, 300.0)); assert_eq!(editor.marquee(), None); } @@ -491,11 +481,7 @@ fn a_corner_keeps_the_proportions_from_the_opposite_corner() { let corner = frame.grip(Grip::BottomRight); let anchor = frame.grip(Grip::TopLeft); - drag( - &mut editor, - corner, - at(anchor.x + frame.width * 2.0, anchor.y + frame.height * 2.0), - ); + drag(&mut editor, corner, at(anchor.x + frame.width * 2.0, anchor.y + frame.height * 2.0)); let shape = object(&editor, 0); assert_eq!((shape.scale_x(), shape.scale_y()), (2.0, 2.0)); @@ -587,11 +573,7 @@ fn a_text_is_scaled_by_its_corners() { let frame = editor.frame().unwrap(); let corner = frame.grip(Grip::BottomRight); - drag( - &mut editor, - corner, - at(corner.x + frame.width, corner.y + frame.height), - ); + drag(&mut editor, corner, at(corner.x + frame.width, corner.y + frame.height)); assert_eq!(object(&editor, 0).scale_x(), 2.0); assert_eq!(object(&editor, 0).width(), 180.0); @@ -602,11 +584,7 @@ fn the_rotation_handle_turns_around_the_centre() { let mut editor = with_a_rectangle(); let frame = editor.frame().unwrap(); - drag( - &mut editor, - frame.grip(Grip::Rotate), - at(frame.centre.x + 100.0, frame.centre.y), - ); + drag(&mut editor, frame.grip(Grip::Rotate), at(frame.centre.x + 100.0, frame.centre.y)); assert_eq!(object(&editor, 0).angle(), 90.0); assert_eq!(object(&editor, 0).centre(), frame.centre); @@ -621,11 +599,7 @@ fn several_objects_turn_around_their_frame() { editor.release(at(150.0, 130.0)); let frame = editor.frame().unwrap(); - drag( - &mut editor, - frame.grip(Grip::Rotate), - at(frame.centre.x, frame.centre.y + 100.0), - ); + drag(&mut editor, frame.grip(Grip::Rotate), at(frame.centre.x, frame.centre.y + 100.0)); assert_eq!(object(&editor, 0).angle(), 180.0); assert!(object(&editor, 0).centre().x > object(&editor, 1).centre().x); @@ -734,11 +708,7 @@ fn the_history_keeps_sixty_states() { let mut editor = with_a_rectangle(); for step in 0..70 { let from = object(&editor, 0).centre(); - drag( - &mut editor, - from, - at(from.x + 1.0, from.y + f64::from(step % 2)), - ); + drag(&mut editor, from, at(from.x + 1.0, from.y + f64::from(step % 2))); } let mut back = 0; @@ -772,10 +742,7 @@ fn a_click_leaves_an_arrow_where_it_stands_until_its_shape_moves() { let mut editor = Editor::open(body, Arc::new(fonts())); drag(&mut editor, at(100.0, 100.0), at(100.0, 100.0)); - assert_eq!( - object(&editor, 1).ends(), - Some([300.0, 100.0, 400.0, 100.0]) - ); + assert_eq!(object(&editor, 1).ends(), Some([300.0, 100.0, 400.0, 100.0])); drag(&mut editor, at(100.0, 100.0), at(100.0, 110.0)); assert_ne!(object(&editor, 1).ends().unwrap()[0], 300.0); @@ -994,10 +961,7 @@ fn the_shape_an_end_would_hold_is_told_while_an_arrow_is_drawn_or_an_end_moved() editor.set_tool(Tool::Arrow); assert!(editor.attaching(on_the_second).is_some()); editor.press(at(50.0, 30.0), false); - assert!( - editor.attaching(at(60.0, 30.0)).is_none(), - "not the one it starts on" - ); + assert!(editor.attaching(at(60.0, 30.0)).is_none(), "not the one it starts on"); editor.release(at(200.0, 200.0)); let end = editor.arrow_ends().unwrap()[1].1; @@ -1029,27 +993,15 @@ fn an_arrow_follows_a_shape_resized_and_rotated() { drag(&mut editor, at(350.0, 30.0), at(350.0, 30.0)); // Its left side pulled 50 to the left. drag(&mut editor, at(299.0, 30.0), at(249.0, 30.0)); - assert!( - (ends(&editor)[2] - 249.0).abs() < 1.0, - "{:?}", - ends(&editor) - ); + assert!((ends(&editor)[2] - 249.0).abs() < 1.0, "{:?}", ends(&editor)); let mut editor = joined(); drag(&mut editor, at(350.0, 30.0), at(350.0, 30.0)); let frame = editor.frame().unwrap(); let handle = frame.grip(Grip::Rotate); - drag( - &mut editor, - handle, - at(frame.centre.x + 200.0, frame.centre.y), - ); + drag(&mut editor, handle, at(frame.centre.x + 200.0, frame.centre.y)); // Turned a quarter, it is 62 wide: its left side came closer to its centre. - assert!( - (ends(&editor)[2] - 319.0).abs() < 1.5, - "{:?}", - ends(&editor) - ); + assert!((ends(&editor)[2] - 319.0).abs() < 1.5, "{:?}", ends(&editor)); } #[test] @@ -1057,11 +1009,7 @@ fn an_end_let_go_on_the_middle_of_a_side_stays_on_it() { let mut editor = joined(); drag(&mut editor, at(299.0, 30.0), at(352.0, 64.0)); assert_eq!(object(&editor, 2).to(), object(&editor, 1).id()); - assert_eq!( - ends(&editor)[2..], - [350.0, 61.0], - "the middle of its bottom" - ); + assert_eq!(ends(&editor)[2..], [350.0, 61.0], "the middle of its bottom"); let stored = editor.body(); assert!(stored.contains(r#""toAnchor":"bottom""#), "{stored}"); assert!(!stored.contains("fromAnchor")); @@ -1070,19 +1018,11 @@ fn an_end_let_go_on_the_middle_of_a_side_stays_on_it() { drag(&mut editor, at(380.0, 10.0), at(380.0, 110.0)); assert_eq!(ends(&editor)[2..], [350.0, 161.0]); drag(&mut editor, at(401.0, 130.0), at(501.0, 130.0)); - assert!( - (ends(&editor)[2] - 400.0).abs() < 1.0, - "{:?}", - ends(&editor) - ); + assert!((ends(&editor)[2] - 400.0).abs() < 1.0, "{:?}", ends(&editor)); let mut reopened = Editor::open(&editor.body(), Arc::new(fonts())); drag(&mut reopened, at(480.0, 150.0), at(480.0, 50.0)); - assert_eq!( - ends(&reopened)[3], - 61.0, - "read back, it is on the same point" - ); + assert_eq!(ends(&reopened)[3], 61.0, "read back, it is on the same point"); } #[test] @@ -1162,10 +1102,7 @@ fn a_shape_is_shown_while_it_is_dragged() { let shown = editor.revision(); editor.drag(at(40.0, 20.0)); - assert_eq!( - (object(&editor, 0).width(), object(&editor, 0).height()), - (40.0, 20.0) - ); + assert_eq!((object(&editor, 0).width(), object(&editor, 0).height()), (40.0, 20.0)); assert!(editor.revision() > shown); assert!(!editor.can_undo(), "a step of the history once let go"); } @@ -1191,12 +1128,7 @@ fn a_click_is_told_from_a_drag_on_the_screen() { #[test] fn a_handle_is_taken_from_as_far_on_the_screen_whatever_the_scale() { - for (scale, away, taken) in [ - (1.0, 8.0, true), - (1.0, 8.5, false), - (2.0, 4.0, true), - (2.0, 4.5, false), - ] { + for (scale, away, taken) in [(1.0, 8.0, true), (1.0, 8.5, false), (2.0, 4.0, true), (2.0, 4.5, false)] { let mut editor = with_a_rectangle(); editor.set_scale(scale); let corner = editor.frame().unwrap().grip(Grip::BottomRight); @@ -1208,12 +1140,7 @@ fn a_handle_is_taken_from_as_far_on_the_screen_whatever_the_scale() { #[test] fn an_end_of_an_arrow_is_taken_from_as_far_on_the_screen() { - for (dx, dy, taken) in [ - (8.0, 0.0, true), - (0.0, 8.0, true), - (8.5, 0.0, false), - (0.0, 8.5, false), - ] { + for (dx, dy, taken) in [(8.0, 0.0, true), (0.0, 8.0, true), (8.5, 0.0, false), (0.0, 8.5, false)] { let mut editor = joined(); let end = at(299.0 + dx, 30.0 + dy); editor.press(end, false); @@ -1244,10 +1171,7 @@ fn the_frame_of_a_turned_shape_turns_with_it() { .into_iter() .zip([(181.0, 79.0), (181.0, 181.0), (119.0, 181.0), (119.0, 79.0)]) { - assert!( - (corner.x - x).abs() < 1e-6 && (corner.y - y).abs() < 1e-6, - "{corner:?}" - ); + assert!((corner.x - x).abs() < 1e-6 && (corner.y - y).abs() < 1e-6, "{corner:?}"); } } @@ -1267,15 +1191,8 @@ fn a_turned_shape_is_scaled_along_its_own_sides() { fn where_an_arrow_is_held_is_told_from_as_far_as_its_side_is_reached() { let mut editor = joined(); editor.set_tool(Tool::Arrow); - for (dx, dy, told) in [ - (8.0, 0.0, true), - (8.5, 0.0, false), - (0.0, 8.0, true), - (0.0, 8.5, false), - ] { - let chosen = editor - .attaching(at(401.0 + dx, 30.0 + dy)) - .and_then(|found| found.chosen); + for (dx, dy, told) in [(8.0, 0.0, true), (8.5, 0.0, false), (0.0, 8.0, true), (0.0, 8.5, false)] { + let chosen = editor.attaching(at(401.0 + dx, 30.0 + dy)).and_then(|found| found.chosen); assert_eq!(chosen, told.then_some(at(401.0, 30.0)), "{dx} {dy}"); } } @@ -1298,10 +1215,7 @@ fn an_arrow_bound_to_a_shape_that_is_gone_stays_where_it_is() { let mut editor = Editor::open(body, Arc::new(fonts())); drag(&mut editor, at(100.0, 100.0), at(100.0, 110.0)); - assert_eq!( - object(&editor, 1).ends(), - Some([300.0, 100.0, 400.0, 100.0]) - ); + assert_eq!(object(&editor, 1).ends(), Some([300.0, 100.0, 400.0, 100.0])); } #[test] @@ -1338,9 +1252,6 @@ fn the_eraser_tells_what_it_would_take_by_its_frame() { let editor = with_a_rectangle(); let frame = editor.erasable(at(150.0, 130.0)).unwrap(); - assert_eq!( - (frame.centre, frame.width, frame.height), - (at(150.0, 130.0), 102.0, 62.0) - ); + assert_eq!((frame.centre, frame.width, frame.height), (at(150.0, 130.0), 102.0, 62.0)); assert!(editor.erasable(at(0.0, 0.0)).is_none()); } diff --git a/crates/drawing/src/geometry.rs b/crates/drawing/src/geometry.rs index 78b2588c6..6428831d9 100644 --- a/crates/drawing/src/geometry.rs +++ b/crates/drawing/src/geometry.rs @@ -41,10 +41,7 @@ pub fn arrow_path([x1, y1, x2, y2]: Ends) -> [PathCommand; 6] { let reach = HEAD.min(length); let (foot_x, foot_y) = (x2 - ux * reach, y2 - uy * reach); let half = reach / 2.0; - let at = |x: f64, y: f64| Point { - x: (x * 10.0).round() / 10.0, - y: (y * 10.0).round() / 10.0, - }; + let at = |x: f64, y: f64| Point { x: (x * 10.0).round() / 10.0, y: (y * 10.0).round() / 10.0 }; [ PathCommand::Move(at(x1, y1)), PathCommand::Line(at(foot_x, foot_y)), @@ -65,10 +62,7 @@ pub(crate) fn number(value: f64) -> String { impl Box { pub fn centre(&self) -> Point { - Point { - x: self.left + self.width / 2.0, - y: self.top + self.height / 2.0, - } + Point { x: self.left + self.width / 2.0, y: self.top + self.height / 2.0 } } } @@ -80,17 +74,10 @@ pub fn edge_point(bounds: &Box, toward: Point) -> Point { return centre; } let along = |half: f64, delta: f64| { - if delta == 0.0 { - f64::INFINITY - } else { - half / delta.abs() - } + if delta == 0.0 { f64::INFINITY } else { half / delta.abs() } }; let scale = along(bounds.width / 2.0, dx).min(along(bounds.height / 2.0, dy)); - Point { - x: centre.x + dx * scale, - y: centre.y + dy * scale, - } + Point { x: centre.x + dx * scale, y: centre.y + dy * scale } } /// What an end of an arrow holds on to. @@ -143,22 +130,10 @@ pub fn drag_box(from: Point, to: Point) -> Box { pub fn diamond_points(width: f64, height: f64) -> [Point; 4] { [ - Point { - x: width / 2.0, - y: 0.0, - }, - Point { - x: width, - y: height / 2.0, - }, - Point { - x: width / 2.0, - y: height, - }, - Point { - x: 0.0, - y: height / 2.0, - }, + Point { x: width / 2.0, y: 0.0 }, + Point { x: width, y: height / 2.0 }, + Point { x: width / 2.0, y: height }, + Point { x: 0.0, y: height / 2.0 }, ] } @@ -175,12 +150,7 @@ pub fn scene_box(boxes: &[Box], margin: f64) -> Option { let top = boxes.iter().map(|b| b.top).reduce(f64::min)? - margin; let right = boxes.iter().map(|b| b.left + b.width).reduce(f64::max)? + margin; let bottom = boxes.iter().map(|b| b.top + b.height).reduce(f64::max)? + margin; - Some(Box { - left, - top, - width: right - left, - height: bottom - top, - }) + Some(Box { left, top, width: right - left, height: bottom - top }) } /// What the commands of a path cover, curves to their furthest; `None` for no point at all. @@ -219,10 +189,7 @@ pub fn smooth_path(points: &[Point]) -> Option> { for pair in points.windows(2) { let (control, next) = (pair[0], pair[1]); if control != next { - let middle = Point { - x: f64::midpoint(control.x, next.x), - y: f64::midpoint(control.y, next.y), - }; + let middle = Point { x: f64::midpoint(control.x, next.x), y: f64::midpoint(control.y, next.y) }; path.push(PathCommand::Quad(control, middle)); } } @@ -249,10 +216,8 @@ fn decimated(points: &[Point]) -> Vec { /// Where a curve turns, on each axis it turns on, as a point of the box around it. fn furthest(from: Point, control: Point, to: Point) -> [Option; 2] { - let at = |t: f64| Point { - x: quadratic(from.x, control.x, to.x, t), - y: quadratic(from.y, control.y, to.y, t), - }; + let at = + |t: f64| Point { x: quadratic(from.x, control.x, to.x, t), y: quadratic(from.y, control.y, to.y, t) }; let turn = |from: f64, control: f64, to: f64| { let t = (from - control) / (from - 2.0 * control + to); (t > 0.0 && t < 1.0).then(|| at(t)) @@ -271,12 +236,7 @@ pub fn points_box(points: &[Point]) -> Option { let top = points.iter().map(|point| point.y).reduce(f64::min)?; let right = points.iter().map(|point| point.x).reduce(f64::max)?; let bottom = points.iter().map(|point| point.y).reduce(f64::max)?; - Some(Box { - left, - top, - width: right - left, - height: bottom - top, - }) + Some(Box { left, top, width: right - left, height: bottom - top }) } #[cfg(test)] @@ -284,12 +244,7 @@ pub fn points_box(points: &[Point]) -> Option { mod tests { use super::*; - const BOX: Box = Box { - left: 0.0, - top: 0.0, - width: 100.0, - height: 50.0, - }; + const BOX: Box = Box { left: 0.0, top: 0.0, width: 100.0, height: 50.0 }; fn at(x: f64, y: f64) -> Point { Point { x, y } @@ -327,22 +282,10 @@ mod tests { fn each_bound_end_is_on_its_shape_facing_the_other() { let left = Held::Edge(BOX); let right = Held::Edge(Box { left: 200.0, ..BOX }); - assert_eq!( - bound_ends([0.0; 4], Some(&left), Some(&right)), - [100.0, 25.0, 200.0, 25.0] - ); - assert_eq!( - bound_ends([0.0, 0.0, 50.0, 300.0], Some(&left), None), - [50.0, 50.0, 50.0, 300.0] - ); - assert_eq!( - bound_ends([400.0, 25.0, 0.0, 0.0], None, Some(&right)), - [400.0, 25.0, 300.0, 25.0] - ); - assert_eq!( - bound_ends([1.0, 2.0, 3.0, 4.0], None, None), - [1.0, 2.0, 3.0, 4.0] - ); + assert_eq!(bound_ends([0.0; 4], Some(&left), Some(&right)), [100.0, 25.0, 200.0, 25.0]); + assert_eq!(bound_ends([0.0, 0.0, 50.0, 300.0], Some(&left), None), [50.0, 50.0, 50.0, 300.0]); + assert_eq!(bound_ends([400.0, 25.0, 0.0, 0.0], None, Some(&right)), [400.0, 25.0, 300.0, 25.0]); + assert_eq!(bound_ends([1.0, 2.0, 3.0, 4.0], None, None), [1.0, 2.0, 3.0, 4.0]); } #[test] @@ -356,12 +299,7 @@ mod tests { #[test] fn a_drag_reads_whichever_way_it_went() { - let covered = Box { - left: 10.0, - top: 40.0, - width: 40.0, - height: 20.0, - }; + let covered = Box { left: 10.0, top: 40.0, width: 40.0, height: 20.0 }; for (from, to) in [ (at(50.0, 40.0), at(10.0, 60.0)), (at(10.0, 40.0), at(50.0, 60.0)), @@ -381,53 +319,21 @@ mod tests { #[test] fn a_picture_s_longest_side_is_brought_to_its_size_never_enlarged_too_much() { - for (width, height, scale) in [ - (800.0, 200.0, 0.5), - (200.0, 800.0, 0.5), - (100.0, 50.0, 2.0), - (0.0, 0.0, 2.0), - ] { - let bounds = Box { - width, - height, - ..BOX - }; - assert_eq!( - picture_scale(&bounds, 400.0, 2.0), - scale, - "{width} {height}" - ); + for (width, height, scale) in + [(800.0, 200.0, 0.5), (200.0, 800.0, 0.5), (100.0, 50.0, 2.0), (0.0, 0.0, 2.0)] + { + let bounds = Box { width, height, ..BOX }; + assert_eq!(picture_scale(&bounds, 400.0, 2.0), scale, "{width} {height}"); } - assert_eq!( - picture_scale( - &Box { - width: 0.5, - height: 0.0, - ..BOX - }, - 400.0, - 900.0 - ), - 400.0 - ); + assert_eq!(picture_scale(&Box { width: 0.5, height: 0.0, ..BOX }, 400.0, 900.0), 400.0); } #[test] fn a_scene_is_framed_by_all_that_is_on_it_with_room_around() { - let small = Box { - left: 150.0, - top: -20.0, - width: 10.0, - height: 10.0, - }; + let small = Box { left: 150.0, top: -20.0, width: 10.0, height: 10.0 }; assert_eq!( scene_box(&[BOX, small], 10.0), - Some(Box { - left: -10.0, - top: -30.0, - width: 180.0, - height: 90.0 - }) + Some(Box { left: -10.0, top: -30.0, width: 180.0, height: 90.0 }) ); assert_eq!(scene_box(&[], MARGIN), None); } @@ -436,13 +342,9 @@ mod tests { fn a_path_is_covered_to_where_its_curves_turn() { use PathCommand::{Close, Line, Move, Quad}; - let covered = - |path: &[PathCommand]| path_box(path).map(|b| [b.left, b.top, b.width, b.height]); + let covered = |path: &[PathCommand]| path_box(path).map(|b| [b.left, b.top, b.width, b.height]); - assert_eq!( - covered(&[Move(at(1.0, 2.0)), Line(at(5.0, 9.0)), Close]), - Some([1.0, 2.0, 4.0, 7.0]) - ); + assert_eq!(covered(&[Move(at(1.0, 2.0)), Line(at(5.0, 9.0)), Close]), Some([1.0, 2.0, 4.0, 7.0])); // A curve up to its control and back: it goes half the way. assert_eq!( covered(&[Move(at(0.0, 0.0)), Quad(at(10.0, 20.0), at(20.0, 0.0))]), @@ -462,10 +364,7 @@ mod tests { covered(&[Move(at(0.0, 0.0)), Quad(at(1.0, 5.0), at(10.0, 10.0))]), Some([0.0, 0.0, 10.0, 10.0]) ); - assert_eq!( - covered(&[Quad(at(9.0, 9.0), at(1.0, 1.0))]), - Some([1.0, 1.0, 0.0, 0.0]) - ); + assert_eq!(covered(&[Quad(at(9.0, 9.0), at(1.0, 1.0))]), Some([1.0, 1.0, 0.0, 0.0])); assert_eq!(covered(&[Close]), None); assert_eq!(covered(&[]), None); } diff --git a/crates/drawing/src/marks.rs b/crates/drawing/src/marks.rs index 83e8093ff..0bc1b3aad 100644 --- a/crates/drawing/src/marks.rs +++ b/crates/drawing/src/marks.rs @@ -63,14 +63,7 @@ struct Plane { } impl Plane { - const IDENTITY: Self = Self { - a: 1.0, - b: 0.0, - c: 0.0, - d: 1.0, - e: 0.0, - f: 0.0, - }; + const IDENTITY: Self = Self { a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: 0.0, f: 0.0 }; /// Fabric's order: translate, rotate, scale, skew. fn of(object: &Object) -> Self { @@ -78,10 +71,7 @@ impl Plane { let (sin, cos) = object.angle().to_radians().sin_cos(); let (flip_x, flip_y) = object.flipped(); let mirror = |flipped: bool| if flipped { -1.0 } else { 1.0 }; - let (scale_x, scale_y) = ( - object.scale_x() * mirror(flip_x), - object.scale_y() * mirror(flip_y), - ); + let (scale_x, scale_y) = (object.scale_x() * mirror(flip_x), object.scale_y() * mirror(flip_y)); let (skew_x, skew_y) = object.skew(); let turned = Self { a: cos * scale_x, @@ -92,14 +82,8 @@ impl Plane { f: centre.y, }; turned - .then(Self { - c: skew_x.to_radians().tan(), - ..Self::IDENTITY - }) - .then(Self { - b: skew_y.to_radians().tan(), - ..Self::IDENTITY - }) + .then(Self { c: skew_x.to_radians().tan(), ..Self::IDENTITY }) + .then(Self { b: skew_y.to_radians().tan(), ..Self::IDENTITY }) } /// This plane, with `inner` inside it. @@ -115,10 +99,7 @@ impl Plane { } fn apply(self, at: Point) -> Point { - Point { - x: self.a * at.x + self.c * at.y + self.e, - y: self.b * at.x + self.d * at.y + self.f, - } + Point { x: self.a * at.x + self.c * at.y + self.e, y: self.b * at.x + self.d * at.y + self.f } } fn scale(self) -> f64 { @@ -159,11 +140,7 @@ fn add(marks: &mut Vec, object: &Object, outer: Plane, fonts: &Fonts) { } fn stroke_width(object: &Object, plane: Plane) -> f64 { - if object.stroke_uniform() { - object.stroke_width() - } else { - object.stroke_width() * plane.scale() - } + if object.stroke_uniform() { object.stroke_width() } else { object.stroke_width() * plane.scale() } } /// Round its centre, each corner an arc when it has a radius. @@ -180,10 +157,7 @@ fn rectangle(object: &Object) -> Vec { for (x, y, from) in corners { for step in 0..=CORNER_STEPS { let turned = from + FRAC_PI_2 * f64::from(step) / f64::from(CORNER_STEPS); - outline.push(Point { - x: x + radius * turned.cos(), - y: y + radius * turned.sin(), - }); + outline.push(Point { x: x + radius * turned.cos(), y: y + radius * turned.sin() }); } } outline @@ -194,10 +168,7 @@ fn ellipse(object: &Object) -> Vec { (0..ELLIPSE_STEPS) .map(|step| { let turned = TAU * f64::from(step) / f64::from(ELLIPSE_STEPS); - Point { - x: rx * turned.cos(), - y: ry * turned.sin(), - } + Point { x: rx * turned.cos(), y: ry * turned.sin() } }) .collect() } @@ -207,10 +178,7 @@ fn polygon(object: &Object) -> Vec { let middle = points_box(&points).map_or(Point { x: 0.0, y: 0.0 }, |bounds| bounds.centre()); points .iter() - .map(|point| Point { - x: point.x - middle.x, - y: point.y - middle.y, - }) + .map(|point| Point { x: point.x - middle.x, y: point.y - middle.y }) .collect() } @@ -218,23 +186,14 @@ fn polygon(object: &Object) -> Vec { fn add_path(marks: &mut Vec, object: &Object, plane: Plane) { let commands = object.path(); let middle = path_box(&commands).map_or(Point { x: 0.0, y: 0.0 }, |bounds| bounds.centre()); - let on_plane = |at: Point| { - plane.apply(Point { - x: at.x - middle.x, - y: at.y - middle.y, - }) - }; + let on_plane = |at: Point| plane.apply(Point { x: at.x - middle.x, y: at.y - middle.y }); let arrow = object.ends().is_some(); let mut flush = |points: &mut Vec, closed: bool| { if points.len() > 1 { marks.push(Mark::Line { points: std::mem::take(points), closed, - fill: if closed && arrow { - Fill::Stroke - } else { - Fill::None - }, + fill: if closed && arrow { Fill::Stroke } else { Fill::None }, hue: object.hue(), width: stroke_width(object, plane), }); @@ -269,13 +228,8 @@ fn add_path(marks: &mut Vec, object: &Object, plane: Plane) { fn along_curve(from: Point, control: Point, to: Point, t: f64) -> Point { let rest = 1.0 - t; - let at = |from: f64, control: f64, to: f64| { - rest * rest * from + 2.0 * rest * t * control + t * t * to - }; - Point { - x: at(from.x, control.x, to.x), - y: at(from.y, control.y, to.y), - } + let at = |from: f64, control: f64, to: f64| rest * rest * from + 2.0 * rest * t * control + t * t * to; + Point { x: at(from.x, control.x, to.x), y: at(from.y, control.y, to.y) } } fn add_text(marks: &mut Vec, object: &Object, plane: Plane, fonts: &Fonts) { @@ -287,10 +241,7 @@ fn add_text(marks: &mut Vec, object: &Object, plane: Plane, fonts: &Fonts) for line in wrap(text, object.width(), font_size, fonts) { marks.push(Mark::Words { text: line, - at: plane.apply(Point { - x: left, - y: baseline, - }), + at: plane.apply(Point { x: left, y: baseline }), angle: plane.angle(), size: font_size * plane.scale(), hue: object.hue(), @@ -315,12 +266,7 @@ mod tests { fn line(mark: &Mark) -> (&[Point], bool, Fill) { match mark { - Mark::Line { - points, - closed, - fill, - .. - } => (points, *closed, *fill), + Mark::Line { points, closed, fill, .. } => (points, *closed, *fill), Mark::Words { .. } => panic!("words"), } } @@ -342,11 +288,7 @@ mod tests { let marks = marks_of(r#"{"type":"Rect","width":20,"height":20,"rx":5}"#); let (points, ..) = line(&marks[0]); - assert!( - points - .iter() - .all(|at| at.x.hypot(at.y) < 10.0 * 2f64.sqrt() - 1.0) - ); + assert!(points.iter().all(|at| at.x.hypot(at.y) < 10.0 * 2f64.sqrt() - 1.0)); } #[test] @@ -389,13 +331,9 @@ mod tests { Mark::Words { .. } => panic!("words"), }; + assert!((width(r#"{"type":"Rect","strokeWidth":2,"scaleX":3,"scaleY":3}"#) - 6.0).abs() < 1e-9); assert!( - (width(r#"{"type":"Rect","strokeWidth":2,"scaleX":3,"scaleY":3}"#) - 6.0).abs() < 1e-9 - ); - assert!( - (width(r#"{"type":"Rect","strokeWidth":2,"scaleX":3,"strokeUniform":true}"#) - 2.0) - .abs() - < 1e-9 + (width(r#"{"type":"Rect","strokeWidth":2,"scaleX":3,"strokeUniform":true}"#) - 2.0).abs() < 1e-9 ); } @@ -428,13 +366,11 @@ mod tests { #[test] fn a_flip_and_a_skew_reach_the_plane() { - let flipped = marks_of( - r#"{"type":"Path","flipX":true,"left":0,"top":0,"path":[["M",0,0],["L",10,0]]}"#, - ); + let flipped = + marks_of(r#"{"type":"Path","flipX":true,"left":0,"top":0,"path":[["M",0,0],["L",10,0]]}"#); assert!(near(line(&flipped[0]).0[0], 5.0, 0.0)); - let skewed = - marks_of(r#"{"type":"Polygon","skewX":45,"points":[{"x":0,"y":0},{"x":0,"y":10}]}"#); + let skewed = marks_of(r#"{"type":"Polygon","skewX":45,"points":[{"x":0,"y":0},{"x":0,"y":10}]}"#); assert!(near(line(&skewed[0]).0[1], 5.0, 5.0)); } @@ -442,42 +378,24 @@ mod tests { fn a_path_of_a_lone_point_is_not_drawn_and_each_piece_is_its_own() { let pieces = |path: &str| { let marks = marks_of(&format!(r#"{{"type":"Path","path":[{path}]}}"#)); - marks - .iter() - .map(|mark| line(mark).0.len()) - .collect::>() + marks.iter().map(|mark| line(mark).0.len()).collect::>() }; assert!(pieces(r#"["M",0,0]"#).is_empty()); assert!(pieces(r#"["M",0,0],["Z"]"#).is_empty()); - assert_eq!( - pieces(r#"["M",0,0],["L",1,0],["M",5,5],["M",6,6],["L",7,7],["L",8,8]"#), - [2, 3] - ); - assert_eq!( - pieces(r#"["M",0,0],["L",1,0],["Z"],["L",9,9],["L",8,8]"#), - [2, 2] - ); + assert_eq!(pieces(r#"["M",0,0],["L",1,0],["M",5,5],["M",6,6],["L",7,7],["L",8,8]"#), [2, 3]); + assert_eq!(pieces(r#"["M",0,0],["L",1,0],["Z"],["L",9,9],["L",8,8]"#), [2, 2]); } /// Each curve starts where the one before ended, whatever it was. #[test] fn a_curve_starts_where_the_pen_was() { - for before in [ - r#"["M",10,0]"#, - r#"["M",0,0],["L",10,0]"#, - r#"["M",0,0],["Q",5,0,10,0]"#, - ] { - let marks = marks_of(&format!( - r#"{{"type":"Path","path":[{before},["Q",10,100,10,200]]}}"# - )); + for before in [r#"["M",10,0]"#, r#"["M",0,0],["L",10,0]"#, r#"["M",0,0],["Q",5,0,10,0]"#] { + let marks = marks_of(&format!(r#"{{"type":"Path","path":[{before},["Q",10,100,10,200]]}}"#)); let (points, ..) = line(&marks[0]); let x = points[points.len() - 1].x; let curve = &points[points.len() - usize::try_from(CURVE_STEPS).unwrap()..]; - assert!( - curve.iter().all(|at| (at.x - x).abs() < 1e-9), - "{before}: {curve:?}" - ); + assert!(curve.iter().all(|at| (at.x - x).abs() < 1e-9), "{before}: {curve:?}"); } } diff --git a/crates/drawing/src/picture.rs b/crates/drawing/src/picture.rs index 258bdb8ff..e65c5f835 100644 --- a/crates/drawing/src/picture.rs +++ b/crates/drawing/src/picture.rs @@ -64,24 +64,14 @@ pub fn pictures(drawing: &Drawing, palette: &Palette, fonts: &Fonts) -> Option

    Option> { +pub fn export(drawing: &Drawing, palette: &Palette, fonts: &Fonts, format: Format) -> Option> { match format { Format::Png => png(drawing, palette, fonts, PICTURE), Format::Svg => svg(drawing, palette, fonts).map(String::into_bytes), } } -fn png( - drawing: &Drawing, - palette: &Palette, - fonts: &Fonts, - (side, most): (f64, f64), -) -> Option> { +fn png(drawing: &Drawing, palette: &Palette, fonts: &Fonts, (side, most): (f64, f64)) -> Option> { let frame = frame(drawing)?; let options = usvg::Options { font_family: fonts.family.clone(), @@ -95,15 +85,11 @@ fn png( clippy::cast_sign_loss, reason = "positive, and a picture's side at most" )] - let (width, height) = ( - (frame.width * scale).ceil() as u32, - (frame.height * scale).ceil() as u32, - ); + let (width, height) = ((frame.width * scale).ceil() as u32, (frame.height * scale).ceil() as u32); let mut pixmap = Pixmap::new(width, height)?; let drawn = tree.size(); #[expect(clippy::cast_precision_loss, reason = "a picture's side")] - let transform = - Transform::from_scale(width as f32 / drawn.width(), height as f32 / drawn.height()); + let transform = Transform::from_scale(width as f32 / drawn.width(), height as f32 / drawn.height()); resvg::render(&tree, transform, &mut pixmap.as_mut()); pixmap.encode_png().ok() } @@ -144,11 +130,8 @@ pub fn svg(drawing: &Drawing, palette: &Palette, fonts: &Fonts) -> Option return, Kind::Group => { @@ -163,12 +146,8 @@ fn write_object(out: &mut String, object: &Object, palette: &Palette, fonts: &Fo Kind::Rect | Kind::Ellipse | Kind::Polygon | Kind::Path => {} } let shape = shape(object, drawn_at); - let _ = write!( - out, - r#"<{shape} transform="{}" {}/>"#, - transform(object, drawn_at), - paint(object, palette) - ); + let _ = + write!(out, r#"<{shape} transform="{}" {}/>"#, transform(object, drawn_at), paint(object, palette)); } /// The tag and geometry of a shape, around the plane's origin: what `left` and `top` place. @@ -187,11 +166,7 @@ fn shape(object: &Object, (scale_x, scale_y): (f64, f64)) -> String { number(radius * scale_y), ) } - Kind::Ellipse => format!( - r#"ellipse rx="{}" ry="{}""#, - number(width / 2.0), - number(height / 2.0) - ), + Kind::Ellipse => format!(r#"ellipse rx="{}" ry="{}""#, number(width / 2.0), number(height / 2.0)), Kind::Polygon => { let points = object.points(); let middle = points_box(&points).map(|bounds| bounds.centre()); @@ -206,10 +181,7 @@ fn shape(object: &Object, (scale_x, scale_y): (f64, f64)) -> String { .collect(); format!(r#"polygon points="{}""#, points.join(" ")) } - _ => format!( - r#"path d="{}""#, - path_data(&object.path(), (scale_x, scale_y)) - ), + _ => format!(r#"path d="{}""#, path_data(&object.path(), (scale_x, scale_y))), } } @@ -274,12 +246,7 @@ fn paint(object: &Object, palette: &Palette) -> String { fn write_text(out: &mut String, object: &Object, palette: &Palette, fonts: &Fonts) { let font_size = object.font_size(); - let lines = wrap( - object.text().unwrap_or_default(), - object.width(), - font_size, - fonts, - ); + let lines = wrap(object.text().unwrap_or_default(), object.width(), font_size, fonts); let step = line_step(font_size, object.line_height()); let left = -object.width() / 2.0; let top = -object.height() / 2.0 + first_baseline(font_size); @@ -293,13 +260,8 @@ fn write_text(out: &mut String, object: &Object, palette: &Palette, fonts: &Font ); let mut baseline = top; for line in lines { - let _ = write!( - out, - r#"{}"#, - number(left), - number(baseline), - escaped(&line) - ); + let _ = + write!(out, r#"{}"#, number(left), number(baseline), escaped(&line)); baseline += step; } out.push_str(""); diff --git a/crates/drawing/src/picture/tests.rs b/crates/drawing/src/picture/tests.rs index a56ae5e19..7ec7f1533 100644 --- a/crates/drawing/src/picture/tests.rs +++ b/crates/drawing/src/picture/tests.rs @@ -3,20 +3,12 @@ use crate::text::tests::fonts; fn palette() -> Palette { let each = |prefix: &str| Hue::ALL.map(|hue| format!("{prefix}-{}", hue.name())); - Palette { - stroke: each("stroke"), - fill: each("fill"), - paper: "#101010".to_owned(), - } + Palette { stroke: each("stroke"), fill: each("fill"), paper: "#101010".to_owned() } } fn colours() -> Palette { let each = |colour: &str| [colour; 6].map(str::to_owned); - Palette { - stroke: each("#e5e7eb"), - fill: each("rgba(96, 165, 250, 0.14)"), - paper: "#101010".to_owned(), - } + Palette { stroke: each("#e5e7eb"), fill: each("rgba(96, 165, 250, 0.14)"), paper: "#101010".to_owned() } } fn scene(objects: &str) -> Drawing { @@ -59,13 +51,9 @@ fn nothing_drawn_has_no_picture() { #[test] fn the_frame_is_what_is_drawn_with_room_on_its_paper() { - let svg = - svg_of(r#"{"type":"Rect","left":100,"top":50,"width":100,"height":50,"strokeWidth":0}"#); + let svg = svg_of(r#"{"type":"Rect","left":100,"top":50,"width":100,"height":50,"strokeWidth":0}"#); - assert!( - svg.contains(r#"viewBox="26 1 148 98" width="148" height="98""#), - "{svg}" - ); + assert!(svg.contains(r#"viewBox="26 1 148 98" width="148" height="98""#), "{svg}"); assert!(svg.contains(r##""##)); } @@ -77,14 +65,16 @@ fn each_shape_is_drawn_round_its_centre_in_its_hues_colours() { {"type":"Polygon","left":0,"top":0,"width":40,"height":20,"points":[{"x":20,"y":0},{"x":40,"y":10},{"x":20,"y":20},{"x":0,"y":10}]}"#, ); - assert!(svg.contains(r#", objects: &[Object]) { if objects.is_empty() && !fields.contains_key(OBJECTS) { return; } - let objects = objects - .iter() - .map(|object| Value::Object(object.fields())) - .collect(); + let objects = objects.iter().map(|object| Value::Object(object.fields())).collect(); fields.insert(OBJECTS.to_owned(), Value::Array(objects)); } @@ -170,10 +159,7 @@ impl Object { /// A new object of Fabric's `kind`, in `hue`, on nothing yet. pub(crate) fn make(kind: &str, id: String, hue: Hue) -> Self { - let mut object = Self { - fields: Map::new(), - children: Vec::new(), - }; + let mut object = Self { fields: Map::new(), children: Vec::new() }; object.put("type", kind); object.put("version", FABRIC); object.put("originX", "center"); @@ -299,10 +285,7 @@ impl Object { /// ⚠️ Fabric 7 places an object by its centre: `left` and `top` are the box's middle. pub fn centre(&self) -> Point { - Point { - x: self.number("left", 0.0), - y: self.number("top", 0.0), - } + Point { x: self.number("left", 0.0), y: self.number("top", 0.0) } } pub fn width(&self) -> f64 { @@ -391,15 +374,9 @@ impl Object { let stroke = self.stroke_width(); let (scale_x, scale_y) = (self.scale_x().abs(), self.scale_y().abs()); if self.stroke_uniform() { - ( - self.width() * scale_x + stroke, - self.height() * scale_y + stroke, - ) + (self.width() * scale_x + stroke, self.height() * scale_y + stroke) } else { - ( - (self.width() + stroke) * scale_x, - (self.height() + stroke) * scale_y, - ) + ((self.width() + stroke) * scale_x, (self.height() + stroke) * scale_y) } } @@ -410,17 +387,9 @@ impl Object { let (sin, cos) = self.angle().to_radians().sin_cos(); let corners = [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)].map(|(x, y)| { let (x, y) = (x * width / 2.0, y * height / 2.0); - Point { - x: centre.x + x * cos - y * sin, - y: centre.y + x * sin + y * cos, - } + Point { x: centre.x + x * cos - y * sin, y: centre.y + x * sin + y * cos } }); - points_box(&corners).unwrap_or(Box { - left: centre.x, - top: centre.y, - width: 0.0, - height: 0.0, - }) + points_box(&corners).unwrap_or(Box { left: centre.x, top: centre.y, width: 0.0, height: 0.0 }) } /// Whether a point falls on it: its whole box, as Fabric finds a target, not its ink. @@ -437,10 +406,7 @@ impl Object { } fn number(&self, name: &str, otherwise: f64) -> f64 { - self.fields - .get(name) - .and_then(Value::as_f64) - .unwrap_or(otherwise) + self.fields.get(name).and_then(Value::as_f64).unwrap_or(otherwise) } fn list(&self, name: &str, read: impl Fn(&Value) -> Option) -> Vec { @@ -459,21 +425,11 @@ fn stored(value: f64) -> Value { } fn point_of(value: &Value) -> Option { - Some(Point { - x: value.get("x")?.as_f64()?, - y: value.get("y")?.as_f64()?, - }) + Some(Point { x: value.get("x")?.as_f64()?, y: value.get("y")?.as_f64()? }) } impl Hue { - pub const ALL: [Self; 6] = [ - Self::Ink, - Self::Blue, - Self::Green, - Self::Amber, - Self::Red, - Self::Purple, - ]; + pub const ALL: [Self; 6] = [Self::Ink, Self::Blue, Self::Green, Self::Amber, Self::Red, Self::Purple]; pub fn name(self) -> &'static str { match self { @@ -488,10 +444,7 @@ impl Hue { /// A name no theme paints is ink, as an object with none. fn named(name: &str) -> Self { - Self::ALL - .into_iter() - .find(|hue| hue.name() == name) - .unwrap_or_default() + Self::ALL.into_iter().find(|hue| hue.name() == name).unwrap_or_default() } } @@ -514,12 +467,8 @@ impl PathCommand { fn read(value: &Value) -> Option { let parts = value.as_array()?; - let at = |index: usize| { - Some(Point { - x: parts.get(index)?.as_f64()?, - y: parts.get(index + 1)?.as_f64()?, - }) - }; + let at = + |index: usize| Some(Point { x: parts.get(index)?.as_f64()?, y: parts.get(index + 1)?.as_f64()? }); match parts.first()?.as_str()? { "M" => Some(Self::Move(at(1)?)), "L" => Some(Self::Line(at(1)?)), diff --git a/crates/drawing/src/scene/tests.rs b/crates/drawing/src/scene/tests.rs index 5143d5f7e..4134c9a04 100644 --- a/crates/drawing/src/scene/tests.rs +++ b/crates/drawing/src/scene/tests.rs @@ -59,11 +59,7 @@ fn a_body_with_no_scene_opens_as_a_new_drawing() { #[test] fn each_object_reads_as_its_kind_and_hue() { let drawing = drawn(); - let read: Vec<_> = drawing - .objects - .iter() - .map(|object| (object.kind(), object.hue())) - .collect(); + let read: Vec<_> = drawing.objects.iter().map(|object| (object.kind(), object.hue())).collect(); assert_eq!( read, @@ -111,19 +107,12 @@ fn an_object_is_placed_by_its_centre_with_fabrics_transform() { #[test] fn a_field_left_out_reads_as_fabrics_default() { let drawing = - Drawing::read(r#"{"scene":{"objects":[{"type":"Textbox","hue":"teal","ends":[1,2]}]}}"#) - .unwrap(); + Drawing::read(r#"{"scene":{"objects":[{"type":"Textbox","hue":"teal","ends":[1,2]}]}}"#).unwrap(); let object = &drawing.objects[0]; assert_eq!(object.centre(), at(0.0, 0.0)); assert_eq!( - [ - object.scale_x(), - object.scale_y(), - object.angle(), - object.stroke_width(), - object.font_size(), - ], + [object.scale_x(), object.scale_y(), object.angle(), object.stroke_width(), object.font_size(),], [1.0, 1.0, 0.0, 1.0, 40.0] ); assert_eq!(object.hue(), Hue::Ink); @@ -139,14 +128,8 @@ fn an_arrow_holds_its_ends_its_shapes_and_its_path() { assert_eq!(arrow.from(), Some("rect-1")); assert_eq!(arrow.to(), Some("ellipse-1")); - assert_eq!( - arrow.ends().map(|ends| ends[0]), - Some(240.000_000_000_000_03) - ); - assert_eq!( - arrow.path().first(), - Some(&PathCommand::Move(at(240.0, 90.1))) - ); + assert_eq!(arrow.ends().map(|ends| ends[0]), Some(240.000_000_000_000_03)); + assert_eq!(arrow.path().first(), Some(&PathCommand::Move(at(240.0, 90.1)))); assert_eq!(arrow.path().last(), Some(&PathCommand::Close)); } @@ -167,8 +150,7 @@ fn a_freehand_line_is_read_with_its_curves() { #[test] fn a_path_command_the_app_never_wrote_is_not_drawn_and_stays_stored() { - let body = - r#"{"scene":{"objects":[{"type":"Path","path":[["M",1,2],["C",1,2,3,4,5,6],["L",3]]}]}}"#; + let body = r#"{"scene":{"objects":[{"type":"Path","path":[["M",1,2],["C",1,2,3,4,5,6],["L",3]]}]}}"#; let drawing = Drawing::read(body).unwrap(); assert_eq!(drawing.objects[0].path(), [PathCommand::Move(at(1.0, 2.0))]); @@ -179,25 +161,10 @@ fn a_path_command_the_app_never_wrote_is_not_drawn_and_stays_stored() { fn a_diamond_keeps_its_corners_a_text_its_words_a_group_its_children() { let drawing = drawn(); - assert_eq!( - drawing.objects[2].points(), - [ - at(60.0, 0.0), - at(120.0, 40.0), - at(60.0, 80.0), - at(0.0, 40.0) - ] - ); - assert_eq!( - drawing.objects[5].text(), - Some("API gateway\nsits in front of « everything »") - ); + assert_eq!(drawing.objects[2].points(), [at(60.0, 0.0), at(120.0, 40.0), at(60.0, 80.0), at(0.0, 40.0)]); + assert_eq!(drawing.objects[5].text(), Some("API gateway\nsits in front of « everything »")); assert_eq!(drawing.objects[5].font_size(), 18.0); - let inside: Vec<_> = drawing.objects[6] - .children - .iter() - .map(Object::kind) - .collect(); + let inside: Vec<_> = drawing.objects[6].children.iter().map(Object::kind).collect(); assert_eq!(inside, [Kind::Rect, Kind::Textbox]); } @@ -215,18 +182,13 @@ fn an_object_taken_away_leaves_the_rest_as_stored() { drawing.objects.remove(0); - assert_eq!( - drawing.write(), - r#"{"version":1,"scene":{"objects":[{"id":"b"}],"background":"x"}}"# - ); + assert_eq!(drawing.write(), r#"{"version":1,"scene":{"objects":[{"id":"b"}],"background":"x"}}"#); } #[test] fn the_first_object_put_on_an_empty_scene_is_stored() { let mut drawing = Drawing::read(r#"{"scene":{}}"#).unwrap(); - drawing.objects = Drawing::read(r#"{"scene":{"objects":[{"id":"a"}]}}"#) - .unwrap() - .objects; + drawing.objects = Drawing::read(r#"{"scene":{"objects":[{"id":"a"}]}}"#).unwrap().objects; assert_eq!(drawing.write(), r#"{"scene":{"objects":[{"id":"a"}]}}"#); } @@ -297,10 +259,7 @@ fn a_drawing_covers_all_that_is_drawn() { fn a_new_drawing_is_empty_and_read_back() { let empty = Drawing::empty(); - assert_eq!( - empty.write(), - r#"{"version":1,"scene":{"version":"7.4.0"}}"# - ); + assert_eq!(empty.write(), r#"{"version":1,"scene":{"version":"7.4.0"}}"#); let read = Drawing::read(&empty.write()).unwrap(); assert_eq!(read.write(), empty.write()); } @@ -310,10 +269,7 @@ fn a_shape_let_go_is_null_and_its_point_goes_with_it() { let mut arrow = Object::make("Path", "a".to_owned(), Hue::Ink); arrow.set_bound("from", Some("b")); arrow.set_anchor("from", Some(Side::Left)); - assert_eq!( - (arrow.from(), arrow.anchor("from")), - (Some("b"), Some(Side::Left)) - ); + assert_eq!((arrow.from(), arrow.anchor("from")), (Some("b"), Some(Side::Left))); arrow.set_bound("from", None); assert_eq!((arrow.from(), arrow.anchor("from")), (None, None)); diff --git a/crates/drawing/src/text.rs b/crates/drawing/src/text.rs index ab1505d93..448cdffe2 100644 --- a/crates/drawing/src/text.rs +++ b/crates/drawing/src/text.rs @@ -36,10 +36,7 @@ impl Fonts { .map_or_else(String::new, |(name, _)| name.clone()); database.set_sans_serif_family(family.clone()); Self { - faces: files - .iter() - .filter_map(|file| FontRef::new(file).ok()) - .collect(), + faces: files.iter().filter_map(|file| FontRef::new(file).ok()).collect(), database: Arc::new(database), family, } @@ -54,9 +51,7 @@ impl Fonts { } fn width(&self, word: &str, font_size: f64) -> f64 { - word.chars() - .map(|character| self.advance(character) * font_size) - .sum() + word.chars().map(|character| self.advance(character) * font_size).sum() } } diff --git a/crates/drawing/src/text/tests.rs b/crates/drawing/src/text/tests.rs index ff243444a..6439e4de2 100644 --- a/crates/drawing/src/text/tests.rs +++ b/crates/drawing/src/text/tests.rs @@ -14,8 +14,7 @@ fn wrapped(text: &str, width: f64) -> Vec { } /// Where Fabric's lines, in a browser, kerned, break elsewhere than these. -const KERNED_ELSEWHERE: [&str; 1] = - ["The quick brown fox jumps over the lazy dog, twice over, then rests"]; +const KERNED_ELSEWHERE: [&str; 1] = ["The quick brown fox jumps over the lazy dog, twice over, then rests"]; #[test] fn the_lines_are_those_fabric_broke_in_a_browser() { @@ -42,10 +41,7 @@ fn the_lines_are_those_fabric_broke_in_a_browser() { #[test] fn a_word_is_never_broken_and_widens_the_box() { - assert_eq!( - wrapped("supercalifragilistic ok", 10.0), - ["supercalifragilistic", "ok"] - ); + assert_eq!(wrapped("supercalifragilistic ok", 10.0), ["supercalifragilistic", "ok"]); } #[test] diff --git a/crates/engine/benches/commands.rs b/crates/engine/benches/commands.rs index 264fd2427..034290ad4 100644 --- a/crates/engine/benches/commands.rs +++ b/crates/engine/benches/commands.rs @@ -77,10 +77,7 @@ fn whole_corpus_read(c: &mut Criterion) { // Narrowed in SQL to the 160 pinned notes: what a filtered query pays for its side tables. group.bench_function("query_notes, pinned only", |b| { - let pinned = NotesQuery { - filter: NoteFilter::Pinned, - ..query("") - }; + let pinned = NotesQuery { filter: NoteFilter::Pinned, ..query("") }; b.iter(|| black_box(run_query(&mut corpus, &pinned))); }); @@ -97,10 +94,7 @@ fn single_write(c: &mut Criterion) { let mut at = 0u32; b.iter(|| { at += 1; - let patch = NotePatch { - title: Some(format!("Retitled {at}")), - ..NotePatch::default() - }; + let patch = NotePatch { title: Some(format!("Retitled {at}")), ..NotePatch::default() }; black_box(store::update(&mut corpus.connection, &id, &patch, now()).expect("a write")); }); }); @@ -122,10 +116,7 @@ fn body_writes(c: &mut Criterion) { // A full history, so every save below also rotates the oldest body out. for kept in 0..=engine::notes::revision::KEEP { - let patch = NotePatch { - content: Some(format!("{body}\n-- {kept}")), - ..NotePatch::default() - }; + let patch = NotePatch { content: Some(format!("{body}\n-- {kept}")), ..NotePatch::default() }; store::update(&mut corpus.connection, &id, &patch, now()).expect("a write"); } @@ -133,10 +124,7 @@ fn body_writes(c: &mut Criterion) { let mut at = 0u32; b.iter(|| { at += 1; - let patch = NotePatch { - content: Some(format!("{body}\n-- saved {at}")), - ..NotePatch::default() - }; + let patch = NotePatch { content: Some(format!("{body}\n-- saved {at}")), ..NotePatch::default() }; black_box(store::update(&mut corpus.connection, &id, &patch, now()).expect("a write")); }); }); @@ -145,10 +133,7 @@ fn body_writes(c: &mut Criterion) { let mut pinned = false; b.iter(|| { pinned = !pinned; - let patch = NotePatch { - pinned: Some(pinned), - ..NotePatch::default() - }; + let patch = NotePatch { pinned: Some(pinned), ..NotePatch::default() }; black_box(store::update(&mut corpus.connection, &id, &patch, now()).expect("a write")); }); }); @@ -164,10 +149,7 @@ fn bulk(c: &mut Criterion) { group.bench_function("tag_notes", |b| { b.iter(|| { - black_box( - store::tag_many(&mut corpus.connection, &ids, &["bulk".to_string()]) - .expect("a batch"), - ); + black_box(store::tag_many(&mut corpus.connection, &ids, &["bulk".to_string()]).expect("a batch")); }); }); @@ -183,9 +165,7 @@ fn bulk(c: &mut Criterion) { group.bench_function("delete_notes then restore_notes", |b| { b.iter(|| { store::trash::trash_many(&mut corpus.connection, &ids, now()).expect("a trashing"); - black_box( - store::trash::restore_many(&mut corpus.connection, &ids).expect("a restoration"), - ); + black_box(store::trash::restore_many(&mut corpus.connection, &ids).expect("a restoration")); }); }); @@ -209,9 +189,7 @@ fn aggregation(c: &mut Criterion) { group.bench_function("list_global_placeholders", |b| { b.iter(|| { - black_box( - store::global_placeholder_values(&mut corpus.connection).expect("the globals"), - ); + black_box(store::global_placeholder_values(&mut corpus.connection).expect("the globals")); }); }); @@ -227,14 +205,9 @@ fn corpus_rewrite(c: &mut Criterion) { let mut at = 0u32; b.iter(|| { at += 1; - let (from, into) = if at.is_multiple_of(2) { - ("ops", "operations") - } else { - ("operations", "ops") - }; - black_box( - store::retag(&mut corpus.connection, &[from.to_string()], into).expect("a retag"), - ); + let (from, into) = + if at.is_multiple_of(2) { ("ops", "operations") } else { ("operations", "ops") }; + black_box(store::retag(&mut corpus.connection, &[from.to_string()], into).expect("a retag")); }); }); @@ -259,14 +232,8 @@ fn disk(c: &mut Criterion) { let notes = store::all(&mut corpus.connection, None).expect("the corpus"); let packed = bundle::collect(&mut corpus.connection, notes).expect("a bundle"); black_box( - file::write( - &target, - &packed, - &attachments, - corpus.connection.vault(), - None, - ) - .expect("a written file"), + file::write(&target, &packed, &attachments, corpus.connection.vault(), None) + .expect("a written file"), ); }); }); @@ -275,8 +242,7 @@ fn disk(c: &mut Criterion) { b.iter(|| { let (incoming, mut payload) = file::read(&target, None).expect("a readable file"); black_box( - bundle::merge(&mut corpus.connection, incoming, &mut payload, &attachments) - .expect("a merge"), + bundle::merge(&mut corpus.connection, incoming, &mut payload, &attachments).expect("a merge"), ); }); }); @@ -304,25 +270,19 @@ fn attachment(c: &mut Criterion) { created_at: now(), }; let (db, vault) = corpus.connection.split(); - sealed::write_sealed( - vault, - &directory.join(screenshot.stored_name()), - &vec![7u8; 256 * 1024], - ) - .expect("a sealed file"); + sealed::write_sealed(vault, &directory.join(screenshot.stored_name()), &vec![7u8; 256 * 1024]) + .expect("a sealed file"); attachments::store::create(db, vault, &screenshot).expect("a record"); group.bench_function("read_attachment, 256 kB", |b| { b.iter(|| { black_box( - attachments::files::read_plain(&mut corpus.connection, "a-screenshot") - .expect("the bytes"), + attachments::files::read_plain(&mut corpus.connection, "a-screenshot").expect("the bytes"), ) }); }); - let profile = - std::env::temp_dir().join(format!("devnotes-bench-profile-{}", uuid::Uuid::new_v4())); + let profile = std::env::temp_dir().join(format!("devnotes-bench-profile-{}", uuid::Uuid::new_v4())); std::fs::create_dir_all(&profile).expect("a writable temporary directory"); libraries::registry::open_directory_in(&profile).expect("a registry"); @@ -348,12 +308,8 @@ fn unlock(c: &mut Criterion) { group.bench_function("Vault::derive at the shipped cost", |b| { b.iter(|| { black_box( - Vault::derive( - black_box("a passphrase"), - b"0123456789abcdef", - Cost::default(), - ) - .expect("a key"), + Vault::derive(black_box("a passphrase"), b"0123456789abcdef", Cost::default()) + .expect("a key"), ) }); }); @@ -367,11 +323,9 @@ fn cookie_jar(c: &mut Criterion) { use engine::http::cookies::{self, Change, JarCookie}; let scratch = tempfile::tempdir().expect("a temporary directory"); - let mut library = engine::db::open( - &scratch.path().join("jar.sqlite3"), - engine::db::test_vault().expect("a key"), - ) - .expect("a library"); + let mut library = + engine::db::open(&scratch.path().join("jar.sqlite3"), engine::db::test_vault().expect("a key")) + .expect("a library"); let changes: Vec = (0..500) .map(|at| { Change::Set(JarCookie { diff --git a/crates/engine/benches/corpus.rs b/crates/engine/benches/corpus.rs index 9d71d0a5a..1e760976b 100644 --- a/crates/engine/benches/corpus.rs +++ b/crates/engine/benches/corpus.rs @@ -29,9 +29,7 @@ pub(crate) const NOTES: usize = 8000; /// Roughly 13 kB of body. const LINES_PER_NOTE: usize = 200; const SPACES: usize = 4; -const TAGS: &[&str] = &[ - "angular", "api", "ci", "db", "docker", "git", "ops", "rust", "sql", "ssh", -]; +const TAGS: &[&str] = &["angular", "api", "ci", "db", "docker", "git", "ops", "rust", "sql", "ssh"]; /// A database file of its own per group, erased with the guard. pub(crate) struct Corpus { @@ -82,23 +80,14 @@ fn draft(seed: usize, space_id: &str) -> NoteDraft { language: Language::Rs, content: if checklist { String::new() } else { body(seed) }, source: "Runbook".to_string(), - tags: vec![ - TAGS[seed % TAGS.len()].to_string(), - TAGS[(seed + 3) % TAGS.len()].to_string(), - ], + tags: vec![TAGS[seed % TAGS.len()].to_string(), TAGS[(seed + 3) % TAGS.len()].to_string()], pinned: seed.is_multiple_of(50), lifecycle: if seed.is_multiple_of(25) { - NoteLifecycle::Expires { - at: now() + TimeDelta::days(3), - } + NoteLifecycle::Expires { at: now() + TimeDelta::days(3) } } else { NoteLifecycle::Permanent }, - kind: if checklist { - NoteKind::Checklist - } else { - NoteKind::Snippet - }, + kind: if checklist { NoteKind::Checklist } else { NoteKind::Snippet }, priority: Priority::None, items: if checklist { (0..5u32) @@ -125,11 +114,7 @@ pub(crate) fn run_query(corpus: &mut Corpus, request: &NotesQuery) -> Vec Corpus { // The corpus is sealed like a real library, so the benchmarks measure what the // commands really pay, encryption included. - let mut connection = db::open( - &directory.join("bench.sqlite3"), - db::test_vault().expect("a key"), - ) - .expect("a fresh database"); + let mut connection = db::open(&directory.join("bench.sqlite3"), db::test_vault().expect("a key")) + .expect("a fresh database"); let space_ids: Vec = (0..SPACES) - .map(|at| { - spaces::create(&mut connection, &format!("Space {at}")) - .expect("a space") - .id - }) + .map(|at| spaces::create(&mut connection, &format!("Space {at}")).expect("a space").id) .collect(); let at = now(); let note_ids: Vec = (0..notes) .map(|seed| { let space_id = &space_ids[seed % SPACES]; - store::create(&mut connection, draft(seed, space_id), at) - .expect("a note") - .id + store::create(&mut connection, draft(seed, space_id), at).expect("a note").id }) .collect(); - Corpus { - connection, - space_ids, - note_ids, - _directory: TempDir(directory), - } + Corpus { connection, space_ids, note_ids, _directory: TempDir(directory) } } diff --git a/crates/engine/benches/corpus_size.rs b/crates/engine/benches/corpus_size.rs index a70f41796..ede273c5a 100644 --- a/crates/engine/benches/corpus_size.rs +++ b/crates/engine/benches/corpus_size.rs @@ -66,13 +66,9 @@ fn query_by_corpus_size(c: &mut Criterion) { // The same query stopped before the view is built: the gap between the two is // what the view costs, and what a LIMIT could not take away. - group.bench_with_input( - BenchmarkId::new(format!("{name}, read only"), size), - &size, - |b, _| { - b.iter(|| black_box(read_only(&mut corpus, &request))); - }, - ); + group.bench_with_input(BenchmarkId::new(format!("{name}, read only"), size), &size, |b, _| { + b.iter(|| black_box(read_only(&mut corpus, &request))); + }); } } diff --git a/crates/engine/benches/index.rs b/crates/engine/benches/index.rs index 8229dabaa..2142503bf 100644 --- a/crates/engine/benches/index.rs +++ b/crates/engine/benches/index.rs @@ -31,27 +31,16 @@ struct Bench { fn bench(size: Size) -> Bench { let mut corpus = build(size); let runtime = tokio::runtime::Runtime::new().unwrap(); - let paths = Paths { - profile: std::env::temp_dir(), - }; - let engine = Arc::new(Engine::new( - paths, - Arc::new(RecordingSink::default()), - runtime.handle().clone(), - )); + let paths = Paths { profile: std::env::temp_dir() }; + let engine = Arc::new(Engine::new(paths, Arc::new(RecordingSink::default()), runtime.handle().clone())); *engine.db().lock().unwrap() = corpus.library.take(); reference::attach(&engine, &corpus.note_ids); - Bench { - engine, - runtime, - corpus, - } + Bench { engine, runtime, corpus } } impl Bench { fn fill(&self) { - self.runtime - .block_on(engine::index::fill(Arc::clone(&self.engine))); + self.runtime.block_on(engine::index::fill(Arc::clone(&self.engine))); } } @@ -103,17 +92,11 @@ fn index_query(c: &mut Criterion) { let engine = &bench.engine; let mut group = c.benchmark_group(format!("index_query/{}", label(size))); group.sample_size(20); - for (name, search) in [ - ("unfiltered", ""), - ("search matching nothing", "zzzzzz"), - ("search folding accents", "etape"), - ] { + for (name, search) in + [("unfiltered", ""), ("search matching nothing", "zzzzzz"), ("search folding accents", "etape")] + { group.bench_function(name, |b| { - b.iter(|| { - black_box(run_here(engine, |e| { - query_notes(e, &query(search)).unwrap() - })) - }); + b.iter(|| black_box(run_here(engine, |e| query_notes(e, &query(search)).unwrap()))); }); } let space = bench.corpus.space_ids[0].clone(); @@ -145,10 +128,7 @@ fn index_refresh(c: &mut Criterion) { let mut n = 0_u32; b.iter(|| { n += 1; - let patch = NotePatch { - title: Some(format!("Retitrée {n}")), - ..NotePatch::default() - }; + let patch = NotePatch { title: Some(format!("Retitrée {n}")), ..NotePatch::default() }; black_box(run_here(engine, |e| update_note(e, &id, &patch).unwrap())) }); }); diff --git a/crates/engine/benches/reference.rs b/crates/engine/benches/reference.rs index d8162d08e..a7a631829 100644 --- a/crates/engine/benches/reference.rs +++ b/crates/engine/benches/reference.rs @@ -88,20 +88,13 @@ fn line(seed: usize) -> &'static str { } fn lines(seed: usize, count: usize) -> String { - (0..count) - .map(|n| line(seed + n)) - .collect::>() - .join("\n") + (0..count).map(|n| line(seed + n)).collect::>().join("\n") } fn markdown(seed: usize) -> String { let mut text = format!("# Procédure {seed}\n\n"); for section in 0..4 { - let _ = write!( - text, - "## Étape {section}\n\n{}\n\n", - lines(seed + section, 4) - ); + let _ = write!(text, "## Étape {section}\n\n{}\n\n", lines(seed + section, 4)); text.push_str("- vérifier\n- **déployer**\n- surveiller\n\n"); text.push_str("| hôte | rôle |\n| --- | --- |\n| db-1 | primaire |\n\n"); let _ = write!(text, "```sql\n{}\n```\n\n", lines(seed, 3)); @@ -169,17 +162,10 @@ fn note(n: usize, size: Size, space_id: &str, folder_id: Option<&str>) -> Note { space_id: space_id.to_string(), folder_id: folder_id.map(str::to_string), title: format!("Note {n} — étape de déploiement"), - language: if kind == NoteKind::Snippet { - LANGUAGES[n % LANGUAGES.len()] - } else { - Language::Txt - }, + language: if kind == NoteKind::Snippet { LANGUAGES[n % LANGUAGES.len()] } else { Language::Txt }, content, source: format!("API Gateway / Auth / {}", n % 50), - tags: vec![ - format!("tag-{}", n % TAGS), - format!("tag-{}", (n * 7) % TAGS), - ], + tags: vec![format!("tag-{}", n % TAGS), format!("tag-{}", (n * 7) % TAGS)], pinned: n.is_multiple_of(97), created_at: at, updated_at: at, @@ -196,30 +182,20 @@ fn uuid(n: usize) -> String { } pub(crate) fn build(size: Size) -> Reference { - let directory = - std::env::temp_dir().join(format!("devnotes-reference-{}", uuid::Uuid::new_v4())); + let directory = std::env::temp_dir().join(format!("devnotes-reference-{}", uuid::Uuid::new_v4())); std::fs::create_dir_all(&directory).unwrap(); let vault = engine::vault::file::create(&directory, "a passphrase", Cost::FOR_TESTS).unwrap(); let mut library = db::open(&directory.join("devnotes.sqlite3"), vault).unwrap(); let (space_ids, note_ids) = seed(&mut library, size); std::fs::create_dir_all(directory.join("attachments")).unwrap(); - Reference { - library: Some(library), - note_ids, - space_ids, - _directory: Directory(directory), - } + Reference { library: Some(library), note_ids, space_ids, _directory: Directory(directory) } } /// Everything but the attachments, into a library already open: the spaces, then the notes. pub(crate) fn seed(library: &mut Library, size: Size) -> (Vec, Vec) { let space_ids: Vec = (0..SPACES) - .map(|n| { - engine::spaces::store::create(library, &format!("Espace {n}")) - .unwrap() - .id - }) + .map(|n| engine::spaces::store::create(library, &format!("Espace {n}")).unwrap().id) .collect(); let folder_ids = folders(library, &space_ids); let note_ids = notes(library, size, &space_ids, &folder_ids); @@ -330,15 +306,10 @@ fn http(library: &mut Library) { }, }; let name = draft.name.clone(); - request_ids.push( - engine::http::store::create_request(library, &draft, &name, now()) - .unwrap() - .id, - ); + request_ids.push(engine::http::store::create_request(library, &draft, &name, now()).unwrap().id); } for n in 0..ENVIRONMENTS { - engine::http::environments::store::create(library, &format!("Environnement {n}"), now()) - .unwrap(); + engine::http::environments::store::create(library, &format!("Environnement {n}"), now()).unwrap(); } for n in 0..HISTORY { let summary = serde_json::from_value(serde_json::json!({ diff --git a/crates/engine/benches/reference_profile.rs b/crates/engine/benches/reference_profile.rs index 1b31eb68b..3bf7f5cef 100644 --- a/crates/engine/benches/reference_profile.rs +++ b/crates/engine/benches/reference_profile.rs @@ -31,11 +31,7 @@ fn main() { std::fs::create_dir_all(&profile).unwrap(); let runtime = tokio::runtime::Runtime::new().unwrap(); let paths = Paths { profile }; - let engine = Arc::new(Engine::new( - paths, - Arc::new(RecordingSink::default()), - runtime.handle().clone(), - )); + let engine = Arc::new(Engine::new(paths, Arc::new(RecordingSink::default()), runtime.handle().clone())); run_here(&engine, |e| create_vault(e, secret(PASSPHRASE.to_owned()))).unwrap(); let (_, note_ids) = run_here(&engine, |e| { let mut library = e.db().lock().unwrap(); diff --git a/crates/engine/build.rs b/crates/engine/build.rs index 9c350d6c4..639443b0e 100644 --- a/crates/engine/build.rs +++ b/crates/engine/build.rs @@ -13,8 +13,8 @@ fn export_metadata() { println!("cargo:rerun-if-changed=Cargo.toml"); let manifest_dir = env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set by cargo"); - let text = fs::read_to_string(Path::new(&manifest_dir).join("Cargo.toml")) - .expect("Cargo.toml is readable"); + let text = + fs::read_to_string(Path::new(&manifest_dir).join("Cargo.toml")).expect("Cargo.toml is readable"); let manifest: toml::Table = toml::from_str(&text).expect("Cargo.toml is valid TOML"); let metadata = manifest @@ -38,10 +38,7 @@ fn export_metadata() { let author = authors.split(';').next().unwrap_or_default(); println!("cargo:rustc-env=DEVNOTES_AUTHOR={author}"); - println!( - "cargo:rustc-env=DEVNOTES_RUST_VERSION={}", - pinned_toolchain(&manifest_dir) - ); + println!("cargo:rustc-env=DEVNOTES_RUST_VERSION={}", pinned_toolchain(&manifest_dir)); } /// Every page of `docs/content`, by language and name, for `docs.rs` to embed: a page added there @@ -59,11 +56,7 @@ fn list_the_documentation() { let path = file.expect("docs/content is readable").path(); if path.extension().is_some_and(|extension| extension == "md") { let id = path.file_stem().and_then(|stem| stem.to_str()); - pages.push(( - language, - id.expect("a page's name is text").to_owned(), - path, - )); + pages.push((language, id.expect("a page's name is text").to_owned(), path)); } } } @@ -72,8 +65,7 @@ fn list_the_documentation() { let mut out = String::from("const SOURCES: &[(&str, &str, &str)] = &[\n"); for (language, id, path) in pages { let path = path.to_str().expect("the repository is at a path of text"); - writeln!(out, " ({language:?}, {id:?}, include_str!({path:?})),") - .expect("a string grows"); + writeln!(out, " ({language:?}, {id:?}, include_str!({path:?})),").expect("a string grows"); } out.push_str("];\n"); let target = Path::new(&env::var("OUT_DIR").expect("cargo sets OUT_DIR")).join("docs.rs"); diff --git a/crates/engine/src/attachments.rs b/crates/engine/src/attachments.rs index bee45db98..b33e99d29 100644 --- a/crates/engine/src/attachments.rs +++ b/crates/engine/src/attachments.rs @@ -34,10 +34,7 @@ pub async fn attach_file( crate::db::run(engine, move |engine| { engine.write(|db| { let answer = store_new(note_id, file_name, &bytes, db)?; - let changed = Changed { - attachments: true, - ..Changed::default() - }; + let changed = Changed { attachments: true, ..Changed::default() }; Ok((answer, changed)) }) }) @@ -97,10 +94,7 @@ pub fn attach_image( let png = model::encode_png(width, height, rgba)?; model::validate_size(png.len() as u64, &model::png_name(file_name))?; let answer = store_new(note_id, model::png_name(file_name), &png, db)?; - let changed = Changed { - attachments: true, - ..Changed::default() - }; + let changed = Changed { attachments: true, ..Changed::default() }; Ok((answer, changed)) }) } @@ -108,10 +102,7 @@ pub fn attach_image( pub fn delete_attachment(engine: &Engine, id: &str) -> Result<(), AppError> { engine.write(|db| { delete(db, id)?; - let changed = Changed { - attachments: true, - ..Changed::default() - }; + let changed = Changed { attachments: true, ..Changed::default() }; Ok(((), changed)) }) } diff --git a/crates/engine/src/attachments/files.rs b/crates/engine/src/attachments/files.rs index 54e14ad23..7d4b1f12a 100644 --- a/crates/engine/src/attachments/files.rs +++ b/crates/engine/src/attachments/files.rs @@ -66,8 +66,8 @@ pub(crate) fn store_new( let destination = directory.join(attachment.stored_name()); let (db, vault) = connection.split(); - let stored = sealed::write_sealed(vault, &destination, bytes) - .and_then(|_| store::create(db, vault, &attachment)); + let stored = + sealed::write_sealed(vault, &destination, bytes).and_then(|_| store::create(db, vault, &attachment)); if stored.is_err() { remove_files(&directory, &[attachment.stored_name()]); } @@ -114,12 +114,9 @@ pub(crate) fn write_plain(path: &str, bytes: &[u8]) -> Result<(), StorageError> std::fs::write(path, bytes).context(path) } -fn locate( - library: &mut Library, - id: &str, -) -> Result<(Attachment, PathBuf, Arc), StorageError> { - let attachment = store::find(library, id)? - .ok_or_else(|| StorageError::AttachmentNotFound(id.to_string()))?; +fn locate(library: &mut Library, id: &str) -> Result<(Attachment, PathBuf, Arc), StorageError> { + let attachment = + store::find(library, id)?.ok_or_else(|| StorageError::AttachmentNotFound(id.to_string()))?; let path = directory(library).join(attachment.stored_name()); Ok((attachment, path, library.shared_vault())) @@ -129,10 +126,7 @@ fn locate( pub fn sweep_orphan_files(db: &Db) -> Result { let (directory, known) = { let mut connection = lock(db)?; - ( - directory(&connection), - store::all_stored_names(&mut connection)?, - ) + (directory(&connection), store::all_stored_names(&mut connection)?) }; let entries = std::fs::read_dir(&directory).context("attachments sweep")?; @@ -192,10 +186,7 @@ pub(crate) mod tests { fn attachments_live_in_the_library_s_own_directory() { let (scratch, db, _) = a_library_with_a_note(); - assert_eq!( - attachments_of(&db), - scratch.path().join(crate::layout::ATTACHMENTS) - ); + assert_eq!(attachments_of(&db), scratch.path().join(crate::layout::ATTACHMENTS)); } /// Sealed like the rows beside it: the plain bytes are nowhere on disk. @@ -208,10 +199,7 @@ pub(crate) mod tests { let on_disk = std::fs::read(attachments_of(&db).join(stored.stored_name())).unwrap(); assert!(!on_disk.windows(bytes.len()).any(|window| window == bytes)); - assert_eq!( - (stored.byte_size, stored.mime_type.as_str()), - (18, "image/png") - ); + assert_eq!((stored.byte_size, stored.mime_type.as_str()), (18, "image/png")); assert_eq!(listed(&db, ¬e_id)[0].id, stored.id); } @@ -220,12 +208,7 @@ pub(crate) mod tests { fn an_attachment_of_a_note_not_there_leaves_no_file() { let (_scratch, db, _) = a_library_with_a_note(); - let refused = store_new( - "missing".to_string(), - "capture.png".to_string(), - b"png", - &db, - ); + let refused = store_new("missing".to_string(), "capture.png".to_string(), b"png", &db); assert!(matches!(refused, Err(StorageError::NoteNotFound(id)) if id == "missing")); assert_eq!(std::fs::read_dir(attachments_of(&db)).unwrap().count(), 0); @@ -239,15 +222,9 @@ pub(crate) mod tests { let (record, bytes) = read_plain(&mut lock(&db).unwrap(), &stored.id).unwrap(); let (_, outside) = read_outside_lock(&db, &stored.id).unwrap(); - assert_eq!( - (record.file_name.as_str(), bytes.as_slice()), - ("notes.txt", &b"plain"[..]) - ); + assert_eq!((record.file_name.as_str(), bytes.as_slice()), ("notes.txt", &b"plain"[..])); assert_eq!(outside, b"plain"); - assert!( - db.try_lock().is_ok(), - "the lock is free once the bytes are in hand" - ); + assert!(db.try_lock().is_ok(), "the lock is free once the bytes are in hand"); } /// Opening a file nothing refers to would read outside what the library knows. @@ -257,10 +234,7 @@ pub(crate) mod tests { std::fs::write(attachments_of(&db).join("stray"), b"stray").unwrap(); for id in ["stray", "missing"] { - assert!(matches!( - read_outside_lock(&db, id), - Err(StorageError::AttachmentNotFound(_)) - )); + assert!(matches!(read_outside_lock(&db, id), Err(StorageError::AttachmentNotFound(_)))); } } @@ -276,10 +250,7 @@ pub(crate) mod tests { assert_eq!(read.len() as u64, model::MAX_BYTES + 1); let missing = scratch.path().join("missing.bin"); - assert!(matches!( - read_within_limit(&missing.to_string_lossy()), - Err(StorageError::File(_)) - )); + assert!(matches!(read_within_limit(&missing.to_string_lossy()), Err(StorageError::File(_)))); } /// Two copies of one name do not overwrite each other. diff --git a/crates/engine/src/attachments/model.rs b/crates/engine/src/attachments/model.rs index cd7a875d3..635af260c 100644 --- a/crates/engine/src/attachments/model.rs +++ b/crates/engine/src/attachments/model.rs @@ -54,21 +54,13 @@ fn copy_name(id: &str, file_name: &str) -> String { } }) .collect(); - let mut name = replaced - .trim_end_matches(['.', ' ']) - .trim_start() - .to_string(); + let mut name = replaced.trim_end_matches(['.', ' ']).trim_start().to_string(); if name.chars().count() > COPY_NAME_CHARS { let extension = extension_of(&name).map(|extension| format!(".{extension}")); let kept = COPY_NAME_CHARS - extension.as_ref().map_or(0, String::len); name = name.chars().take(kept).collect::() + extension.as_deref().unwrap_or(""); } - let stem = name - .split('.') - .next() - .unwrap_or_default() - .trim_end() - .to_ascii_uppercase(); + let stem = name.split('.').next().unwrap_or_default().trim_end().to_ascii_uppercase(); let device = matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL") || ((stem.starts_with("COM") || stem.starts_with("LPT")) && stem.len() == 4 @@ -100,10 +92,7 @@ fn contained(id: &str) -> String { /// Lowercase and alphanumeric: separators, `..` or colons would escape the directory. fn extension_of(file_name: &str) -> Option { let candidate = file_name.rsplit_once('.')?.1; - if candidate.is_empty() - || candidate.len() > 8 - || !candidate.chars().all(|c| c.is_ascii_alphanumeric()) - { + if candidate.is_empty() || candidate.len() > 8 || !candidate.chars().all(|c| c.is_ascii_alphanumeric()) { return None; } @@ -141,12 +130,7 @@ pub fn mime_of(file_name: &str) -> String { /// Stripped of any path: an import must not show `../../secrets/key.pem` as a note's own. pub fn display_name(path: &str) -> Result { - let trimmed = path - .rsplit(['/', '\\']) - .next() - .unwrap_or_default() - .trim() - .to_string(); + let trimmed = path.rsplit(['/', '\\']).next().unwrap_or_default().trim().to_string(); if trimmed.is_empty() || trimmed == "." || trimmed == ".." { return Err(ValidationError::new("fileName", "unreadable file name")); @@ -159,24 +143,14 @@ pub fn display_name(path: &str) -> Result { /// `mime_of` answers `application/octet-stream` and skips the preview. pub fn png_name(base: &str) -> String { let trimmed = base.trim(); - let stem = if trimmed.is_empty() { - "capture" - } else { - trimmed - }; + let stem = if trimmed.is_empty() { "capture" } else { trimmed }; - if stem.to_ascii_lowercase().ends_with(".png") { - stem.to_string() - } else { - format!("{stem}.png") - } + if stem.to_ascii_lowercase().ends_with(".png") { stem.to_string() } else { format!("{stem}.png") } } /// Encodes raw RGBA — what the system clipboard hands over — into PNG. pub fn encode_png(width: u32, height: u32, rgba: &[u8]) -> Result, StorageError> { - let expected = (width as usize) - .saturating_mul(height as usize) - .saturating_mul(4); + let expected = (width as usize).saturating_mul(height as usize).saturating_mul(4); if width == 0 || height == 0 || rgba.len() < expected { return Err(StorageError::File(format!( "clipboard image of {width}×{height} carries {} bytes, {expected} expected", @@ -190,9 +164,7 @@ pub fn encode_png(width: u32, height: u32, rgba: &[u8]) -> Result, Stora encoder.set_color(png::ColorType::Rgba); encoder.set_depth(png::BitDepth::Eight); let mut writer = encoder.write_header().context("png header")?; - writer - .write_image_data(&rgba[..expected]) - .context("png data")?; + writer.write_image_data(&rgba[..expected]).context("png data")?; } Ok(png) @@ -205,10 +177,7 @@ const _: () = assert!(MAX_BYTES == MAX_MEGABYTES as u64 * 1024 * 1024); pub fn validate_size(byte_size: u64, name: &str) -> Result { if byte_size > MAX_BYTES { - return Err(StorageError::TooLarge { - name: name.to_string(), - limit_mb: MAX_MEGABYTES, - }); + return Err(StorageError::TooLarge { name: name.to_string(), limit_mb: MAX_MEGABYTES }); } Ok(saturating_u32(byte_size)) @@ -235,11 +204,7 @@ mod tests { ("a-1", "Capture.PNG", "a-1.png"), ("a-1", "archive.tar.gz", "a-1.gz"), ("a-1", "notes", "a-1"), - ( - "3f2504e0-4f89-41d3-9a0c-0305e82c3301", - "x.png", - "3f2504e0-4f89-41d3-9a0c-0305e82c3301.png", - ), + ("3f2504e0-4f89-41d3-9a0c-0305e82c3301", "x.png", "3f2504e0-4f89-41d3-9a0c-0305e82c3301.png"), ]; for (id, file_name, stored) in cases { @@ -324,11 +289,7 @@ mod tests { assert_eq!(display_name(path), Ok(shown.to_string()), "{path}"); } for unreadable in ["", "folder/", ".", "..", " "] { - assert_eq!( - display_name(unreadable).unwrap_err().field, - "fileName", - "{unreadable:?}" - ); + assert_eq!(display_name(unreadable).unwrap_err().field, "fileName", "{unreadable:?}"); } } @@ -372,10 +333,7 @@ mod tests { #[test] fn a_file_is_attached_up_to_ten_megabytes_and_refused_past_them() { - assert_eq!( - validate_size(MAX_BYTES, "big.bin").unwrap(), - 10 * 1024 * 1024 - ); + assert_eq!(validate_size(MAX_BYTES, "big.bin").unwrap(), 10 * 1024 * 1024); assert!(matches!( validate_size(MAX_BYTES + 1, "big.bin"), Err(StorageError::TooLarge { name, limit_mb: 10 }) if name == "big.bin" @@ -385,14 +343,8 @@ mod tests { /// Two copies of one name must not meet: each sits in a folder of its own. #[test] fn an_opened_copy_sits_in_a_folder_of_its_own_under_its_own_name() { - assert_eq!( - attachment("a-1", "Rapport.pdf").opened_copy(), - PathBuf::from("a-1").join("Rapport.pdf") - ); - assert_eq!( - attachment("../a-1", "x.pdf").opened_copy(), - PathBuf::from("a-1").join("x.pdf") - ); + assert_eq!(attachment("a-1", "Rapport.pdf").opened_copy(), PathBuf::from("a-1").join("Rapport.pdf")); + assert_eq!(attachment("../a-1", "x.pdf").opened_copy(), PathBuf::from("a-1").join("x.pdf")); } /// What Windows forbids is replaced; a device name or nothing left falls back on the diff --git a/crates/engine/src/attachments/sealed.rs b/crates/engine/src/attachments/sealed.rs index b3b149241..bb7619857 100644 --- a/crates/engine/src/attachments/sealed.rs +++ b/crates/engine/src/attachments/sealed.rs @@ -38,10 +38,7 @@ pub fn sweep_plaintext(paths: &Paths) { if let Err(error) = std::fs::remove_dir_all(&directory) && error.kind() != std::io::ErrorKind::NotFound { - log::warn!( - "Decrypted copies not swept from {}: {error}", - directory.display() - ); + log::warn!("Decrypted copies not swept from {}: {error}", directory.display()); } } @@ -58,14 +55,9 @@ mod tests { #[test] fn the_decrypted_copies_live_under_the_profile_and_go_in_one_sweep() { let profile = tempfile::tempdir().unwrap(); - let paths = Paths { - profile: profile.path().to_path_buf(), - }; + let paths = Paths { profile: profile.path().to_path_buf() }; let directory = plaintext_directory(&paths); - assert_eq!( - directory, - profile.path().join(crate::layout::PLAINTEXT_COPIES) - ); + assert_eq!(directory, profile.path().join(crate::layout::PLAINTEXT_COPIES)); sweep_plaintext(&paths); std::fs::create_dir_all(&directory).unwrap(); @@ -121,8 +113,7 @@ mod tests { let target = directory.join("capture.png"); write_sealed(&vault(), &target, b"bytes").unwrap(); - let other = - Vault::derive("another passphrase", b"0123456789abcdef", Cost::FOR_TESTS).unwrap(); + let other = Vault::derive("another passphrase", b"0123456789abcdef", Cost::FOR_TESTS).unwrap(); assert!(read_sealed(&other, &target).is_err()); } diff --git a/crates/engine/src/attachments/store.rs b/crates/engine/src/attachments/store.rs index 5de5a2d49..1ecfee619 100644 --- a/crates/engine/src/attachments/store.rs +++ b/crates/engine/src/attachments/store.rs @@ -26,10 +26,8 @@ struct AttachmentRow { /// `{id}.{extension}`, so the type is already public. Sealing it would be theatre. impl AttachmentRow { fn open(row: Self, vault: &Vault) -> Result { - let created_at = iso8601::parse(&row.created_at).map_err(|_| StorageError::CorruptRow { - id: row.id.clone(), - field: "createdAt", - })?; + let created_at = iso8601::parse(&row.created_at) + .map_err(|_| StorageError::CorruptRow { id: row.id.clone(), field: "createdAt" })?; Ok(Attachment { byte_size: saturating_u32(row.byte_size), @@ -116,10 +114,7 @@ pub fn delete(connection: &mut SqliteConnection, id: &str) -> Result<(), Storage /// The records an export carries. The bytes are not here: the caller reads them from the /// attachments directory by [`model::stored_name`]. -pub fn for_notes( - connection: &mut Library, - note_ids: &[String], -) -> Result, StorageError> { +pub fn for_notes(connection: &mut Library, note_ids: &[String]) -> Result, StorageError> { if note_ids.is_empty() { return Ok(Vec::new()); } @@ -137,10 +132,7 @@ pub fn for_notes( } /// ⚠️ Collected before a purge: the cascade takes the records, never the files. -pub fn stored_names_of( - connection: &mut Library, - note_ids: &[String], -) -> Result, StorageError> { +pub fn stored_names_of(connection: &mut Library, note_ids: &[String]) -> Result, StorageError> { if note_ids.is_empty() { return Ok(Vec::new()); } @@ -211,12 +203,7 @@ mod tests { .id } - fn attachment( - id: &str, - note_id: &str, - file_name: &str, - created_at: DateTime, - ) -> Attachment { + fn attachment(id: &str, note_id: &str, file_name: &str, created_at: DateTime) -> Attachment { Attachment { id: id.to_string(), note_id: note_id.to_string(), @@ -233,10 +220,7 @@ mod tests { } fn ids(attachments: &[Attachment]) -> Vec<&str> { - attachments - .iter() - .map(|attachment| attachment.id.as_str()) - .collect() + attachments.iter().map(|attachment| attachment.id.as_str()).collect() } /// The foreign key would refuse it too, in words the screen cannot translate. @@ -250,10 +234,7 @@ mod tests { for note_id in ["missing", trashed.as_str()] { let refused = create(db, vault, &attachment("a-1", note_id, "x.png", Utc::now())); - assert!( - matches!(refused, Err(StorageError::NoteNotFound(id)) if id == note_id), - "{note_id}" - ); + assert!(matches!(refused, Err(StorageError::NoteNotFound(id)) if id == note_id), "{note_id}"); } } @@ -262,18 +243,9 @@ mod tests { let mut library = open_in_memory().unwrap(); let note = note_in(&mut library); let other = note_in(&mut library); - record( - &mut library, - &attachment("late", ¬e, "b.png", at("2026-07-25T11:00:00.000Z")), - ); - record( - &mut library, - &attachment("early", ¬e, "a.png", at("2026-07-25T10:00:00.000Z")), - ); - record( - &mut library, - &attachment("else", &other, "c.png", at("2026-07-25T10:00:00.000Z")), - ); + record(&mut library, &attachment("late", ¬e, "b.png", at("2026-07-25T11:00:00.000Z"))); + record(&mut library, &attachment("early", ¬e, "a.png", at("2026-07-25T10:00:00.000Z"))); + record(&mut library, &attachment("else", &other, "c.png", at("2026-07-25T10:00:00.000Z"))); assert_eq!(ids(&list(&mut library, ¬e).unwrap()), ["early", "late"]); } @@ -283,12 +255,7 @@ mod tests { fn a_record_s_name_is_sealed_and_read_back_whole() { let mut library = open_in_memory().unwrap(); let note = note_in(&mut library); - let made = attachment( - "a-1", - ¬e, - "secret plan.png", - at("2026-07-25T10:00:00.000Z"), - ); + let made = attachment("a-1", ¬e, "secret plan.png", at("2026-07-25T10:00:00.000Z")); record(&mut library, &made); let (name, mime): (String, String) = attachments::table @@ -344,18 +311,9 @@ mod tests { let first = note_in(&mut library); let second = note_in(&mut library); let left = note_in(&mut library); - record( - &mut library, - &attachment("a-1", &first, "Shot.PNG", at("2026-07-25T10:00:00.000Z")), - ); - record( - &mut library, - &attachment("a-2", &second, "notes", at("2026-07-25T11:00:00.000Z")), - ); - record( - &mut library, - &attachment("a-3", &left, "x.pdf", at("2026-07-25T12:00:00.000Z")), - ); + record(&mut library, &attachment("a-1", &first, "Shot.PNG", at("2026-07-25T10:00:00.000Z"))); + record(&mut library, &attachment("a-2", &second, "notes", at("2026-07-25T11:00:00.000Z"))); + record(&mut library, &attachment("a-3", &left, "x.pdf", at("2026-07-25T12:00:00.000Z"))); let chosen = [first, second]; let records = for_notes(&mut library, &chosen).unwrap(); diff --git a/crates/engine/src/backup.rs b/crates/engine/src/backup.rs index 818950ba5..0ea99f9f1 100644 --- a/crates/engine/src/backup.rs +++ b/crates/engine/src/backup.rs @@ -85,11 +85,7 @@ pub fn take_restored_aside(engine: &Engine) -> Option { fn restore(db: &Db, id: &str, now: DateTime) -> Result { let mut open = db.lock().map_err(|_| StorageError::Unavailable)?; - let directory = open - .as_ref() - .ok_or(StorageError::Locked)? - .directory() - .to_path_buf(); + let directory = open.as_ref().ok_or(StorageError::Locked)?.directory().to_path_buf(); // Dropped before a single file moves, and the lock held for the whole swap. *open = None; diff --git a/crates/engine/src/backup/copies.rs b/crates/engine/src/backup/copies.rs index f4db3eb9b..4283e0729 100644 --- a/crates/engine/src/backup/copies.rs +++ b/crates/engine/src/backup/copies.rs @@ -154,11 +154,7 @@ pub(crate) fn list(library: &Path) -> Vec { /// Moved aside into `replaced/`, never deleted, and `vault.json` with it: the copy brings its /// own, and a database and a key from two wrappings open nothing. `attachments/` goes too, and /// the copy's is linked back: an attachment added since is kept aside, not lost. -pub(crate) fn replace( - library: &Path, - id: &str, - now: DateTime, -) -> Result { +pub(crate) fn replace(library: &Path, id: &str, now: DateTime) -> Result { // ⚠️ Matched against the listing, never joined: the id comes from the front end, and // `../2026-01-01_00-00-00` joins to a path outside `backups/` that still parses as a stamp. let copy = existing(&library.join(BACKUPS)) @@ -213,11 +209,7 @@ fn copy_back(copy: &Path, library: &Path) -> Result<(), String> { fn put_back(moved: &[(PathBuf, PathBuf)], aside: &Path) { for (from, to) in moved { - let _ = if from.is_dir() { - std::fs::remove_dir_all(from) - } else { - std::fs::remove_file(from) - }; + let _ = if from.is_dir() { std::fs::remove_dir_all(from) } else { std::fs::remove_file(from) }; let _ = std::fs::rename(to, from); } let _ = std::fs::remove_dir_all(aside); @@ -250,10 +242,7 @@ pub(crate) fn rewrap(library: &Path, vault: &Vault, passphrase: &str, cost: Cost match crate::vault::file::write_wrapped(&path, vault, passphrase, cost) { Ok(()) => tally.done += 1, Err(error) => { - log::warn!( - "{}: still opens with the old passphrase: {error}", - path.display() - ); + log::warn!("{}: still opens with the old passphrase: {error}", path.display()); tally.left += 1; } } @@ -298,9 +287,7 @@ mod tests { let vault = file::create(directory, PHRASE, Cost::FOR_TESTS).unwrap(); let mut connection = db::open(&directory.join(layout::DATABASE), vault).unwrap(); let space = spaces::create(&mut connection, "Work").unwrap().id; - let note = notes::create(&mut connection, draft(&space, "Kept"), at(0)) - .unwrap() - .id; + let note = notes::create(&mut connection, draft(&space, "Kept"), at(0)).unwrap().id; std::fs::create_dir_all(directory.join(ATTACHMENTS)).unwrap(); std::fs::write(directory.join(ATTACHMENTS).join("a-1.png"), b"png").unwrap(); @@ -315,10 +302,7 @@ mod tests { } fn ids(directory: &Path) -> Vec { - list(directory) - .into_iter() - .map(|backup| backup.id) - .collect() + list(directory).into_iter().map(|backup| backup.id).collect() } /// A copy that cannot be opened is no backup: its key file travels, its attachments too. @@ -327,19 +311,11 @@ mod tests { let scratch = tempfile::tempdir().unwrap(); let (mut connection, _) = library(scratch.path()); - let target = rotate(scratch.path(), &mut connection, at(0)) - .unwrap() - .unwrap(); + let target = rotate(scratch.path(), &mut connection, at(0)).unwrap().unwrap(); - assert_eq!( - target, - scratch.path().join(BACKUPS).join(layout::stamp(at(0))) - ); + assert_eq!(target, scratch.path().join(BACKUPS).join(layout::stamp(at(0)))); assert_eq!(titles_in(&target, PHRASE), ["Kept"]); - assert_eq!( - std::fs::read(target.join(ATTACHMENTS).join("a-1.png")).unwrap(), - b"png" - ); + assert_eq!(std::fs::read(target.join(ATTACHMENTS).join("a-1.png")).unwrap(), b"png"); } /// One file under two names: the copy costs no disk, and a purge in the library only @@ -350,16 +326,11 @@ mod tests { let scratch = tempfile::tempdir().unwrap(); let (mut connection, _) = library(scratch.path()); - let target = rotate(scratch.path(), &mut connection, at(0)) - .unwrap() - .unwrap(); + let target = rotate(scratch.path(), &mut connection, at(0)).unwrap().unwrap(); let live = scratch.path().join(ATTACHMENTS).join("a-1.png"); let copied = target.join(ATTACHMENTS).join("a-1.png"); - let mut through_the_library = std::fs::OpenOptions::new() - .append(true) - .open(&live) - .unwrap(); + let mut through_the_library = std::fs::OpenOptions::new().append(true).open(&live).unwrap(); through_the_library.write_all(b", once").unwrap(); drop(through_the_library); std::fs::remove_file(&live).unwrap(); @@ -374,9 +345,7 @@ mod tests { let (mut connection, _) = library(scratch.path()); std::fs::create_dir_all(scratch.path().join(ATTACHMENTS).join("stray")).unwrap(); - let target = rotate(scratch.path(), &mut connection, at(0)) - .unwrap() - .unwrap(); + let target = rotate(scratch.path(), &mut connection, at(0)).unwrap().unwrap(); assert!(target.join(ATTACHMENTS).join("a-1.png").is_file()); assert!(!target.join(ATTACHMENTS).join("stray").exists()); @@ -415,25 +384,13 @@ mod tests { } std::fs::write(directory.join(KEY_FILE), b"half copied").unwrap(); std::fs::create_dir_all(directory.join(ATTACHMENTS)).unwrap(); - std::fs::write( - directory.join(ATTACHMENTS).join("from-the-copy.png"), - b"half", - ) - .unwrap(); + std::fs::write(directory.join(ATTACHMENTS).join("from-the-copy.png"), b"half").unwrap(); put_back(&moved, &aside); - assert_eq!( - std::fs::read(directory.join(KEY_FILE)).unwrap(), - b"live key" - ); + assert_eq!(std::fs::read(directory.join(KEY_FILE)).unwrap(), b"live key"); assert!(directory.join(ATTACHMENTS).join("a-1.png").is_file()); - assert!( - !directory - .join(ATTACHMENTS) - .join("from-the-copy.png") - .exists() - ); + assert!(!directory.join(ATTACHMENTS).join("from-the-copy.png").exists()); assert!(!aside.exists()); } @@ -450,10 +407,7 @@ mod tests { let retried = rotate(scratch.path(), &mut connection, at(1)).unwrap(); assert!(matches!(failed, Err(StorageError::File(_)))); - assert_eq!( - retried, - Some(scratch.path().join(BACKUPS).join(layout::stamp(at(1)))) - ); + assert_eq!(retried, Some(scratch.path().join(BACKUPS).join(layout::stamp(at(1))))); assert_eq!(list(scratch.path()).len(), 1); } @@ -482,10 +436,7 @@ mod tests { rotate(scratch.path(), &mut connection, at(24 * day)).unwrap(); } - let kept: Vec = [4, 3, 2] - .iter() - .map(|day| layout::stamp(at(24 * day))) - .collect(); + let kept: Vec = [4, 3, 2].iter().map(|day| layout::stamp(at(24 * day))).collect(); assert_eq!(ids(scratch.path()), kept); } @@ -495,30 +446,19 @@ mod tests { fn a_copy_is_listed_with_its_size_and_whether_it_opens() { let scratch = tempfile::tempdir().unwrap(); let (mut connection, _) = library(scratch.path()); - let whole = rotate(scratch.path(), &mut connection, at(0)) - .unwrap() - .unwrap(); - let keyless = rotate(scratch.path(), &mut connection, at(48)) - .unwrap() - .unwrap(); + let whole = rotate(scratch.path(), &mut connection, at(0)).unwrap().unwrap(); + let keyless = rotate(scratch.path(), &mut connection, at(48)).unwrap().unwrap(); std::fs::remove_file(keyless.join(KEY_FILE)).unwrap(); std::fs::create_dir_all(scratch.path().join(BACKUPS).join("not a stamp")).unwrap(); let listed = list(scratch.path()); - let shown: Vec<(&str, bool)> = listed - .iter() - .map(|backup| (backup.id.as_str(), backup.openable)) - .collect(); + let shown: Vec<(&str, bool)> = + listed.iter().map(|backup| (backup.id.as_str(), backup.openable)).collect(); let (whole_id, keyless_id) = (layout::stamp(at(0)), layout::stamp(at(48))); - assert_eq!( - shown, - [(keyless_id.as_str(), false), (whole_id.as_str(), true)] - ); + assert_eq!(shown, [(keyless_id.as_str(), false), (whole_id.as_str(), true)]); assert_eq!(listed[1].taken_at, at(0)); - let size = std::fs::metadata(whole.join(layout::DATABASE)) - .unwrap() - .len(); + let size = std::fs::metadata(whole.join(layout::DATABASE)).unwrap().len(); assert_eq!(listed[1].bytes, size); } @@ -550,9 +490,7 @@ mod tests { fn a_copy_not_there_or_without_its_key_is_not_put_back() { let scratch = tempfile::tempdir().unwrap(); let (mut connection, _) = library(scratch.path()); - let copy = rotate(scratch.path(), &mut connection, at(0)) - .unwrap() - .unwrap(); + let copy = rotate(scratch.path(), &mut connection, at(0)).unwrap().unwrap(); std::fs::remove_file(copy.join(KEY_FILE)).unwrap(); drop(connection); @@ -570,9 +508,7 @@ mod tests { fn a_copy_is_found_by_its_listing_never_by_a_path() { let scratch = tempfile::tempdir().unwrap(); let (mut connection, _) = library(scratch.path()); - let copy = rotate(scratch.path(), &mut connection, at(0)) - .unwrap() - .unwrap(); + let copy = rotate(scratch.path(), &mut connection, at(0)).unwrap().unwrap(); drop(connection); let stamp = layout::stamp(at(0)); let outside = scratch.path().join(&stamp); @@ -600,17 +536,8 @@ mod tests { let failed = replace(scratch.path(), &layout::stamp(at(0)), at(1)); assert!(matches!(failed, Err(StorageError::File(_)))); - assert_eq!( - std::fs::read(scratch.path().join(layout::DATABASE)).unwrap(), - database - ); - assert!( - !scratch - .path() - .join(REPLACED) - .join(layout::stamp(at(1))) - .exists() - ); + assert_eq!(std::fs::read(scratch.path().join(layout::DATABASE)).unwrap(), database); + assert!(!scratch.path().join(REPLACED).join(layout::stamp(at(1))).exists()); } /// ⚠️ What makes a new phrase revoke anything: every retained copy's key file is rewrapped @@ -620,34 +547,16 @@ mod tests { fn a_new_phrase_reaches_every_copy_s_key_file() { let scratch = tempfile::tempdir().unwrap(); let (mut connection, _) = library(scratch.path()); - let first = rotate(scratch.path(), &mut connection, at(0)) - .unwrap() - .unwrap(); - let keyless = rotate(scratch.path(), &mut connection, at(48)) - .unwrap() - .unwrap(); + let first = rotate(scratch.path(), &mut connection, at(0)).unwrap().unwrap(); + let keyless = rotate(scratch.path(), &mut connection, at(48)).unwrap().unwrap(); std::fs::remove_file(keyless.join(KEY_FILE)).unwrap(); let vault = file::unlock(scratch.path(), PHRASE).unwrap(); - file::write_wrapped( - &first.join(KEY_FILE), - &vault, - "an older one", - Cost::FOR_TESTS, - ) - .unwrap(); - - let tally = rewrap( - scratch.path(), - &vault, - "the next passphrase", - Cost::FOR_TESTS, - ); + file::write_wrapped(&first.join(KEY_FILE), &vault, "an older one", Cost::FOR_TESTS).unwrap(); + + let tally = rewrap(scratch.path(), &vault, "the next passphrase", Cost::FOR_TESTS); assert_eq!(tally, Rewrapped { done: 1, left: 0 }); - assert!(matches!( - file::unlock(&first, "an older one"), - Err(StorageError::WrongPassphrase) - )); + assert!(matches!(file::unlock(&first, "an older one"), Err(StorageError::WrongPassphrase))); assert_eq!(titles_in(&first, "the next passphrase"), ["Kept"]); assert!(!keyless.join(KEY_FILE).exists()); } @@ -658,15 +567,9 @@ mod tests { fn a_key_file_that_cannot_be_rewritten_is_counted_as_left() { let scratch = tempfile::tempdir().unwrap(); let (mut connection, _) = library(scratch.path()); - let copy = rotate(scratch.path(), &mut connection, at(0)) - .unwrap() - .unwrap(); + let copy = rotate(scratch.path(), &mut connection, at(0)).unwrap().unwrap(); let vault = file::unlock(scratch.path(), PHRASE).unwrap(); - let refused = Cost { - memory_kib: 0, - passes: 0, - lanes: 0, - }; + let refused = Cost { memory_kib: 0, passes: 0, lanes: 0 }; let tally = rewrap(scratch.path(), &vault, "the next passphrase", refused); diff --git a/crates/engine/src/changelog.rs b/crates/engine/src/changelog.rs index fc10237cc..eb67f7e05 100644 --- a/crates/engine/src/changelog.rs +++ b/crates/engine/src/changelog.rs @@ -33,11 +33,7 @@ mod tests { assert!(!releases.is_empty(), "the file describes no release"); for release in &releases { - assert!( - !release.sections.is_empty(), - "release {} carries no entry", - release.version - ); + assert!(!release.sections.is_empty(), "release {} carries no entry", release.version); for section in &release.sections { assert!( !section.items.is_empty(), @@ -68,36 +64,25 @@ mod tests { spans.iter().any(|span| span.kind == SpanKind::Code), "no entry in the file carries code any more" ); - assert!( - !spans.iter().any(|span| span.text.contains("**")), - "a marker reached the panel as text" - ); + assert!(!spans.iter().any(|span| span.text.contains("**")), "a marker reached the panel as text"); } /// What `release.yml` hands the updater is the newest section of this very file. #[test] fn the_newest_section_reads_the_same_alone_as_in_the_file() { let start = CHANGELOG.find("\n## ").expect("a release heading") + 1; - let body_start = CHANGELOG[start..] - .find('\n') - .map_or(CHANGELOG.len(), |at| start + at + 1); + let body_start = CHANGELOG[start..].find('\n').map_or(CHANGELOG.len(), |at| start + at + 1); let body_end = CHANGELOG[body_start..] .find("\n## ") .map_or(CHANGELOG.len(), |at| body_start + at); - assert_eq!( - release_notes(&CHANGELOG[body_start..body_end]), - app_changelog().remove(0).sections - ); + assert_eq!(release_notes(&CHANGELOG[body_start..body_end]), app_changelog().remove(0).sections); } #[test] fn the_shipped_file_shows_neither_the_site_nor_its_pages() { for heading in model::NOT_IN_THE_APP { - assert!( - CHANGELOG.contains(&format!("### {heading}\n")), - "{heading} is in no release" - ); + assert!(CHANGELOG.contains(&format!("### {heading}\n")), "{heading} is in no release"); } let shown: Vec<_> = app_changelog() .into_iter() @@ -105,27 +90,17 @@ mod tests { .map(|section| section.title) .collect(); - assert!( - !shown - .iter() - .any(|title| model::NOT_IN_THE_APP.contains(&title.as_str())) - ); + assert!(!shown.iter().any(|title| model::NOT_IN_THE_APP.contains(&title.as_str()))); } /// Written by the script, recognised here: a heading renamed on one side alone would reach /// the panel. #[test] fn the_headings_left_out_are_the_ones_the_release_script_writes() { - let script = include_str!(concat!( - env!("CARGO_MANIFEST_DIR"), - "/../../scripts/release-notes.mjs" - )); + let script = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../scripts/release-notes.mjs")); for heading in model::NOT_IN_THE_APP { - assert!( - script.contains(&format!("heading: '{heading}'")), - "{heading}" - ); + assert!(script.contains(&format!("heading: '{heading}'")), "{heading}"); } } diff --git a/crates/engine/src/changelog/model.rs b/crates/engine/src/changelog/model.rs index 06b95c0dc..1d86adbeb 100644 --- a/crates/engine/src/changelog/model.rs +++ b/crates/engine/src/changelog/model.rs @@ -70,11 +70,7 @@ pub fn parse(markdown: &str) -> Vec { release.sections = sections.take(); } let (version, date) = split_heading(heading); - releases.push(ChangelogRelease { - version, - date, - sections: Vec::new(), - }); + releases.push(ChangelogRelease { version, date, sections: Vec::new() }); } else if !releases.is_empty() { // The preamble sits above the first release, with nothing to attach to. sections.read(line); @@ -128,10 +124,8 @@ impl Sections { /// `false` for a line the grammar has no place for. fn read(&mut self, line: &str) -> bool { if let Some(title) = line.strip_prefix("### ") { - self.sections.push(ChangelogSection { - title: title.trim().to_string(), - items: Vec::new(), - }); + self.sections + .push(ChangelogSection { title: title.trim().to_string(), items: Vec::new() }); self.item_open = false; } else if let Some(entry) = bullet(line) { self.current().items.push(spans(entry)); @@ -152,15 +146,10 @@ impl Sections { fn current(&mut self) -> &mut ChangelogSection { if self.sections.is_empty() { - self.sections.push(ChangelogSection { - title: String::new(), - items: Vec::new(), - }); + self.sections.push(ChangelogSection { title: String::new(), items: Vec::new() }); } - self.sections - .last_mut() - .expect("a section was just pushed if there was none") + self.sections.last_mut().expect("a section was just pushed if there was none") } fn take(&mut self) -> Vec { @@ -268,16 +257,9 @@ fn split_heading(heading: &str) -> (String, Option) { }, }; - let date = rest - .trim() - .trim_start_matches(['-', '–', '—']) - .trim() - .to_string(); + let date = rest.trim().trim_start_matches(['-', '–', '—']).trim().to_string(); - ( - version.trim().to_string(), - (!date.is_empty()).then_some(date), - ) + (version.trim().to_string(), (!date.is_empty()).then_some(date)) } #[cfg(test)] @@ -341,10 +323,7 @@ Everything above the first release is preamble. drop_what_is_not_in_the_app(&mut sections); - let titles: Vec<_> = sections - .iter() - .map(|section| section.title.as_str()) - .collect(); + let titles: Vec<_> = sections.iter().map(|section| section.title.as_str()).collect(); assert_eq!(titles, ["✨ Added", "🧰 Under the hood"]); } @@ -379,10 +358,7 @@ Everything above the first release is preamble. #[test] fn keeps_a_dash_inside_a_version_out_of_the_date() { - assert_eq!( - split_heading("1.0.0-rc.1"), - ("1.0.0-rc.1".to_string(), None) - ); + assert_eq!(split_heading("1.0.0-rc.1"), ("1.0.0-rc.1".to_string(), None)); assert_eq!( split_heading("[1.0.0-rc.1] - 2026-01-01"), ("1.0.0-rc.1".to_string(), Some("2026-01-01".to_string())) @@ -410,9 +386,7 @@ Everything above the first release is preamble. use super::*; fn only(markdown: &str) -> ChangelogEntry { - parse(&format!("## 0.1.0\n\n- {markdown}\n")) - .remove(0) - .sections[0] + parse(&format!("## 0.1.0\n\n- {markdown}\n")).remove(0).sections[0] .items .remove(0) } @@ -445,22 +419,14 @@ Everything above the first release is preamble. fn the_pull_request_number_is_dropped() { assert_eq!( only("Let the library rail go down to 160px (#213)"), - vec![ChangelogSpan::plain( - "Let the library rail go down to 160px".to_string() - )] + vec![ChangelogSpan::plain("Let the library rail go down to 160px".to_string())] ); } #[test] fn something_that_only_looks_like_a_number_is_left_alone() { - assert_eq!( - read(&only("Read the guide (#start here)")), - "Read the guide (#start here)" - ); - assert_eq!( - read(&only("Nothing in brackets (#)")), - "Nothing in brackets (#)" - ); + assert_eq!(read(&only("Read the guide (#start here)")), "Read the guide (#start here)"); + assert_eq!(read(&only("Nothing in brackets (#)")), "Nothing in brackets (#)"); } /// Unclosed is text: an entry about `5 * 3` has to stay readable. @@ -468,9 +434,7 @@ Everything above the first release is preamble. fn a_lone_marker_is_text() { assert_eq!( only("5 * 3 and a ** that closes nothing"), - vec![ChangelogSpan::plain( - "5 * 3 and a ** that closes nothing".to_string() - )] + vec![ChangelogSpan::plain("5 * 3 and a ** that closes nothing".to_string())] ); } @@ -499,10 +463,7 @@ Everything above the first release is preamble. use super::*; fn titles(sections: &[ChangelogSection]) -> Vec<&str> { - sections - .iter() - .map(|section| section.title.as_str()) - .collect() + sections.iter().map(|section| section.title.as_str()).collect() } #[test] diff --git a/crates/engine/src/closed_enum.rs b/crates/engine/src/closed_enum.rs index bd700a220..308438846 100644 --- a/crates/engine/src/closed_enum.rs +++ b/crates/engine/src/closed_enum.rs @@ -82,14 +82,8 @@ mod tests { assert_eq!(shade.to_string(), spelling); assert_eq!(Shade::from_str(spelling), Ok(shade)); - assert_eq!( - serde_json::to_string(&shade).unwrap(), - format!("\"{spelling}\"") - ); - assert_eq!( - serde_json::from_str::(&format!("\"{spelling}\"")).unwrap(), - shade - ); + assert_eq!(serde_json::to_string(&shade).unwrap(), format!("\"{spelling}\"")); + assert_eq!(serde_json::from_str::(&format!("\"{spelling}\"")).unwrap(), shade); } } diff --git a/crates/engine/src/db.rs b/crates/engine/src/db.rs index d9a57fc0f..f2e1b15eb 100644 --- a/crates/engine/src/db.rs +++ b/crates/engine/src/db.rs @@ -79,9 +79,7 @@ impl Library { F: FnOnce(&mut SqliteConnection, &Vault) -> Result, { // Destructured so the two disjoint fields borrow separately. - let Self { - connection, vault, .. - } = self; + let Self { connection, vault, .. } = self; connection.transaction(|connection| f(connection, vault)) } } @@ -95,10 +93,7 @@ pub type Db = Mutex>; /// ⚠️ On the db thread alone (`queue`), checked in debug builds; the crate's own unit tests /// lock their in-memory libraries on the test thread. pub(crate) fn lock(db: &Db) -> Result, StorageError> { - debug_assert!( - cfg!(test) || queue::on_db_thread(), - "the library is locked off the db thread" - ); + debug_assert!(cfg!(test) || queue::on_db_thread(), "the library is locked off the db thread"); let guard = db.lock().map_err(|_| StorageError::Unavailable)?; if guard.is_none() { return Err(StorageError::Locked); @@ -120,10 +115,7 @@ where /// [`run`], queued at the call rather than at the first poll: the interface sends from its /// thread and waits elsewhere, and two jobs sent in a row must still run in that order. -pub fn submit( - engine: &Arc, - job: F, -) -> impl Future> + use +pub fn submit(engine: &Arc, job: F) -> impl Future> + use where T: Send + 'static, F: FnOnce(&Engine) -> Result + Send + 'static, @@ -201,21 +193,14 @@ fn is_unreadable(error: &StorageError) -> bool { /// Every failure names the file: this is the error a user meets before any window has /// anything in it, and the database sits in a directory they have never opened. pub fn open(path: &Path, vault: Vault) -> Result { - let named = |error: &dyn std::fmt::Display| { - StorageError::Migration(format!("{}: {error}", path.display())) - }; + let named = + |error: &dyn std::fmt::Display| StorageError::Migration(format!("{}: {error}", path.display())); let mut connection = SqliteConnection::establish(&path.to_string_lossy()).map_err(|error| named(&error))?; - let damaged = - |error: &StorageError| StorageError::Damaged(format!("{}: {error}", path.display())); - configure(&mut connection).map_err(|error| { - if is_unreadable(&error) { - damaged(&error) - } else { - named(&error) - } - })?; + let damaged = |error: &StorageError| StorageError::Damaged(format!("{}: {error}", path.display())); + configure(&mut connection) + .map_err(|error| if is_unreadable(&error) { damaged(&error) } else { named(&error) })?; // ⚠️ Before the migrations, which write: running them over a damaged file is how a // salvageable database becomes an unsalvageable one. @@ -243,8 +228,7 @@ pub fn open_in_memory() -> Result { connection, vault: Arc::new(test_vault()?), // Named, never created: a test writing beside the library fails loudly. - directory: std::env::temp_dir() - .join(format!("devnotes-in-memory-{}", uuid::Uuid::new_v4())), + directory: std::env::temp_dir().join(format!("devnotes-in-memory-{}", uuid::Uuid::new_v4())), number: next_number(), }) } @@ -253,8 +237,7 @@ impl Library { /// Once the index holds every body, nothing reads the file end to end again, and what stays /// mapped stays in the process. Before that, the mapping is what makes the fill fast. pub(crate) fn map_less(&mut self) -> Result<(), StorageError> { - self.connection - .batch_execute("PRAGMA mmap_size = 67108864;")?; + self.connection.batch_execute("PRAGMA mmap_size = 67108864;")?; Ok(()) } } @@ -263,11 +246,7 @@ impl Library { /// what the tests and the benchmarks need. #[doc(hidden)] pub fn test_vault() -> Result { - Vault::derive( - "in-memory", - b"0123456789abcdef", - crate::vault::key::Cost::FOR_TESTS, - ) + Vault::derive("in-memory", b"0123456789abcdef", crate::vault::key::Cost::FOR_TESTS) } fn configure(connection: &mut SqliteConnection) -> Result<(), StorageError> { @@ -395,11 +374,7 @@ mod tests { let scratch = tempfile::tempdir().unwrap(); let mut library = opened(&scratch); - for (name, value) in [ - ("foreign_keys", 1), - ("busy_timeout", 5000), - ("synchronous", 1), - ] { + for (name, value) in [("foreign_keys", 1), ("busy_timeout", 5000), ("synchronous", 1)] { assert_eq!(pragma(&mut library, name), value, "{name}"); } // A build of SQLite whose ceiling is lower answers that ceiling. @@ -531,10 +506,7 @@ mod tests { }) .join(); - assert!(matches!( - lock(&db).map(drop), - Err(StorageError::Unavailable) - )); + assert!(matches!(lock(&db).map(drop), Err(StorageError::Unavailable))); } /// A send writes only into the library it read from. diff --git a/crates/engine/src/db/migration.rs b/crates/engine/src/db/migration.rs index c0335d6cc..e0accd159 100644 --- a/crates/engine/src/db/migration.rs +++ b/crates/engine/src/db/migration.rs @@ -88,11 +88,9 @@ mod tests { #[test] fn a_migration_this_binary_does_not_know_is_refused() { let mut connection = open_in_memory().unwrap(); - diesel::sql_query( - "INSERT INTO __diesel_schema_migrations (version) VALUES ('2099-01-01-000000')", - ) - .execute(connection.db()) - .unwrap(); + diesel::sql_query("INSERT INTO __diesel_schema_migrations (version) VALUES ('2099-01-01-000000')") + .execute(connection.db()) + .unwrap(); let error = run(connection.db()).unwrap_err(); diff --git a/crates/engine/src/db/queue.rs b/crates/engine/src/db/queue.rs index 62e447464..bc92febec 100644 --- a/crates/engine/src/db/queue.rs +++ b/crates/engine/src/db/queue.rs @@ -60,10 +60,7 @@ impl DbQueue { /// Queues `job` now, in the caller's order, and answers a future of its result: what /// keeps two calls made one after the other in that order when the waiting is done /// elsewhere. - pub(crate) fn submit( - &self, - job: F, - ) -> impl Future> + use + pub(crate) fn submit(&self, job: F) -> impl Future> + use where T: Send + 'static, F: FnOnce() -> Result + Send + 'static, @@ -89,10 +86,7 @@ mod tests { use crate::error::ErrorCode; fn block_on(future: impl Future) -> T { - tokio::runtime::Builder::new_current_thread() - .build() - .unwrap() - .block_on(future) + tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(future) } #[test] diff --git a/crates/engine/src/docs.rs b/crates/engine/src/docs.rs index 30b41b527..1a0340186 100644 --- a/crates/engine/src/docs.rs +++ b/crates/engine/src/docs.rs @@ -10,10 +10,7 @@ use model::{Index, Page}; // `SOURCES`: each file of `docs/content/`, by language and page, written by `build.rs`. include!(concat!(env!("OUT_DIR"), "/docs.rs")); -const INDEX: &str = include_str!(concat!( - env!("CARGO_MANIFEST_DIR"), - "/../../docs/content/index.json" -)); +const INDEX: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../docs/content/index.json")); static READ_INDEX: LazyLock = LazyLock::new(|| serde_json::from_str(INDEX).expect("compiled in, and held by a test")); @@ -29,12 +26,8 @@ pub fn docs_index() -> &'static Index { /// A page in a language, by its name in the index. pub fn docs_page(language: &str, id: &str) -> Option<&'static Page> { - let at = SOURCES - .iter() - .position(|source| source.0 == language && source.1 == id)?; - PAGES[at] - .get_or_init(|| model::read(id, SOURCES[at].2).ok()) - .as_ref() + let at = SOURCES.iter().position(|source| source.0 == language && source.1 == id)?; + PAGES[at].get_or_init(|| model::read(id, SOURCES[at].2).ok()).as_ref() } #[cfg(test)] @@ -47,10 +40,7 @@ mod tests { const LANGUAGES: [&str; 2] = ["fr", "en"]; fn ids() -> Vec<&'static str> { - docs_index() - .pages() - .map(|entry| entry.id.as_str()) - .collect() + docs_index().pages().map(|entry| entry.id.as_str()).collect() } fn runs(block: &Block) -> Vec<&Inline> { @@ -124,10 +114,7 @@ mod tests { let mut sections = Vec::new(); for block in &page.body { if let Block::Heading { id: section, .. } = block { - assert!( - !sections.contains(§ion), - "{language}/{id}.md: {section}" - ); + assert!(!sections.contains(§ion), "{language}/{id}.md: {section}"); sections.push(section); } } @@ -137,17 +124,8 @@ mod tests { #[test] fn every_link_leads_to_a_page_and_a_section_that_exist() { for (language, id, _) in SOURCES { - for run in docs_page(language, id) - .expect(id) - .body - .iter() - .flat_map(runs) - { - let Inline::Link { - text, - to: Target::Page { id: to, section }, - } = run - else { + for run in docs_page(language, id).expect(id).body.iter().flat_map(runs) { + let Inline::Link { text, to: Target::Page { id: to, section } } = run else { continue; }; let name = format!("docs/content/{language}/{id}.md: « {text} »"); @@ -170,11 +148,7 @@ mod tests { Block::Pages(pages) => Some(pages.clone()), _ => None, }); - assert_eq!( - listed.unwrap_or_default(), - ids()[1..], - "{language}/overview.md" - ); + assert_eq!(listed.unwrap_or_default(), ids()[1..], "{language}/overview.md"); } } diff --git a/crates/engine/src/docs/model.rs b/crates/engine/src/docs/model.rs index 1d473a19b..2ceda14e4 100644 --- a/crates/engine/src/docs/model.rs +++ b/crates/engine/src/docs/model.rs @@ -163,9 +163,7 @@ pub fn read(id: &str, markdown: &str) -> Reading { let mut reader = Reader { id, markdown, - events: Parser::new_ext(markdown, options) - .into_offset_iter() - .collect(), + events: Parser::new_ext(markdown, options).into_offset_iter().collect(), at: 0, }; reader.page() @@ -181,10 +179,7 @@ struct Reader<'a> { impl<'a> Reader<'a> { fn page(&mut self) -> Reading { let title = match self.next() { - Some(Event::Start(Tag::Heading { - level: HeadingLevel::H1, - .. - })) => self.plain()?, + Some(Event::Start(Tag::Heading { level: HeadingLevel::H1, .. })) => self.plain()?, _ => return self.refuse("a page begins with # and its title"), }; let summary = match self.next() { @@ -196,21 +191,13 @@ impl<'a> Reader<'a> { while self.at < self.events.len() { body.push(self.titled_block()?); } - Ok(Page { - id: self.id.to_owned(), - title, - summary, - body, - }) + Ok(Page { id: self.id.to_owned(), title, summary, body }) } /// A block, and the title of a table or a code block: the bold line just above it. fn titled_block(&mut self) -> Reading { let first = self.block(None)?; - let titled = matches!( - self.peek(), - Some(Event::Start(Tag::Table(_) | Tag::CodeBlock(_))) - ); + let titled = matches!(self.peek(), Some(Event::Start(Tag::Table(_) | Tag::CodeBlock(_)))); match first { Block::Paragraph(text) if titled => match text.as_slice() { [Inline::Strong(title)] => self.block(Some(title)), @@ -248,11 +235,7 @@ impl<'a> Reader<'a> { _ => return self.refuse("a section is ## or ###"), }; let text = self.plain()?; - Ok(Block::Heading { - level, - id: slug(&text), - text, - }) + Ok(Block::Heading { level, id: slug(&text), text }) } fn list(&mut self, ordered: bool) -> Reading { @@ -289,11 +272,7 @@ impl<'a> Reader<'a> { CodeBlockKind::Fenced(language) => language.to_string(), CodeBlockKind::Indented => return self.refuse("a code block is between ```"), }; - Ok(Block::Code { - title: title.to_owned(), - language, - text: text.trim_end_matches('\n').to_owned(), - }) + Ok(Block::Code { title: title.to_owned(), language, text: text.trim_end_matches('\n').to_owned() }) } fn table(&mut self, title: &str) -> Reading { @@ -319,29 +298,21 @@ impl<'a> Reader<'a> { .collect::>(); let title = title.to_owned(); if !SHORTCUTS.contains(&head[0].as_str()) { - return Ok(Block::Table { - title, - head, - rows: rows.collect(), - }); + return Ok(Block::Table { title, head, rows: rows.collect() }); } let mut shortcuts = Vec::new(); for row in rows { match row.as_slice() { [keys, does] => match keys.as_slice() { - [Inline::Keys(keys)] => shortcuts.push(Shortcut { - keys: keys.clone(), - does: text_of(does), - }), + [Inline::Keys(keys)] => { + shortcuts.push(Shortcut { keys: keys.clone(), does: text_of(does) }); + } _ => return self.refuse("a table of shortcuts holds one per row"), }, _ => return self.refuse("a table of shortcuts has two columns"), } } - Ok(Block::Shortcuts { - title, - rows: shortcuts, - }) + Ok(Block::Shortcuts { title, rows: shortcuts }) } /// What an item or a note holds: one paragraph, marked as such or not. @@ -368,10 +339,9 @@ impl<'a> Reader<'a> { Some(Event::Code(code)) => Inline::Code(code.to_string()), Some(Event::Start(Tag::Strong)) => Inline::Strong(self.plain()?), Some(Event::Start(Tag::Emphasis)) => Inline::Label(self.plain()?), - Some(Event::Start(Tag::Link { dest_url, .. })) => Inline::Link { - text: self.plain()?, - to: self.target(&dest_url)?, - }, + Some(Event::Start(Tag::Link { dest_url, .. })) => { + Inline::Link { text: self.plain()?, to: self.target(&dest_url)? } + } Some(Event::InlineHtml(tag)) if &*tag == "" => Inline::Keys(self.keys()?), Some(other) => return self.refuse(format!("{other:?} is not read")), }; @@ -417,10 +387,7 @@ impl<'a> Reader<'a> { None if file.is_empty() && section.is_some() => self.id, _ => return self.refuse(format!("{href} leads nowhere")), }; - Ok(Target::Page { - id: id.to_owned(), - section, - }) + Ok(Target::Page { id: id.to_owned(), section }) } fn peek(&self) -> Option<&Event<'a>> { @@ -435,26 +402,15 @@ impl<'a> Reader<'a> { /// At the event just read. fn refuse(&self, message: impl Into) -> Reading { - let at = self - .events - .get(self.at.saturating_sub(1)) - .map_or(0, |(_, range)| range.start); - Err(Refusal { - line: self.markdown[..at].matches('\n').count() + 1, - message: message.into(), - }) + let at = self.events.get(self.at.saturating_sub(1)).map_or(0, |(_, range)| range.start); + Err(Refusal { line: self.markdown[..at].matches('\n').count() + 1, message: message.into() }) } } /// The page an item leads to, when it is a link to it and nothing more. fn only_page(item: &[Inline]) -> Option { match item { - [ - Inline::Link { - to: Target::Page { id, section: None }, - .. - }, - ] => Some(id.clone()), + [Inline::Link { to: Target::Page { id, section: None }, .. }] => Some(id.clone()), _ => None, } } @@ -499,10 +455,7 @@ mod tests { #[test] fn a_page_opens_on_its_title_and_its_summary() { let page = read("page", HEAD).expect("a page"); - assert_eq!( - (page.title.as_str(), page.summary.as_str()), - ("Titre", "Résumé.") - ); + assert_eq!((page.title.as_str(), page.summary.as_str()), ("Titre", "Résumé.")); assert!(page.body.is_empty()); let refusal = read("page", "Sans titre.\n").expect_err("no title"); @@ -530,10 +483,7 @@ mod tests { text(" ou "), Inline::Link { text: "là".to_owned(), - to: Target::Page { - id: "start".to_owned(), - section: Some("cle-maitre".to_owned()), - }, + to: Target::Page { id: "start".to_owned(), section: Some("cle-maitre".to_owned()) }, }, text("."), ])] @@ -549,13 +499,7 @@ mod tests { }, other => panic!("{other:?}"), }; - assert_eq!( - to("[a](#ici)"), - Target::Page { - id: "page".to_owned(), - section: Some("ici".to_owned()), - } - ); + assert_eq!(to("[a](#ici)"), Target::Page { id: "page".to_owned(), section: Some("ici".to_owned()) }); assert_eq!( to("[a](https://devnotes.fr/telecharger)"), Target::Address("https://devnotes.fr/telecharger".to_owned()) @@ -567,10 +511,7 @@ mod tests { fn a_list_of_nothing_but_pages_is_the_list_of_them() { assert_eq!( body("- [Écrire](writing.md)\n- [Ranger](organising.md)\n"), - [Block::Pages(vec![ - "writing".to_owned(), - "organising".to_owned() - ])] + [Block::Pages(vec!["writing".to_owned(), "organising".to_owned()])] ); assert_eq!( body("1. un\n2. *deux*\n"), @@ -600,10 +541,7 @@ mod tests { [Block::Table { title: "Fichiers".to_owned(), head: vec!["Système".to_owned(), "Fichier".to_owned()], - rows: vec![vec![ - vec![text("Linux")], - vec![Inline::Code("a|b".to_owned())] - ]], + rows: vec![vec![vec![text("Linux")], vec![Inline::Code("a|b".to_owned())]]], }] ); assert_eq!( @@ -621,9 +559,8 @@ mod tests { #[test] fn a_table_headed_by_the_keys_is_one_of_shortcuts() { for head in SHORTCUTS { - let table = format!( - "**Palette**\n\n| {head} | Action |\n| --- | --- |\n| ↑ ↓ | Choisir |\n" - ); + let table = + format!("**Palette**\n\n| {head} | Action |\n| --- | --- |\n| ↑ ↓ | Choisir |\n"); assert_eq!( body(&table), [Block::Shortcuts { @@ -649,9 +586,7 @@ mod tests { "- un\n - dedans\n", "> [!TIP]\n> un\n>\n> deux\n", ] { - assert!( - refused(markdown).starts_with('5') || refused(markdown).starts_with(['6', '8']) - ); + assert!(refused(markdown).starts_with('5') || refused(markdown).starts_with(['6', '8'])); } } @@ -680,23 +615,14 @@ mod tests { ); } for nowhere in ["", "start", "a/start.md", "a.b.md", "ftp://a"] { - assert!( - refused(&format!("[a]({nowhere})")).contains("leads nowhere"), - "{nowhere}" - ); + assert!(refused(&format!("[a]({nowhere})")).contains("leads nowhere"), "{nowhere}"); } } #[test] fn a_name_is_given_in_its_language_or_in_english() { - let names = Names { - fr: "Début".to_owned(), - en: "Start".to_owned(), - }; + let names = Names { fr: "Début".to_owned(), en: "Start".to_owned() }; - assert_eq!( - [names.of("fr"), names.of("en"), names.of("de")], - ["Début", "Start", "Start"] - ); + assert_eq!([names.of("fr"), names.of("en"), names.of("de")], ["Début", "Start", "Start"]); } } diff --git a/crates/engine/src/docs/search.rs b/crates/engine/src/docs/search.rs index 23717f4c4..883b98f7f 100644 --- a/crates/engine/src/docs/search.rs +++ b/crates/engine/src/docs/search.rs @@ -44,15 +44,13 @@ pub fn search_docs(language: &str, query: &str) -> Vec { let mut found: Vec<_> = sections(language) .iter() .filter(|section| { - terms.iter().all(|term| { - section.folded_heading.contains(term) || section.folded_text.contains(term) - }) + terms + .iter() + .all(|term| section.folded_heading.contains(term) || section.folded_text.contains(term)) }) .collect(); found.sort_by_key(|section| { - let named = terms - .iter() - .filter(|term| section.folded_heading.contains(**term)); + let named = terms.iter().filter(|term| section.folded_heading.contains(**term)); std::cmp::Reverse(named.count()) }); found @@ -97,14 +95,7 @@ fn cut(page: &'static Page) -> Vec

    { .into_iter() .map(|(id, heading, words)| { let text = words.join(" "); - Section { - page, - id, - heading, - folded_heading: fold(heading), - folded_text: fold(&text), - text, - } + Section { page, id, heading, folded_heading: fold(heading), folded_text: fold(&text), text } }) .collect() } @@ -116,9 +107,7 @@ fn said(block: &Block) -> String { Block::List { items, .. } => join(items.iter().map(|item| text_of(item))), Block::Code { title, text, .. } => format!("{title} {text}"), Block::Shortcuts { title, rows } => { - let rows = rows - .iter() - .map(|Shortcut { keys, does }| format!("{} {does}", keys.join(" "))); + let rows = rows.iter().map(|Shortcut { keys, does }| format!("{} {does}", keys.join(" "))); format!("{title} {}", join(rows)) } Block::Table { title, rows, .. } => { @@ -159,10 +148,7 @@ mod tests { #[test] fn a_heading_comes_before_a_mention() { let hits = search_docs("en", "palette"); - assert_eq!( - (hits[0].page.id.as_str(), hits[0].heading), - ("paste", "The palette") - ); + assert_eq!((hits[0].page.id.as_str(), hits[0].heading), ("paste", "The palette")); } #[test] @@ -187,10 +173,7 @@ mod tests { #[test] fn an_excerpt_says_where_it_was_cut() { let text = "un deux trois quatre cinq six sept huit neuf dix"; - assert_eq!( - excerpt(text, "huit"), - "…deux trois quatre cinq six sept huit neuf dix" - ); + assert_eq!(excerpt(text, "huit"), "…deux trois quatre cinq six sept huit neuf dix"); assert_eq!(excerpt(text, "absent"), text); } diff --git a/crates/engine/src/error.rs b/crates/engine/src/error.rs index 4542f9f23..d884ede03 100644 --- a/crates/engine/src/error.rs +++ b/crates/engine/src/error.rs @@ -16,10 +16,7 @@ pub struct ValidationError { impl ValidationError { pub fn new(field: &'static str, detail: impl Into) -> Self { - Self { - field, - detail: detail.into(), - } + Self { field, detail: detail.into() } } } @@ -200,11 +197,7 @@ pub struct AppError { impl AppError { pub(crate) fn new(code: ErrorCode, detail: String) -> Self { - Self { - code, - params: BTreeMap::new(), - detail, - } + Self { code, params: BTreeMap::new(), detail } } pub(crate) fn with(code: ErrorCode, detail: String, key: &str, value: &str) -> Self { @@ -249,11 +242,7 @@ impl AppError { | C::HttpScriptSkipped | C::HttpRunData ); - if plain { - format!("{:?}: {}", self.code, self.detail) - } else { - format!("{:?}", self.code) - } + if plain { format!("{:?}: {}", self.code, self.detail) } else { format!("{:?}", self.code) } } pub fn storage_unavailable() -> Self { @@ -266,12 +255,7 @@ impl AppError { impl From for AppError { fn from(error: ValidationError) -> Self { - Self::with( - ErrorCode::InvalidInput, - error.to_string(), - "field", - error.field, - ) + Self::with(ErrorCode::InvalidInput, error.to_string(), "field", error.field) } } @@ -280,27 +264,19 @@ impl From for AppError { let detail = error.to_string(); match error { - StorageError::NoteNotFound(id) => { - Self::with(ErrorCode::NoteNotFound, detail, "id", &id) - } - StorageError::SpaceNotFound(id) => { - Self::with(ErrorCode::SpaceNotFound, detail, "id", &id) - } + StorageError::NoteNotFound(id) => Self::with(ErrorCode::NoteNotFound, detail, "id", &id), + StorageError::SpaceNotFound(id) => Self::with(ErrorCode::SpaceNotFound, detail, "id", &id), StorageError::DuplicateSpaceName(name) => { Self::with(ErrorCode::DuplicateSpaceName, detail, "name", &name) } - StorageError::FolderNotFound(id) => { - Self::with(ErrorCode::FolderNotFound, detail, "id", &id) - } + StorageError::FolderNotFound(id) => Self::with(ErrorCode::FolderNotFound, detail, "id", &id), StorageError::DuplicateFolderName(name) => { Self::with(ErrorCode::DuplicateFolderName, detail, "name", &name) } StorageError::AttachmentNotFound(id) => { Self::with(ErrorCode::AttachmentNotFound, detail, "id", &id) } - StorageError::HttpItemNotFound(id) => { - Self::with(ErrorCode::HttpItemNotFound, detail, "id", &id) - } + StorageError::HttpItemNotFound(id) => Self::with(ErrorCode::HttpItemNotFound, detail, "id", &id), StorageError::HttpEnvironmentNotFound(id) => { Self::with(ErrorCode::HttpEnvironmentNotFound, detail, "id", &id) } @@ -308,23 +284,15 @@ impl From for AppError { Self::with(ErrorCode::DuplicateEnvironmentName, detail, "name", &name) } StorageError::Invalid(error) => error.into(), - StorageError::RevisionNotFound(id) => { - Self::with(ErrorCode::RevisionNotFound, detail, "id", &id) - } - StorageError::LibraryNotFound(id) => { - Self::with(ErrorCode::LibraryNotFound, detail, "id", &id) - } + StorageError::RevisionNotFound(id) => Self::with(ErrorCode::RevisionNotFound, detail, "id", &id), + StorageError::LibraryNotFound(id) => Self::with(ErrorCode::LibraryNotFound, detail, "id", &id), StorageError::LibraryOpen => Self::new(ErrorCode::LibraryOpen, detail), StorageError::LastLibrary => Self::new(ErrorCode::LastLibrary, detail), StorageError::NothingToSetAside(path) => { Self::with(ErrorCode::NothingToSetAside, detail, "path", &path) } - StorageError::BackupNotFound(id) => { - Self::with(ErrorCode::BackupNotFound, detail, "id", &id) - } - StorageError::BackupUnopenable(id) => { - Self::with(ErrorCode::BackupUnopenable, detail, "id", &id) - } + StorageError::BackupNotFound(id) => Self::with(ErrorCode::BackupNotFound, detail, "id", &id), + StorageError::BackupUnopenable(id) => Self::with(ErrorCode::BackupUnopenable, detail, "id", &id), StorageError::Unavailable => Self::new(ErrorCode::StorageUnavailable, detail), StorageError::WrongPassphrase => Self::new(ErrorCode::WrongPassphrase, detail), StorageError::PassphraseRequired => Self::new(ErrorCode::PassphraseRequired, detail), @@ -332,8 +300,7 @@ impl From for AppError { StorageError::Damaged(_) => Self::new(ErrorCode::LibraryDamaged, detail), StorageError::File(_) => Self::new(ErrorCode::FileAccess, detail), StorageError::TooLarge { name, limit_mb } => { - Self::with(ErrorCode::FileTooLarge, detail, "name", &name) - .and("limit", &limit_mb.to_string()) + Self::with(ErrorCode::FileTooLarge, detail, "name", &name).and("limit", &limit_mb.to_string()) } StorageError::ImportFormat(_) => Self::new(ErrorCode::ImportFormat, detail), // Nothing here gives the front anything to do beyond reporting the failure. @@ -363,60 +330,20 @@ mod tests { vec![ (E::NoteNotFound(text("x")), C::NoteNotFound, Some("id")), (E::SpaceNotFound(text("x")), C::SpaceNotFound, Some("id")), - ( - E::DuplicateSpaceName(text("x")), - C::DuplicateSpaceName, - Some("name"), - ), + (E::DuplicateSpaceName(text("x")), C::DuplicateSpaceName, Some("name")), (E::FolderNotFound(text("x")), C::FolderNotFound, Some("id")), - ( - E::DuplicateFolderName(text("x")), - C::DuplicateFolderName, - Some("name"), - ), - ( - E::AttachmentNotFound(text("x")), - C::AttachmentNotFound, - Some("id"), - ), - ( - E::HttpItemNotFound(text("x")), - C::HttpItemNotFound, - Some("id"), - ), - ( - E::HttpEnvironmentNotFound(text("x")), - C::HttpEnvironmentNotFound, - Some("id"), - ), - ( - E::DuplicateEnvironmentName(text("x")), - C::DuplicateEnvironmentName, - Some("name"), - ), - ( - E::RevisionNotFound(text("x")), - C::RevisionNotFound, - Some("id"), - ), - ( - E::LibraryNotFound(text("x")), - C::LibraryNotFound, - Some("id"), - ), + (E::DuplicateFolderName(text("x")), C::DuplicateFolderName, Some("name")), + (E::AttachmentNotFound(text("x")), C::AttachmentNotFound, Some("id")), + (E::HttpItemNotFound(text("x")), C::HttpItemNotFound, Some("id")), + (E::HttpEnvironmentNotFound(text("x")), C::HttpEnvironmentNotFound, Some("id")), + (E::DuplicateEnvironmentName(text("x")), C::DuplicateEnvironmentName, Some("name")), + (E::RevisionNotFound(text("x")), C::RevisionNotFound, Some("id")), + (E::LibraryNotFound(text("x")), C::LibraryNotFound, Some("id")), (E::LibraryOpen, C::LibraryOpen, None), (E::LastLibrary, C::LastLibrary, None), - ( - E::NothingToSetAside(text("x")), - C::NothingToSetAside, - Some("path"), - ), + (E::NothingToSetAside(text("x")), C::NothingToSetAside, Some("path")), (E::BackupNotFound(text("x")), C::BackupNotFound, Some("id")), - ( - E::BackupUnopenable(text("x")), - C::BackupUnopenable, - Some("id"), - ), + (E::BackupUnopenable(text("x")), C::BackupUnopenable, Some("id")), (E::File(text("x")), C::FileAccess, None), (E::ImportFormat(text("x")), C::ImportFormat, None), (E::Damaged(text("x")), C::LibraryDamaged, None), @@ -425,14 +352,7 @@ mod tests { (E::Unavailable, C::StorageUnavailable, None), (E::Locked, C::Locked, None), // Nothing here gives the interface anything to do beyond reporting the failure. - ( - E::CorruptRow { - id: text("x"), - field: "tags", - }, - C::Storage, - None, - ), + (E::CorruptRow { id: text("x"), field: "tags" }, C::Storage, None), (E::SchemaTooRecent(text("x")), C::Storage, None), (E::Migration(text("x")), C::Storage, None), (E::Vault(text("x")), C::Storage, None), @@ -459,29 +379,17 @@ mod tests { #[test] fn a_file_too_large_says_its_name_and_the_limit() { - let answered = AppError::from(StorageError::TooLarge { - name: text("film.mp4"), - limit_mb: 25, - }); + let answered = AppError::from(StorageError::TooLarge { name: text("film.mp4"), limit_mb: 25 }); assert_eq!(answered.code, ErrorCode::FileTooLarge); - assert_eq!( - ( - answered.params["name"].as_str(), - answered.params["limit"].as_str() - ), - ("film.mp4", "25") - ); + assert_eq!((answered.params["name"].as_str(), answered.params["limit"].as_str()), ("film.mp4", "25")); } #[test] fn an_input_refused_names_its_field_wherever_it_was_refused() { let refused = || ValidationError::new("folderId", "a folder cannot move into itself"); - for answered in [ - AppError::from(refused()), - AppError::from(StorageError::from(refused())), - ] { + for answered in [AppError::from(refused()), AppError::from(StorageError::from(refused()))] { assert_eq!( (answered.code, answered.params["field"].as_str()), (ErrorCode::InvalidInput, "folderId") @@ -500,10 +408,7 @@ mod tests { #[test] fn a_storage_unavailable_is_the_same_wherever_it_is_said() { - assert_eq!( - AppError::storage_unavailable().code, - AppError::from(StorageError::Unavailable).code - ); + assert_eq!(AppError::storage_unavailable().code, AppError::from(StorageError::Unavailable).code); assert!(AppError::storage_unavailable().params.is_empty()); } @@ -517,11 +422,7 @@ mod tests { StorageError::DuplicateEnvironmentName(typed()).into(), StorageError::NothingToSetAside(typed()).into(), StorageError::File(typed()).into(), - StorageError::TooLarge { - name: typed(), - limit_mb: 1, - } - .into(), + StorageError::TooLarge { name: typed(), limit_mb: 1 }.into(), StorageError::ImportFormat(typed()).into(), ValidationError::new("title", typed()).into(), SendError::Variable(typed()).into(), @@ -533,10 +434,7 @@ mod tests { SendError::FileTooLarge(typed()).into(), SendError::GraphqlVariables(typed()).into(), SendError::Network(typed()).into(), - SendError::SocketScheme { - twin: Some(typed()), - } - .into(), + SendError::SocketScheme { twin: Some(typed()) }.into(), ]; for error in errors { let line = error.for_log(); @@ -553,20 +451,13 @@ mod tests { StorageError::BackupNotFound(text("2026-07-25_09-05-07")).into(), StorageError::Locked.into(), StorageError::Damaged(text("page 3")).into(), - StorageError::CorruptRow { - id: text("n-1"), - field: "tags", - } - .into(), + StorageError::CorruptRow { id: text("n-1"), field: "tags" }.into(), SendError::Handshake(403).into(), SendError::Fell.into(), DataFault::Empty.into(), ]; for error in errors { - assert_eq!( - error.for_log(), - format!("{:?}: {}", error.code, error.detail) - ); + assert_eq!(error.for_log(), format!("{:?}: {}", error.code, error.detail)); } } } diff --git a/crates/engine/src/folders.rs b/crates/engine/src/folders.rs index 763d0c12d..24ed9d2fc 100644 --- a/crates/engine/src/folders.rs +++ b/crates/engine/src/folders.rs @@ -69,12 +69,7 @@ pub fn save_board_layout( let db = &engine.db; let mut connection = lock(db)?; - Ok(store::board::save_layout( - &mut connection, - root_id.map(std::string::String::as_str), - zones, - cards, - )?) + Ok(store::board::save_layout(&mut connection, root_id.map(std::string::String::as_str), zones, cards)?) } /// `None` = every space, like [`crate::notes::view::NotesQuery::space_id`]. @@ -82,10 +77,7 @@ pub fn list_folders(engine: &Engine, space_id: Option<&String>) -> Result Result { @@ -94,17 +86,9 @@ pub fn create_folder(engine: &Engine, draft: &FolderDraft) -> Result Result Result { +pub fn recolour_folder(engine: &Engine, id: &str, colour: FolderColour) -> Result { engine.write(|db| { let mut connection = lock(db)?; let answer = store::recolour(&mut connection, id, colour)?; - let changed = Changed { - folders: true, - ..Changed::default() - }; + let changed = Changed { folders: true, ..Changed::default() }; Ok((answer, changed)) }) } @@ -152,15 +126,9 @@ pub fn move_folder( engine.write(|db| { let mut connection = lock(db)?; - let answer = store::move_to( - &mut connection, - id, - (space_id, parent_id.map(std::string::String::as_str)), - )?; - let changed = Changed { - folders: true, - ..Changed::notes(answer.notes.clone()) - }; + let answer = + store::move_to(&mut connection, id, (space_id, parent_id.map(std::string::String::as_str)))?; + let changed = Changed { folders: true, ..Changed::notes(answer.notes.clone()) }; Ok((answer, changed)) }) } @@ -171,10 +139,7 @@ pub fn move_folder_back(engine: &Engine, was: &FolderMove) -> Result BoardFrame { #[must_use] pub fn clamp_point(point: BoardPoint) -> BoardPoint { - BoardPoint { - x: point.x.clamp(0, MAX_SIDE), - y: point.y.clamp(0, MAX_SIDE), - } + BoardPoint { x: point.x.clamp(0, MAX_SIDE), y: point.y.clamp(0, MAX_SIDE) } } /// Big enough for the header and one card, or nothing can be dropped in. @@ -360,12 +357,7 @@ pub fn arrange_zones(contents: &[ZoneContents], card: i32) -> Vec { let height = default_zone_height(zone.notes, zone.nested, card); row_height = row_height.max(height); - frames.push(BoardFrame { - x: BOARD_MARGIN + px(column) * (width + GAP), - y: row_top, - width, - height, - }); + frames.push(BoardFrame { x: BOARD_MARGIN + px(column) * (width + GAP), y: row_top, width, height }); } frames @@ -404,12 +396,7 @@ fn overlaps(at: BoardPoint, card: i32, frame: BoardFrame) -> bool { } fn card_frame(at: BoardPoint, card: i32) -> BoardFrame { - BoardFrame { - x: at.x, - y: at.y, - width: CARD_WIDTH, - height: card, - } + BoardFrame { x: at.x, y: at.y, width: CARD_WIDTH, height: card } } /// Below everything already on the board — where a seat goes when the grid has none free. @@ -421,10 +408,7 @@ fn under_everything(taken: &[BoardPoint], zones: &[BoardFrame], card: i32) -> Bo .max() .unwrap_or(BOARD_MARGIN); - BoardPoint { - x: BOARD_MARGIN, - y: bottom + GAP, - } + BoardPoint { x: BOARD_MARGIN, y: bottom + GAP } } /// Where a card that has never been placed goes: the first seat of the flow grid nothing @@ -453,9 +437,7 @@ pub fn free_slot_from( (first..=limit) .map(|index| (index, slot(index, top, card))) .find(|(_, at)| { - !taken - .iter() - .any(|other| overlaps(*at, card, card_frame(*other, card))) + !taken.iter().any(|other| overlaps(*at, card, card_frame(*other, card))) && !zones.iter().any(|frame| overlaps(*at, card, *frame)) }) .unwrap_or_else(|| (first, under_everything(taken, zones, card))) @@ -565,11 +547,7 @@ pub fn build( let hit = criteria.passes(¬e); matched += usize::from(hit); - let entry = BoardNote { - note: model::decorate(note, request.now), - matches: hit, - position: None, - }; + let entry = BoardNote { note: model::decorate(note, request.now), matches: hit, position: None }; match seat { Seat::Zone(id) => by_folder.entry(id).or_default().push(entry), @@ -581,10 +559,7 @@ pub fn build( entry.position = positions.get(&entry.note.id).copied(); } - let by_id: HashMap<&str, &Folder> = folders - .iter() - .map(|folder| (folder.id.as_str(), folder)) - .collect(); + let by_id: HashMap<&str, &Folder> = folders.iter().map(|folder| (folder.id.as_str(), folder)).collect(); let zones: Vec = lineage .children(root) .iter() @@ -601,12 +576,7 @@ pub fn build( height: default_zone_height(notes.len(), !children.is_empty(), card), }); - BoardZone { - folder: (*folder).clone(), - frame, - notes, - children, - } + BoardZone { folder: (*folder).clone(), frame, notes, children } }) .collect(); @@ -696,10 +666,7 @@ pub fn arrange_everything( zones: folder_counts .iter() .zip(frames.iter()) - .map(|((folder_id, _), frame)| ZonePlacement { - folder_id: folder_id.clone(), - frame: *frame, - }) + .map(|((folder_id, _), frame)| ZonePlacement { folder_id: folder_id.clone(), frame: *frame }) .collect(), cards: flowed(loose_ids, loose_top(&frames), card), } @@ -710,20 +677,14 @@ pub fn arrange_everything( /// `zones` comes back empty: nothing placed or sized by hand is touched. #[must_use] pub fn arrange_loose_cards(frames: &[BoardFrame], loose_ids: &[String], card: i32) -> BoardLayout { - BoardLayout { - zones: Vec::new(), - cards: flowed(loose_ids, loose_top(frames), card), - } + BoardLayout { zones: Vec::new(), cards: flowed(loose_ids, loose_top(frames), card) } } fn flowed(loose_ids: &[String], top: i32, card: i32) -> Vec { loose_ids .iter() .zip(arrange_loose(loose_ids.len(), top, card)) - .map(|(note_id, position)| CardPlacement { - note_id: note_id.clone(), - position, - }) + .map(|(note_id, position)| CardPlacement { note_id: note_id.clone(), position }) .collect() } @@ -748,11 +709,7 @@ mod tests { } fn filed(id: &str, folder_id: Option<&str>) -> Note { - Note { - id: id.to_string(), - folder_id: folder_id.map(str::to_string), - ..note() - } + Note { id: id.to_string(), folder_id: folder_id.map(str::to_string), ..note() } } fn request(root: Option<&str>) -> BoardQuery { @@ -780,19 +737,8 @@ mod tests { ] } - fn board( - notes: Vec, - positions: &HashMap, - query: &BoardQuery, - ) -> BoardView { - build( - notes, - &folders(), - &HashMap::new(), - positions, - &Facets::default(), - query, - ) + fn board(notes: Vec, positions: &HashMap, query: &BoardQuery) -> BoardView { + build(notes, &folders(), &HashMap::new(), positions, &Facets::default(), query) } fn ids(notes: &[BoardNote]) -> Vec<&str> { @@ -800,12 +746,7 @@ mod tests { } fn frame(x: i32, y: i32, width: i32, height: i32) -> BoardFrame { - BoardFrame { - x, - y, - width, - height, - } + BoardFrame { x, y, width, height } } fn point(x: i32, y: i32) -> BoardPoint { @@ -814,11 +755,8 @@ mod tests { #[test] fn a_card_is_as_tall_as_the_lines_it_shows() { - let cases = [ - (PreviewLines::Three, 3, 120), - (PreviewLines::Four, 4, 140), - (PreviewLines::Five, 5, 160), - ]; + let cases = + [(PreviewLines::Three, 3, 120), (PreviewLines::Four, 4, 140), (PreviewLines::Five, 5, 160)]; for (lines, count, height) in cases { assert_eq!((lines.count(), lines.card_height()), (count, height)); @@ -859,10 +797,7 @@ mod tests { let space = Occupancy::on(¬es, &lineage, None); let infra = Occupancy::on(¬es, &lineage, Some("infra")); - assert_eq!( - space.per_folder, - HashMap::from([("infra".to_string(), 2), ("docs".to_string(), 1)]) - ); + assert_eq!(space.per_folder, HashMap::from([("infra".to_string(), 2), ("docs".to_string(), 1)])); assert_eq!(space.loose, ["loose"]); assert_eq!(infra.per_folder, HashMap::from([("perf".to_string(), 1)])); assert_eq!(infra.loose, ["in-infra"]); @@ -873,15 +808,9 @@ mod tests { #[test] fn a_frame_is_kept_on_the_board_and_big_enough_to_drop_a_card_into() { let cases = [ - ( - frame(-5, -1, 10, 10), - frame(0, 0, MIN_ZONE_WIDTH, MIN_ZONE_HEIGHT), - ), + (frame(-5, -1, 10, 10), frame(0, 0, MIN_ZONE_WIDTH, MIN_ZONE_HEIGHT)), (frame(40, 60, 600, 400), frame(40, 60, 600, 400)), - ( - frame(0, 0, i32::MAX, i32::MAX), - frame(0, 0, MAX_SIDE, MAX_SIDE), - ), + (frame(0, 0, i32::MAX, i32::MAX), frame(0, 0, MAX_SIDE, MAX_SIDE)), ]; for (asked, kept) in cases { @@ -894,10 +823,8 @@ mod tests { /// belong to the ground. #[test] fn a_point_falls_in_the_topmost_zone_that_holds_it() { - let frames = [ - ("under".to_string(), frame(0, 0, 100, 100)), - ("over".to_string(), frame(50, 50, 100, 100)), - ]; + let frames = + [("under".to_string(), frame(0, 0, 100, 100)), ("over".to_string(), frame(50, 50, 100, 100))]; let cases = [ (point(10, 10), Some("under")), (point(60, 60), Some("over")), @@ -933,8 +860,7 @@ mod tests { #[test] fn a_zone_is_tall_enough_for_its_rows_of_cards_and_never_less_than_one() { - let height = - |notes: usize, columns: i32, nested: bool| zone_height(notes, columns, nested, CARD); + let height = |notes: usize, columns: i32, nested: bool| zone_height(notes, columns, nested, CARD); assert_eq!(height(0, 2, false), height(1, 2, false)); assert_eq!(height(2, 2, false), height(1, 2, false)); @@ -942,19 +868,13 @@ mod tests { assert_eq!(height(2, 0, false), height(2, 1, false)); assert_eq!(height(1, 2, true) - height(1, 2, false), ZONE_SUBFOLDERS); assert_eq!(zone_height(1, 1, false, MIN_CARD_HEIGHT), MIN_ZONE_HEIGHT); - assert_eq!( - default_zone_height(3, true, CARD), - height(3, ZONE_COLUMNS, true) - ); + assert_eq!(default_zone_height(3, true, CARD), height(3, ZONE_COLUMNS, true)); } /// Three across in the order handed over; a row starts under the tallest of the one above. #[test] fn zones_are_laid_out_in_reading_order_three_across() { - let contents = [5, 0, 0, 0].map(|notes| ZoneContents { - notes, - nested: false, - }); + let contents = [5, 0, 0, 0].map(|notes| ZoneContents { notes, nested: false }); let width = default_zone_width(); let frames = arrange_zones(&contents, CARD); @@ -1002,11 +922,7 @@ mod tests { ]; for (taken, zones, seat) in cases { - assert_eq!( - free_slot(100, &taken, &zones, CARD), - seat, - "{taken:?} {zones:?}" - ); + assert_eq!(free_slot(100, &taken, &zones, CARD), seat, "{taken:?} {zones:?}"); } } @@ -1014,10 +930,7 @@ mod tests { fn a_card_with_no_seat_left_goes_under_everything() { let zone = frame(0, 0, 10_000, 5_000); - assert_eq!( - free_slot(100, &[], &[zone], CARD), - point(BOARD_MARGIN, 5_000 + GAP) - ); + assert_eq!(free_slot(100, &[], &[zone], CARD), point(BOARD_MARGIN, 5_000 + GAP)); } /// The run starts each search where the last stopped, and gives the seats one by one would. @@ -1053,23 +966,14 @@ mod tests { position: Some(point(0, 600)), }; - assert_eq!( - surface(&[], &[], CARD), - (960 + BOARD_MARGIN, 540 + BOARD_MARGIN) - ); - assert_eq!( - surface(&[zone], &[card], CARD), - (1_500 + BOARD_MARGIN, 600 + CARD + BOARD_MARGIN) - ); + assert_eq!(surface(&[], &[], CARD), (960 + BOARD_MARGIN, 540 + BOARD_MARGIN)); + assert_eq!(surface(&[zone], &[card], CARD), (1_500 + BOARD_MARGIN, 600 + CARD + BOARD_MARGIN)); } #[test] fn the_space_s_board_draws_its_top_folders_each_gathering_what_is_under_it() { - let notes = vec![ - filed("in-infra", Some("infra")), - filed("in-perf", Some("perf")), - filed("loose", None), - ]; + let notes = + vec![filed("in-infra", Some("infra")), filed("in-perf", Some("perf")), filed("loose", None)]; let view = board(notes, &HashMap::new(), &request(None)); @@ -1078,17 +982,9 @@ mod tests { .iter() .map(|zone| (zone.folder.id.as_str(), ids(&zone.notes))) .collect(); - assert_eq!( - zones, - [("infra", vec!["in-infra", "in-perf"]), ("docs", vec![])] - ); + assert_eq!(zones, [("infra", vec!["in-infra", "in-perf"]), ("docs", vec![])]); assert_eq!(ids(&view.loose), ["loose"]); - assert!( - view.zones[0] - .notes - .iter() - .all(|entry| entry.position.is_none()) - ); + assert!(view.zones[0].notes.iter().all(|entry| entry.position.is_none())); } /// Nothing from outside it: a note of a sibling folder, or loose in the space, is not drawn. @@ -1117,20 +1013,10 @@ mod tests { folder("alpha", Some("infra"), "Alpha"), folder("deep", Some("zeta"), "Deep"), ]; - let notes = vec![ - filed("a", Some("zeta")), - filed("b", Some("deep")), - filed("c", Some("infra")), - ]; + let notes = vec![filed("a", Some("zeta")), filed("b", Some("deep")), filed("c", Some("infra"))]; - let view = build( - notes, - &folders, - &HashMap::new(), - &HashMap::new(), - &Facets::default(), - &request(None), - ); + let view = + build(notes, &folders, &HashMap::new(), &HashMap::new(), &Facets::default(), &request(None)); let children: Vec<(&str, u32)> = view.zones[0] .children @@ -1145,29 +1031,13 @@ mod tests { fn a_zone_never_laid_out_is_sized_for_its_notes_and_its_sub_folders() { let stored = frame(300, 300, 600, 600); let frames = HashMap::from([("docs".to_string(), stored)]); - let notes = vec![ - filed("a", Some("infra")), - filed("b", Some("infra")), - filed("c", Some("infra")), - ]; + let notes = vec![filed("a", Some("infra")), filed("b", Some("infra")), filed("c", Some("infra"))]; - let view = build( - notes, - &folders(), - &frames, - &HashMap::new(), - &Facets::default(), - &request(None), - ); + let view = build(notes, &folders(), &frames, &HashMap::new(), &Facets::default(), &request(None)); assert_eq!( view.zones[0].frame, - frame( - BOARD_MARGIN, - BOARD_MARGIN, - default_zone_width(), - default_zone_height(3, true, CARD) - ) + frame(BOARD_MARGIN, BOARD_MARGIN, default_zone_width(), default_zone_height(3, true, CARD)) ); assert_eq!(view.zones[1].frame, stored); } @@ -1187,26 +1057,15 @@ mod tests { .collect(); assert_eq!(at["placed"], placed); let zones: Vec = view.zones.iter().map(|zone| zone.frame).collect(); - assert_eq!( - at["new"], - free_slot(loose_top(&zones), &[placed], &zones, CARD) - ); + assert_eq!(at["new"], free_slot(loose_top(&zones), &[placed], &zones, CARD)); } /// Spatial memory is what the board has that the list does not: a card is dimmed in place. #[test] fn a_card_that_does_not_match_is_dimmed_not_dropped() { - let notes = vec![ - Note { - title: "Postgres".to_string(), - ..filed("hit", Some("infra")) - }, - filed("miss", None), - ]; - let query = BoardQuery { - search: "postgres".to_string(), - ..request(None) - }; + let notes = + vec![Note { title: "Postgres".to_string(), ..filed("hit", Some("infra")) }, filed("miss", None)]; + let query = BoardQuery { search: "postgres".to_string(), ..request(None) }; let view = board(notes, &HashMap::new(), &query); @@ -1218,22 +1077,11 @@ mod tests { #[test] fn the_quick_filter_alone_counts_as_filtering() { - let cases = [ - (NoteFilter::All, false), - (NoteFilter::Pinned, true), - (NoteFilter::Untriaged, true), - ]; + let cases = [(NoteFilter::All, false), (NoteFilter::Pinned, true), (NoteFilter::Untriaged, true)]; for (filter, filtering) in cases { - let query = BoardQuery { - filter, - ..request(None) - }; - assert_eq!( - board(Vec::new(), &HashMap::new(), &query).is_filtering, - filtering, - "{filter:?}" - ); + let query = BoardQuery { filter, ..request(None) }; + assert_eq!(board(Vec::new(), &HashMap::new(), &query).is_filtering, filtering, "{filter:?}"); } } @@ -1241,10 +1089,7 @@ mod tests { fn a_pinned_card_comes_first_in_its_zone() { let notes = vec![ filed("first", Some("infra")), - Note { - pinned: true, - ..filed("pinned", Some("infra")) - }, + Note { pinned: true, ..filed("pinned", Some("infra")) }, filed("second", Some("infra")), ]; @@ -1257,25 +1102,12 @@ mod tests { #[test] fn the_rails_offer_the_space_s_tags_and_languages() { let facets = Facets { - tags: vec![FacetCount { - value: "sql".to_string(), - count: 2, - }], - languages: vec![FacetCount { - value: Language::Sql, - count: 2, - }], + tags: vec![FacetCount { value: "sql".to_string(), count: 2 }], + languages: vec![FacetCount { value: Language::Sql, count: 2 }], ..Facets::default() }; - let view = build( - Vec::new(), - &folders(), - &HashMap::new(), - &HashMap::new(), - &facets, - &request(None), - ); + let view = build(Vec::new(), &folders(), &HashMap::new(), &HashMap::new(), &facets, &request(None)); assert_eq!(view.available_tags, ["sql"]); assert_eq!(view.available_languages, [Language::Sql]); @@ -1285,10 +1117,7 @@ mod tests { #[test] fn a_card_carries_only_its_preview() { let long = Note { - content: (1..=20) - .map(|line| format!("line {line}")) - .collect::>() - .join("\n"), + content: (1..=20).map(|line| format!("line {line}")).collect::>().join("\n"), ..filed("long", None) }; @@ -1307,11 +1136,7 @@ mod tests { path: vec![id.to_string()], }; let mut view = board( - vec![ - filed("own", Some("infra")), - filed("below", Some("perf")), - filed("loose", None), - ], + vec![filed("own", Some("infra")), filed("below", Some("perf")), filed("loose", None)], &HashMap::new(), &request(None), ); @@ -1333,13 +1158,7 @@ mod tests { #[test] fn tidying_everything_lays_the_zones_out_again_and_flows_the_loose_cards_under_them() { let counts = [ - ( - "infra".to_string(), - ZoneContents { - notes: 3, - nested: true, - }, - ), + ("infra".to_string(), ZoneContents { notes: 3, nested: true }), ("docs".to_string(), ZoneContents::default()), ]; let loose = ["a".to_string(), "b".to_string()]; @@ -1347,11 +1166,8 @@ mod tests { let layout = arrange_everything(&counts, &loose, CARD); let frames = arrange_zones(&[counts[0].1, counts[1].1], CARD); - let placed: Vec<(&str, BoardFrame)> = layout - .zones - .iter() - .map(|zone| (zone.folder_id.as_str(), zone.frame)) - .collect(); + let placed: Vec<(&str, BoardFrame)> = + layout.zones.iter().map(|zone| (zone.folder_id.as_str(), zone.frame)).collect(); assert_eq!(placed, [("infra", frames[0]), ("docs", frames[1])]); let seats = arrange_loose(2, loose_top(&frames), CARD); let cards: Vec = layout.cards.iter().map(|card| card.position).collect(); diff --git a/crates/engine/src/folders/model.rs b/crates/engine/src/folders/model.rs index b54b8167b..02aa06991 100644 --- a/crates/engine/src/folders/model.rs +++ b/crates/engine/src/folders/model.rs @@ -121,25 +121,15 @@ impl Lineage { let mut lineage = Self::default(); for (id, parent) in &links { - let parent = parent - .clone() - .filter(|parent| known.contains(parent.as_str())); - lineage - .children - .entry(parent.clone()) - .or_default() - .push(id.clone()); + let parent = parent.clone().filter(|parent| known.contains(parent.as_str())); + lineage.children.entry(parent.clone()).or_default().push(id.clone()); lineage.parents.insert(id.clone(), parent); } lineage } pub fn of(folders: &[Folder]) -> Self { - Self::new( - folders - .iter() - .map(|folder| (folder.id.clone(), folder.parent_id.clone())), - ) + Self::new(folders.iter().map(|folder| (folder.id.clone(), folder.parent_id.clone()))) } pub fn contains(&self, id: &str) -> bool { @@ -152,9 +142,7 @@ impl Lineage { /// In the order the folders were handed over: creation, for the board's zones. pub fn children(&self, parent: Option<&str>) -> &[String] { - self.children - .get(&parent.map(str::to_string)) - .map_or(&[], Vec::as_slice) + self.children.get(&parent.map(str::to_string)).map_or(&[], Vec::as_slice) } /// The folder and everything under it, the folder first. A cycle a damaged row could make @@ -225,8 +213,7 @@ impl Lineage { None => return Seat::Elsewhere, }, }; - path.get(start) - .map_or(Seat::Elsewhere, |zone| Seat::Zone(zone.clone())) + path.get(start).map_or(Seat::Elsewhere, |zone| Seat::Zone(zone.clone())) } /// A folder made under `parent`: in this space, and not past [`MAX_DEPTH`]. @@ -240,20 +227,13 @@ impl Lineage { if let Some(parent) = parent && self.subtree(id).iter().any(|below| below == parent) { - return Err(ValidationError::new( - "parentId", - "a folder cannot move into itself", - )); + return Err(ValidationError::new("parentId", "a folder cannot move into itself")); } self.check_room(parent, self.height(id).max(1)) } /// A sub-tree `levels` deep arriving from another space under `parent` of this one. - pub fn check_arrival( - &self, - parent: Option<&str>, - levels: usize, - ) -> Result<(), ValidationError> { + pub fn check_arrival(&self, parent: Option<&str>, levels: usize) -> Result<(), ValidationError> { self.check_room(parent, levels) } @@ -262,17 +242,11 @@ impl Lineage { None => 0, Some(parent) if self.contains(parent) => self.depth(parent), Some(_) => { - return Err(ValidationError::new( - "parentId", - "the parent is not a folder of this space", - )); + return Err(ValidationError::new("parentId", "the parent is not a folder of this space")); } }; if above + levels > MAX_DEPTH { - return Err(ValidationError::new( - "parentId", - format!("folders nest at most {MAX_DEPTH} deep"), - )); + return Err(ValidationError::new("parentId", format!("folders nest at most {MAX_DEPTH} deep"))); } Ok(()) } @@ -293,22 +267,12 @@ mod tests { use super::*; fn tree(links: &[(&str, Option<&str>)]) -> Lineage { - Lineage::new( - links - .iter() - .map(|(id, parent)| ((*id).to_string(), parent.map(str::to_string))), - ) + Lineage::new(links.iter().map(|(id, parent)| ((*id).to_string(), parent.map(str::to_string)))) } /// a ─ b ─ c, and a ─ d, made in that order; e alone at the top. fn sample() -> Lineage { - tree(&[ - ("a", None), - ("b", Some("a")), - ("c", Some("b")), - ("d", Some("a")), - ("e", None), - ]) + tree(&[("a", None), ("b", Some("a")), ("c", Some("b")), ("d", Some("a")), ("e", None)]) } /// f1 ─ f2 ─ … ─ f8, as deep as folders nest, beside `others`. @@ -349,19 +313,13 @@ mod tests { ) .unwrap(); - assert_eq!( - (folder.parent_id, folder.colour), - (None, FolderColour::Blue) - ); + assert_eq!((folder.parent_id, folder.colour), (None, FolderColour::Blue)); } #[test] fn a_folder_s_name_is_read_trimmed_and_never_blank() { - let draft = |name: &str| FolderDraft { - space_id: "s".to_string(), - name: name.to_string(), - parent_id: None, - }; + let draft = + |name: &str| FolderDraft { space_id: "s".to_string(), name: name.to_string(), parent_id: None }; assert_eq!(draft(" Perf\t").validated_name(), Ok("Perf".to_string())); assert_eq!(validated_name(" ").unwrap_err().field, "name"); @@ -451,14 +409,8 @@ mod tests { assert_eq!(lineage.check_child(None), Ok(())); assert_eq!(lineage.check_child(Some("f7")), Ok(())); - assert_eq!( - lineage.check_child(Some("f8")).unwrap_err().field, - "parentId" - ); - assert_eq!( - lineage.check_child(Some("elsewhere")).unwrap_err().field, - "parentId" - ); + assert_eq!(lineage.check_child(Some("f8")).unwrap_err().field, "parentId"); + assert_eq!(lineage.check_child(Some("elsewhere")).unwrap_err().field, "parentId"); } #[test] @@ -466,10 +418,7 @@ mod tests { let lineage = sample(); for into in ["a", "b", "c"] { - assert_eq!( - lineage.check_move("a", Some(into)).unwrap_err().field, - "parentId" - ); + assert_eq!(lineage.check_move("a", Some(into)).unwrap_err().field, "parentId"); } assert_eq!(lineage.check_move("b", Some("e")), Ok(())); assert_eq!(lineage.check_move("b", None), Ok(())); @@ -481,19 +430,10 @@ mod tests { let lineage = deepest(&[("g", None), ("h", Some("g"))]); assert_eq!(lineage.check_move("g", Some("f6")), Ok(())); - assert_eq!( - lineage.check_move("g", Some("f7")).unwrap_err().field, - "parentId" - ); + assert_eq!(lineage.check_move("g", Some("f7")).unwrap_err().field, "parentId"); assert_eq!(lineage.check_move("h", Some("f7")), Ok(())); assert_eq!(lineage.check_move("unknown", Some("f7")), Ok(())); - assert_eq!( - lineage - .check_move("g", Some("elsewhere")) - .unwrap_err() - .field, - "parentId" - ); + assert_eq!(lineage.check_move("g", Some("elsewhere")).unwrap_err().field, "parentId"); } #[test] @@ -501,17 +441,8 @@ mod tests { let lineage = deepest(&[]); assert_eq!(lineage.check_arrival(Some("f6"), 2), Ok(())); - assert_eq!( - lineage.check_arrival(Some("f7"), 2).unwrap_err().field, - "parentId" - ); + assert_eq!(lineage.check_arrival(Some("f7"), 2).unwrap_err().field, "parentId"); assert_eq!(lineage.check_arrival(None, MAX_DEPTH), Ok(())); - assert_eq!( - lineage - .check_arrival(Some("elsewhere"), 1) - .unwrap_err() - .field, - "parentId" - ); + assert_eq!(lineage.check_arrival(Some("elsewhere"), 1).unwrap_err().field, "parentId"); } } diff --git a/crates/engine/src/folders/store.rs b/crates/engine/src/folders/store.rs index d86e3e0ec..99ca835b5 100644 --- a/crates/engine/src/folders/store.rs +++ b/crates/engine/src/folders/store.rs @@ -32,10 +32,8 @@ struct FolderRow { impl FolderRow { fn open(self, vault: &Vault) -> Result { Ok(Folder { - created_at: iso8601::parse(&self.created_at).map_err(|_| StorageError::CorruptRow { - id: self.id.clone(), - field: "createdAt", - })?, + created_at: iso8601::parse(&self.created_at) + .map_err(|_| StorageError::CorruptRow { id: self.id.clone(), field: "createdAt" })?, name: vault.open(&self.name)?, // Degrades like `notes.language`: a folder is worth more than its swatch. colour: self.colour.parse().unwrap_or_default(), @@ -122,22 +120,13 @@ pub fn by_id( .collect(); ( folder.id.clone(), - NoteFolder { - id: folder.id.clone(), - name: folder.name.clone(), - colour: folder.colour, - path, - }, + NoteFolder { id: folder.id.clone(), name: folder.name.clone(), colour: folder.colour, path }, ) }) .collect()) } -fn find( - connection: &mut SqliteConnection, - vault: &Vault, - id: &str, -) -> Result { +fn find(connection: &mut SqliteConnection, vault: &Vault, id: &str) -> Result { folders::table .find(id) .select(FolderRow::as_select()) @@ -158,11 +147,7 @@ pub fn exists(connection: &mut SqliteConnection, id: &str) -> Result Result { +pub fn belongs_to(connection: &mut SqliteConnection, id: &str, space_id: &str) -> Result { Ok(folders::table .find(id) .filter(folders::space_id.eq(space_id)) @@ -201,9 +186,7 @@ pub fn create( name: &str, now: DateTime, ) -> Result { - connection.transaction(|connection, vault| { - create_in(connection, vault, space_id, parent_id, name, now) - }) + connection.transaction(|connection, vault| create_in(connection, vault, space_id, parent_id, name, now)) } /// For a caller already inside a transaction — an import creates the folders it needs. @@ -252,31 +235,17 @@ pub(crate) fn create_in( pub fn rename(connection: &mut Library, id: &str, name: &str) -> Result { connection.transaction(|connection, vault| { let folder = find(connection, vault, id)?; - ensure_unique_name( - connection, - vault, - &folder.space_id, - folder.parent_id.as_deref(), - name, - Some(id), - )?; + ensure_unique_name(connection, vault, &folder.space_id, folder.parent_id.as_deref(), name, Some(id))?; diesel::update(folders::table.find(id)) .set(folders::name.eq(vault.seal(name)?)) .execute(connection)?; - Ok(Folder { - name: name.to_string(), - ..folder - }) + Ok(Folder { name: name.to_string(), ..folder }) }) } -pub fn recolour( - connection: &mut Library, - id: &str, - colour: FolderColour, -) -> Result { +pub fn recolour(connection: &mut Library, id: &str, colour: FolderColour) -> Result { connection.transaction(|connection, vault| { diesel::update(folders::table.find(id)) .set(folders::colour.eq(colour.as_str())) @@ -313,14 +282,7 @@ pub fn move_to( } else { lineage(connection, space_id)?.check_arrival(parent_id, from.height(id).max(1))?; } - ensure_unique_name( - connection, - vault, - space_id, - parent_id, - &folder.name, - Some(id), - )?; + ensure_unique_name(connection, vault, space_id, parent_id, &folder.name, Some(id))?; if folder.space_id != space_id { was.notes = cross(connection, &from.subtree(id), space_id)?; } @@ -333,10 +295,7 @@ pub fn move_to( /// The undo of [`move_to`]: back under the parent it left, in its space and in the frame it /// had; `None` when a parent deleted since, or one it now holds, leaves it where it is. The /// notes that went back: every note filed in it, none left in a folder of another space. -pub fn move_back( - connection: &mut Library, - was: &FolderMove, -) -> Result>, StorageError> { +pub fn move_back(connection: &mut Library, was: &FolderMove) -> Result>, StorageError> { connection.transaction(|connection, vault| { let folder = find(connection, vault, &was.folder_id)?; let here = lineage(connection, &folder.space_id)?; @@ -344,17 +303,10 @@ pub fn move_back( let room = if folder.space_id == was.space_id { here.check_move(&folder.id, parent) } else { - lineage(connection, &was.space_id)? - .check_arrival(parent, here.height(&folder.id).max(1)) + lineage(connection, &was.space_id)?.check_arrival(parent, here.height(&folder.id).max(1)) }; - let named = ensure_unique_name( - connection, - vault, - &was.space_id, - parent, - &folder.name, - Some(&folder.id), - ); + let named = + ensure_unique_name(connection, vault, &was.space_id, parent, &folder.name, Some(&folder.id)); if room.is_err() || named.is_err() { return Ok(None); } @@ -414,10 +366,7 @@ fn place( /// What it held goes to its parent — its notes, filed there, and its sub-folders, each to a /// free slot on that board — or loose at the top of the space. `updated_at` is not touched: /// the user aimed at the folder. -pub fn contents( - connection: &mut Library, - id: &str, -) -> Result { +pub fn contents(connection: &mut Library, id: &str) -> Result { let (connection, _vault) = connection.split(); let under = lineage_of(connection, id)?.subtree(id); Ok(super::model::FolderContents { @@ -591,20 +540,13 @@ pub fn move_into( .load::<(String, String, Option)>(connection)? .into_iter() .filter(|(_, _, current)| current.as_deref() != Some(folder_id)) - .map(|(note_id, space_id, folder_id)| NotePlacement { - note_id, - space_id, - folder_id, - }) + .map(|(note_id, space_id, folder_id)| NotePlacement { note_id, space_id, folder_id }) .collect(); let touched: Vec = moved.iter().map(|one| one.note_id.clone()).collect(); board::forget_positions(connection, &touched)?; diesel::update(notes::table.filter(notes::id.eq_any(&touched))) - .set(( - notes::space_id.eq(space_id), - notes::folder_id.eq(Some(folder_id)), - )) + .set((notes::space_id.eq(space_id), notes::folder_id.eq(Some(folder_id)))) .execute(connection)?; let lineage = lineage_of(connection, folder_id)?; @@ -615,10 +557,7 @@ pub fn move_into( } /// How many live notes these folders hold, which is what a zone has to be tall enough for. -fn count_filed( - connection: &mut SqliteConnection, - folder_ids: &[String], -) -> Result { +fn count_filed(connection: &mut SqliteConnection, folder_ids: &[String]) -> Result { let count: i64 = notes::table .filter(notes::folder_id.eq_any(folder_ids)) .filter(notes::deleted_at.is_null()) @@ -640,10 +579,7 @@ pub fn restore_filings( connection.transaction(|connection, _vault| { let mut restored = 0; - let ids: Vec = filings - .iter() - .map(|filing| filing.note_id.clone()) - .collect(); + let ids: Vec = filings.iter().map(|filing| filing.note_id.clone()).collect(); board::forget_positions(connection, &ids)?; for filing in filings { @@ -654,13 +590,10 @@ pub fn restore_filings( continue; } - restored += diesel::update( - notes::table - .find(&filing.note_id) - .filter(notes::deleted_at.is_null()), - ) - .set(notes::folder_id.eq(filing.folder_id.as_deref())) - .execute(connection)?; + restored += + diesel::update(notes::table.find(&filing.note_id).filter(notes::deleted_at.is_null())) + .set(notes::folder_id.eq(filing.folder_id.as_deref())) + .execute(connection)?; } // Undoing puts notes back into zones that may no longer be tall enough for them; a diff --git a/crates/engine/src/folders/store/board.rs b/crates/engine/src/folders/store/board.rs index e6a6cb024..34370fdea 100644 --- a/crates/engine/src/folders/store/board.rs +++ b/crates/engine/src/folders/store/board.rs @@ -10,8 +10,8 @@ use crate::db::Library; use crate::db::schema::{folders, note_positions, notes}; use crate::error::StorageError; use crate::folders::board::{ - self, BoardArrangement, BoardFrame, BoardLayout, BoardPoint, BoardScope, CardPlacement, - Occupancy, ZoneContents, ZonePlacement, + self, BoardArrangement, BoardFrame, BoardLayout, BoardPoint, BoardScope, CardPlacement, Occupancy, + ZoneContents, ZonePlacement, }; /// What a board read resolves before anything can be drawn: where each zone sits, and @@ -23,12 +23,7 @@ type FrameColumns = (Option, Option, Option, Option); /// All four columns move together: a half-laid-out folder is not a state, and a folder /// never laid out answers `None`. fn frame_from((x, y, width, height): FrameColumns) -> Option { - Some(BoardFrame { - x: x?, - y: y?, - width: width?, - height: height?, - }) + Some(BoardFrame { x: x?, y: y?, width: width?, height: height? }) } pub fn frames( @@ -37,10 +32,7 @@ pub fn frames( ) -> Result, StorageError> { let rows = folders::table .filter(folders::space_id.eq(space_id)) - .select(( - folders::id, - (folders::x, folders::y, folders::w, folders::h), - )) + .select((folders::id, (folders::x, folders::y, folders::w, folders::h))) .load::<(String, FrameColumns)>(connection)?; Ok(rows @@ -81,14 +73,7 @@ pub fn grow_to_fit( return Ok(()); } - set_frame( - connection, - folder_id, - board::clamp(BoardFrame { - height: needed, - ..frame - }), - ) + set_frame(connection, folder_id, board::clamp(BoardFrame { height: needed, ..frame })) } pub fn set_frame( @@ -116,23 +101,13 @@ pub fn positions( ) -> Result, StorageError> { let rows = note_positions::table .filter( - note_positions::note_id.eq_any( - notes::table - .select(notes::id) - .filter(notes::space_id.eq(space_id.to_string())), - ), + note_positions::note_id + .eq_any(notes::table.select(notes::id).filter(notes::space_id.eq(space_id.to_string()))), ) - .select(( - note_positions::note_id, - note_positions::x, - note_positions::y, - )) + .select((note_positions::note_id, note_positions::x, note_positions::y)) .load::<(String, i32, i32)>(connection)?; - Ok(rows - .into_iter() - .map(|(note_id, x, y)| (note_id, BoardPoint { x, y })) - .collect()) + Ok(rows.into_iter().map(|(note_id, x, y)| (note_id, BoardPoint { x, y })).collect()) } pub fn set_position( @@ -152,10 +127,7 @@ pub fn set_position( } /// A row exists only for a loose note: filing one drops it, since a filed card flows. -pub fn forget_positions( - connection: &mut SqliteConnection, - note_ids: &[String], -) -> Result<(), StorageError> { +pub fn forget_positions(connection: &mut SqliteConnection, note_ids: &[String]) -> Result<(), StorageError> { if note_ids.is_empty() { return Ok(()); } @@ -183,11 +155,7 @@ pub fn save_layout( if !crate::folders::store::exists(connection, &placement.folder_id)? { return Err(StorageError::FolderNotFound(placement.folder_id.clone())); } - set_frame( - connection, - &placement.folder_id, - board::clamp(placement.frame), - )?; + set_frame(connection, &placement.folder_id, board::clamp(placement.frame))?; } // ⚠️ Only a note filed in the root has a place on its board: one filed elsewhere between @@ -207,11 +175,7 @@ pub fn save_layout( continue; } - set_position( - connection, - &placement.note_id, - board::clamp_point(placement.position), - )?; + set_position(connection, &placement.note_id, board::clamp_point(placement.position))?; } Ok(()) @@ -240,10 +204,8 @@ pub fn geometry( stored_positions.retain(|id, _| loose.contains(id.as_str())); let folder_ids: Vec<&String> = zones.iter().map(|(id, _)| id).collect(); - let missing: Vec<&&String> = folder_ids - .iter() - .filter(|id| !stored_frames.contains_key(**id)) - .collect(); + let missing: Vec<&&String> = + folder_ids.iter().filter(|id| !stored_frames.contains_key(**id)).collect(); if !missing.is_empty() { // Against every zone, so one added later takes its reading-order slot rather @@ -348,11 +310,7 @@ fn loose_ids( }; Ok(query - .order(( - notes::pinned.desc(), - notes::updated_at.desc(), - notes::id.asc(), - )) + .order((notes::pinned.desc(), notes::updated_at.desc(), notes::id.asc())) .select(notes::id) .load::(connection)?) } @@ -387,28 +345,19 @@ pub fn arrange( }; for placement in &next.zones { - set_frame( - connection, - &placement.folder_id, - board::clamp(placement.frame), - )?; + set_frame(connection, &placement.folder_id, board::clamp(placement.frame))?; } for placement in &next.cards { - set_position( - connection, - &placement.note_id, - board::clamp_point(placement.position), - )?; + set_position(connection, &placement.note_id, board::clamp_point(placement.position))?; } let zones: Vec = next .zones .iter() .filter_map(|placement| { - before.get(&placement.folder_id).map(|frame| ZonePlacement { - folder_id: placement.folder_id.clone(), - frame: *frame, - }) + before + .get(&placement.folder_id) + .map(|frame| ZonePlacement { folder_id: placement.folder_id.clone(), frame: *frame }) }) .collect(); let cards: Vec = next @@ -417,34 +366,27 @@ pub fn arrange( .filter_map(|placement| { places .get(&placement.note_id) - .map(|position| CardPlacement { - note_id: placement.note_id.clone(), - position: *position, - }) + .map(|position| CardPlacement { note_id: placement.note_id.clone(), position: *position }) }) .collect(); let moved = zones .iter() .filter(|was| { - next.zones.iter().any(|now| { - now.folder_id == was.folder_id && board::clamp(now.frame) != was.frame - }) + next.zones + .iter() + .any(|now| now.folder_id == was.folder_id && board::clamp(now.frame) != was.frame) }) .count() + cards .iter() .filter(|was| { next.cards.iter().any(|now| { - now.note_id == was.note_id - && board::clamp_point(now.position) != was.position + now.note_id == was.note_id && board::clamp_point(now.position) != was.position }) }) .count(); - Ok(BoardArrangement { - moved: saturating_u32(moved), - previous: BoardLayout { zones, cards }, - }) + Ok(BoardArrangement { moved: saturating_u32(moved), previous: BoardLayout { zones, cards } }) }) } diff --git a/crates/engine/src/host.rs b/crates/engine/src/host.rs index db12d7fee..49044492a 100644 --- a/crates/engine/src/host.rs +++ b/crates/engine/src/host.rs @@ -42,10 +42,7 @@ pub struct RecordingSink(Mutex>); impl RecordingSink { pub fn events(&self) -> Vec { - self.0 - .lock() - .map(|events| events.clone()) - .unwrap_or_default() + self.0.lock().map(|events| events.clone()).unwrap_or_default() } } @@ -65,11 +62,7 @@ mod tests { fn finished(id: &str) -> EngineEvent { EngineEvent::Run(RunEvent { id: id.to_string(), - step: RunStep::Finished { - cancelled: false, - millis: 1, - capped: false, - }, + step: RunStep::Finished { cancelled: false, millis: 1, capped: false }, }) } diff --git a/crates/engine/src/http.rs b/crates/engine/src/http.rs index 818b659ac..927123b36 100644 --- a/crates/engine/src/http.rs +++ b/crates/engine/src/http.rs @@ -48,17 +48,11 @@ pub fn http_tree(engine: &Engine) -> Result { } /// The palette's requests, ranked here: the URL is read from each sealed document. -pub fn search_http_requests( - engine: &Engine, - search: &str, -) -> Result, AppError> { +pub fn search_http_requests(engine: &Engine, search: &str) -> Result, AppError> { let db = &engine.db; let mut connection = lock(db)?; - Ok(search::rank( - store::search_candidates(&mut connection)?, - search, - )) + Ok(search::rank(store::search_candidates(&mut connection)?, search)) } pub fn create_http_collection(engine: &Engine, name: &str) -> Result { @@ -67,11 +61,7 @@ pub fn create_http_collection(engine: &Engine, name: &str) -> Result Result { +pub fn create_http_request(engine: &Engine, draft: &HttpRequestDraft) -> Result { let db = &engine.db; let name = model::validated_name(&draft.name)?; let mut connection = lock(db)?; - Ok(store::create_request( - &mut connection, - draft, - &name, - Utc::now(), - )?) + Ok(store::create_request(&mut connection, draft, &name, Utc::now())?) } /// The first save of a request where nothing holds it yet: what `create` names is created @@ -121,16 +103,8 @@ pub fn create_http_request_in( ) -> Result { let db = &engine.db; let name = model::validated_name(&draft.name)?; - let collection = create - .collection - .as_deref() - .map(model::validated_name) - .transpose()?; - let folder = create - .folder - .as_deref() - .map(model::validated_name) - .transpose()?; + let collection = create.collection.as_deref().map(model::validated_name).transpose()?; + let folder = create.folder.as_deref().map(model::validated_name).transpose()?; let mut connection = lock(db)?; @@ -157,21 +131,11 @@ pub fn save_http_request( patch: &HttpRequestPatch, ) -> Result { let db = &engine.db; - let name = patch - .name - .as_deref() - .map(model::validated_name) - .transpose()?; + let name = patch.name.as_deref().map(model::validated_name).transpose()?; let mut connection = lock(db)?; - Ok(store::save_request( - &mut connection, - id, - patch, - name.as_deref(), - Utc::now(), - )?) + Ok(store::save_request(&mut connection, id, patch, name.as_deref(), Utc::now())?) } pub fn rename_http_item(engine: &Engine, item: &HttpItem, name: &str) -> Result<(), AppError> { @@ -199,11 +163,7 @@ pub fn delete_http_item(engine: &Engine, item: &HttpItem) -> Result<(), AppError } /// The copy's name comes from the front: no user-visible word is Rust's. -pub fn duplicate_http_item( - engine: &Engine, - item: &HttpItem, - name: &str, -) -> Result { +pub fn duplicate_http_item(engine: &Engine, item: &HttpItem, name: &str) -> Result { let db = &engine.db; let name = model::validated_name(name)?; @@ -219,10 +179,7 @@ pub fn move_http_item(engine: &Engine, item: &HttpItem, place: &HttpPlace) -> Re Ok(store::move_item(&mut connection, item, place)?) } -pub fn http_settings( - engine: &Engine, - item: &HttpItem, -) -> Result { +pub fn http_settings(engine: &Engine, item: &HttpItem) -> Result { let db = &engine.db; let mut connection = lock(db)?; @@ -252,10 +209,8 @@ pub fn save_http_settings( let mut connection = lock(db)?; // The dialog does not hold the run order: the one the runner left is kept. - let settings = model::ContainerSettings { - run_order: store::settings(&mut connection, item)?.run_order, - ..settings - }; + let settings = + model::ContainerSettings { run_order: store::settings(&mut connection, item)?.run_order, ..settings }; Ok(store::save_settings(&mut connection, item, &settings)?) } @@ -269,11 +224,7 @@ pub fn inherited_http_settings( let db = &engine.db; let mut connection = lock(db)?; - Ok(store::inherited( - &mut connection, - collection_id, - folder_id.map(std::string::String::as_str), - )?) + Ok(store::inherited(&mut connection, collection_id, folder_id.map(std::string::String::as_str))?) } /// What a body implies, whether a JSON one reads, and whether its method seldom carries one: @@ -304,9 +255,7 @@ pub struct BodyAnswer { /// Each header's fault by its rank, or none: the table marks the row and says why. The rule is /// the model's; the table holds none. -pub fn check_http_headers( - rows: &[model::KeyValue], -) -> Result>, AppError> { +pub fn check_http_headers(rows: &[model::KeyValue]) -> Result>, AppError> { Ok(model::header_faults(rows)) } @@ -329,11 +278,7 @@ pub fn implied_http_headers( let inherited = match collection_id { Some(collection_id) => { let mut connection = lock(db)?; - store::inherited( - &mut connection, - &collection_id, - folder_id.map(std::string::String::as_str), - )? + store::inherited(&mut connection, &collection_id, folder_id.map(std::string::String::as_str))? } None => settings::inherit(&[]), }; @@ -388,12 +333,7 @@ fn resolver_for( inherited: &settings::Inherited, environment_id: Option<&str>, ) -> Result { - Ok(variables::Resolver::new(&layers_for( - connection, - own, - inherited, - environment_id, - )?)) + Ok(variables::Resolver::new(&layers_for(connection, own, inherited, environment_id)?)) } fn layers_for( @@ -405,11 +345,8 @@ fn layers_for( use variables::{VariableLayer, VariableScope}; let sets = environments::store::list(connection)?; - let mut layers = vec![VariableLayer { - scope: VariableScope::Request, - from: String::new(), - variables: own.to_vec(), - }]; + let mut layers = + vec![VariableLayer { scope: VariableScope::Request, from: String::new(), variables: own.to_vec() }]; layers.extend(inherited.variables.iter().cloned()); if let Some(environment) = sets .environments @@ -437,31 +374,12 @@ pub fn generate_http_code( request: CodeRequestOf, ) -> Result { let db = &engine.db; - let CodeRequestOf { - target, - options, - kind, - method, - document, - collection_id, - folder_id, - environment_id, - } = request; + let CodeRequestOf { target, options, kind, method, document, collection_id, folder_id, environment_id } = + request; let mut connection = lock(db)?; - let inherited = inherited_of( - &mut connection, - collection_id.as_deref(), - folder_id.as_deref(), - )?; - let layers = layers_for( - &mut connection, - &document.variables, - &inherited, - environment_id.as_deref(), - )?; - Ok(codegen::generate( - target, options, kind, method, &document, &inherited, &layers, - )) + let inherited = inherited_of(&mut connection, collection_id.as_deref(), folder_id.as_deref())?; + let layers = layers_for(&mut connection, &document.variables, &inherited, environment_id.as_deref())?; + Ok(codegen::generate(target, options, kind, method, &document, &inherited, &layers)) } #[derive(Debug, Clone)] @@ -483,25 +401,10 @@ pub fn http_variables( request: VariablesRequest, ) -> Result, AppError> { let db = &engine.db; - let VariablesRequest { - kind, - document, - collection_id, - folder_id, - environment_id, - } = request; + let VariablesRequest { kind, document, collection_id, folder_id, environment_id } = request; let mut connection = lock(db)?; - let inherited = inherited_of( - &mut connection, - collection_id.as_deref(), - folder_id.as_deref(), - )?; - let resolver = resolver_for( - &mut connection, - &document.variables, - &inherited, - environment_id.as_deref(), - )?; + let inherited = inherited_of(&mut connection, collection_id.as_deref(), folder_id.as_deref())?; + let resolver = resolver_for(&mut connection, &document.variables, &inherited, environment_id.as_deref())?; Ok(resolver.used(&variables::texts(kind, &document, &inherited))) } @@ -522,10 +425,7 @@ pub fn http_run_order(engine: &Engine, item: &HttpItem) -> Result Result<(), AppError> { let db = &engine.db; let mut connection = lock(db)?; - let settings = model::ContainerSettings { - run_order: order, - ..store::settings(&mut connection, item)? - }; + let settings = model::ContainerSettings { run_order: order, ..store::settings(&mut connection, item)? }; Ok(store::save_settings(&mut connection, item, &settings)?) } @@ -547,10 +444,7 @@ pub fn save_http_run_order( /// A collection or a folder run, one request after the other, each sent as a send is — its /// scripts, its tests, its extractions — but written in no history. Each step is said as an /// event; answers once the run is over. The lock is held for reads alone, never over a send. -pub async fn run_http_collection( - engine: Arc, - run: runner::RunRequest, -) -> Result<(), AppError> { +pub async fn run_http_collection(engine: Arc, run: runner::RunRequest) -> Result<(), AppError> { let tree = db::run(Arc::clone(&engine), |engine| { let db = &engine.db; let mut connection = lock(db)?; @@ -563,16 +457,9 @@ pub async fn run_http_collection( .iter() .filter_map(|id| placed.iter().find(|known| &known.id == id).cloned()) .collect(); - let rows = run - .data - .as_ref() - .map(|data| data.rows.clone()) - .unwrap_or_default(); - let iterations = if rows.is_empty() { - run.iterations.max(1) - } else { - u32::try_from(rows.len()).unwrap_or(u32::MAX) - }; + let rows = run.data.as_ref().map(|data| data.rows.clone()).unwrap_or_default(); + let iterations = + if rows.is_empty() { run.iterations.max(1) } else { u32::try_from(rows.len()).unwrap_or(u32::MAX) }; let runs = &engine.runs; runs.start(&run.id); let started = std::time::Instant::now(); @@ -589,27 +476,13 @@ pub async fn run_http_collection( } steps += 1; let placed = &order[index]; - let step = RunStep { - run: &run, - iteration, - iterations, - index, - steps, - placed, - row: &row, - }; + let step = RunStep { run: &run, iteration, iterations, index, steps, placed, row: &row }; let Some((result, next)) = run_step(&engine, step, &mut overlay).await else { cancelled = true; break 'run; }; let failed = result.failed(); - say_run( - &engine, - &run.id, - runner::RunStep::Ended { - result: Box::new(result), - }, - ); + say_run(&engine, &run.id, runner::RunStep::Ended { result: Box::new(result) }); if run.stop_on_failure && failed { break 'run; } @@ -630,15 +503,7 @@ pub async fn run_http_collection( } runs.finish(&run.id); let millis = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX); - say_run( - &engine, - &run.id, - runner::RunStep::Finished { - cancelled, - millis, - capped, - }, - ); + say_run(&engine, &run.id, runner::RunStep::Finished { cancelled, millis, capped }); Ok(()) } @@ -665,11 +530,7 @@ pub fn cancel_http_send(engine: &Engine, id: &str) -> Result { } /// The whole body of the last answer to `id`, not the text shown: `false` when there is none. -pub async fn save_http_response( - engine: Arc, - id: String, - path: String, -) -> Result { +pub async fn save_http_response(engine: Arc, id: String, path: String) -> Result { crate::transfer::model::validate_path(&path)?; off_thread(move || engine.sending.save(&id, Path::new(&path)).context(&path)) .await? @@ -683,10 +544,7 @@ pub fn forget_http_response(engine: &Engine, id: &str) -> Result<(), AppError> { } /// The last answer to `id` as an image to show, when it is one. -pub async fn http_response_image( - engine: Arc, - id: String, -) -> Result, AppError> { +pub async fn http_response_image(engine: Arc, id: String) -> Result, AppError> { off_thread(move || engine.sending.image(&id)).await } @@ -701,17 +559,11 @@ pub async fn http_response_note( } /// What was sent, newest first, a group a local day. -pub fn http_history( - engine: &Engine, - tz_offset_minutes: i32, -) -> Result, AppError> { +pub fn http_history(engine: &Engine, tz_offset_minutes: i32) -> Result, AppError> { let db = &engine.db; let mut connection = lock(db)?; - Ok(history::by_day( - history::store::list(&mut connection)?, - tz_offset_minutes, - )) + Ok(history::by_day(history::store::list(&mut connection)?, tz_offset_minutes)) } pub fn http_history_entry(engine: &Engine, id: &str) -> Result { @@ -737,20 +589,14 @@ pub fn clear_http_history(engine: &Engine) -> Result { } /// One entry gone, answered whole: its undo hands it back to `restore_http_history_entry`. -pub fn delete_http_history_entry( - engine: &Engine, - id: &str, -) -> Result { +pub fn delete_http_history_entry(engine: &Engine, id: &str) -> Result { let db = &engine.db; let mut connection = lock(db)?; Ok(history::store::delete(&mut connection, id)?) } -pub fn restore_http_history_entry( - engine: &Engine, - entry: &history::HistoryEntry, -) -> Result<(), AppError> { +pub fn restore_http_history_entry(engine: &Engine, entry: &history::HistoryEntry) -> Result<(), AppError> { let db = &engine.db; let mut connection = lock(db)?; @@ -775,11 +621,7 @@ pub fn http_history_onto_request( Err(crate::error::StorageError::HttpItemNotFound(_)) => return Ok(None), Err(error) => return Err(error.into()), }; - let above = store::inherited( - &mut connection, - ¤t.collection_id, - current.folder_id.as_deref(), - )?; + let above = store::inherited(&mut connection, ¤t.collection_id, current.folder_id.as_deref())?; Ok(Some(history::onto(&entry, ¤t, &above.headers))) } @@ -788,16 +630,11 @@ pub fn http_history_draft(engine: &Engine, id: &str) -> Result Result { +pub fn describe_graphql(document: &graphql::GraphqlDocument) -> Result { Ok(graphql::describe(document)) } @@ -818,54 +655,26 @@ pub struct WebsocketRequest { /// Its headers and auth composed like a request's, under the lock for what it inherits; the /// handshake waited on without it. Answers once the socket is open. -pub async fn connect_websocket( - engine: Arc, - request: WebsocketRequest, -) -> Result<(), AppError> { - let WebsocketRequest { - id, - mut document, - collection_id, - folder_id, - environment_id, - } = request; +pub async fn connect_websocket(engine: Arc, request: WebsocketRequest) -> Result<(), AppError> { + let WebsocketRequest { id, mut document, collection_id, folder_id, environment_id } = request; document.body = model::RequestBody::None; let outgoing = db::run(Arc::clone(&engine), move |engine| { let db = &engine.db; let mut connection = lock(db)?; - let inherited = inherited_of( - &mut connection, - collection_id.as_deref(), - folder_id.as_deref(), - )?; - let resolver = resolver_for( - &mut connection, - &document.variables, - &inherited, - environment_id.as_deref(), - )?; + let inherited = inherited_of(&mut connection, collection_id.as_deref(), folder_id.as_deref())?; + let resolver = + resolver_for(&mut connection, &document.variables, &inherited, environment_id.as_deref())?; let (mut document, inherited) = variables::resolve(&document, &inherited, &resolver); document.url = websocket::socket_url(&document.url)?; - Ok(send::compose( - model::RequestKind::Http, - model::HttpMethod::Get, - &document, - &inherited, - ) - .map(|outgoing| (outgoing, document.websocket.protocols))?) + Ok(send::compose(model::RequestKind::Http, model::HttpMethod::Get, &document, &inherited) + .map(|outgoing| (outgoing, document.websocket.protocols))?) }) .await?; let (outgoing, protocols) = outgoing; Ok(engine .sockets - .connect( - &engine.runtime, - Arc::clone(&engine.events), - id, - outgoing, - &protocols, - ) + .connect(&engine.runtime, Arc::clone(&engine.events), id, outgoing, &protocols) .await?) } @@ -923,20 +732,13 @@ pub fn http_environments(engine: &Engine) -> Result Result { +pub fn create_http_environment(engine: &Engine, name: &str) -> Result { let db = &engine.db; let name = environments::validated_name(name)?; let mut connection = lock(db)?; - Ok(environments::store::create( - &mut connection, - &name, - Utc::now(), - )?) + Ok(environments::store::create(&mut connection, &name, Utc::now())?) } pub fn save_http_environment( @@ -945,20 +747,11 @@ pub fn save_http_environment( patch: &environments::EnvironmentPatch, ) -> Result { let db = &engine.db; - let name = patch - .name - .as_deref() - .map(environments::validated_name) - .transpose()?; + let name = patch.name.as_deref().map(environments::validated_name).transpose()?; let mut connection = lock(db)?; - Ok(environments::store::save( - &mut connection, - id, - patch, - name.as_deref(), - )?) + Ok(environments::store::save(&mut connection, id, patch, name.as_deref())?) } pub fn save_http_globals( @@ -968,11 +761,7 @@ pub fn save_http_globals( let db = &engine.db; let mut connection = lock(db)?; - Ok(environments::store::save_globals( - &mut connection, - variables, - Utc::now(), - )?) + Ok(environments::store::save_globals(&mut connection, variables, Utc::now())?) } /// The copy's name comes from the front: no user-visible word is Rust's. @@ -986,12 +775,7 @@ pub fn duplicate_http_environment( let mut connection = lock(db)?; - Ok(environments::store::duplicate( - &mut connection, - id, - &name, - Utc::now(), - )?) + Ok(environments::store::duplicate(&mut connection, id, &name, Utc::now())?) } pub fn delete_http_environment(engine: &Engine, id: &str) -> Result<(), AppError> { diff --git a/crates/engine/src/http/codegen.rs b/crates/engine/src/http/codegen.rs index 13ad8efb9..3ed77c8df 100644 --- a/crates/engine/src/http/codegen.rs +++ b/crates/engine/src/http/codegen.rs @@ -167,11 +167,7 @@ impl CodeRequest { /// starting on a variable left unresolved is written as typed: `{{base}}` holds its own scheme. fn with_scheme(url: &str) -> String { let url = url.trim(); - if url.contains("://") || url.starts_with("{{") { - url.to_string() - } else { - format!("http://{url}") - } + if url.contains("://") || url.starts_with("{{") { url.to_string() } else { format!("http://{url}") } } fn append_query(url: &mut String, pairs: &[(&str, &str)]) { @@ -195,11 +191,7 @@ pub fn request_of( ) -> CodeRequest { let mut url = with_scheme(&document.url); let auth = send::auth_of(document, inherited); - if let RequestAuth::ApiKey { - name, - value, - place: KeyPlace::Query, - } = auth + if let RequestAuth::ApiKey { name, value, place: KeyPlace::Query } = auth && !name.trim().is_empty() { append_query(&mut url, &[(name.trim(), value)]); @@ -215,12 +207,7 @@ pub fn request_of( if let Some(variables) = variables { pairs.push(("variables", variables)); } - if let Some(name) = document - .graphql - .operation_name - .as_deref() - .filter(|name| !name.is_empty()) - { + if let Some(name) = document.graphql.operation_name.as_deref().filter(|name| !name.is_empty()) { pairs.push(("operationName", name)); } append_query(&mut url, &pairs); @@ -228,10 +215,7 @@ pub fn request_of( } RequestKind::Graphql => { let variables = graphql::variables(&document.graphql).ok().flatten(); - ( - HttpMethod::Post, - CodeBody::Text(graphql::body(&document.graphql, variables)), - ) + (HttpMethod::Post, CodeBody::Text(graphql::body(&document.graphql, variables))) } RequestKind::Http | RequestKind::Websocket => (method, body_of(&document.body)), }; @@ -248,9 +232,7 @@ pub fn request_of( fn body_of(body: &RequestBody) -> CodeBody { match body { RequestBody::None => CodeBody::None, - RequestBody::Json { text } | RequestBody::Text { text } if text.is_empty() => { - CodeBody::None - } + RequestBody::Json { text } | RequestBody::Text { text } if text.is_empty() => CodeBody::None, RequestBody::Json { text } | RequestBody::Text { text } => CodeBody::Text(text.clone()), RequestBody::Form { fields } => CodeBody::Form( fields @@ -316,22 +298,13 @@ pub fn generate( } } let (document, inherited) = if options.resolve_variables { - let resolver = if options.include_secrets { - everything - } else { - Resolver::new(&without_secrets(layers)) - }; + let resolver = + if options.include_secrets { everything } else { Resolver::new(&without_secrets(layers)) }; variables::resolve(document, inherited, &resolver) } else { (document.clone(), inherited.clone()) }; - let request = request_of( - kind, - method, - &document, - &inherited, - options.follow_redirects, - ); + let request = request_of(kind, method, &document, &inherited, options.follow_redirects); let notice = (!target.sends_multipart() && matches!(request.body, CodeBody::Multipart(_))) .then_some(CodeNotice::MultipartUnsupported); let code = match target { @@ -356,13 +329,7 @@ pub fn generate( CodeTarget::Dart => dart::write(&request), CodeTarget::Elixir => req::write(&request), }; - GeneratedCode { - code, - language: target.language(), - secrets, - unresolved, - notice, - } + GeneratedCode { code, language: target.language(), secrets, unresolved, notice } } /// `'…'` for a POSIX shell: a quote inside closes, escapes and reopens. @@ -388,13 +355,7 @@ pub fn shell_lines(first: &str, arguments: &[String], multiline: bool) -> String lines .iter() .enumerate() - .map(|(at, line)| { - if at == last { - line.clone() - } else { - format!("{line} \\") - } - }) + .map(|(at, line)| if at == last { line.clone() } else { format!("{line} \\") }) .collect::>() .join("\n") } @@ -423,10 +384,7 @@ pub(crate) mod golden { url: "https://api.exemple.fr/customers/cus_42/invoices?page=1&limit=50".to_string(), headers: vec![ ("Accept".to_string(), "application/json".to_string()), - ( - "Authorization".to_string(), - "Bearer {{accessToken}}".to_string(), - ), + ("Authorization".to_string(), "Bearer {{accessToken}}".to_string()), ], basic: None, body: CodeBody::None, @@ -443,10 +401,7 @@ pub(crate) mod golden { let form = CodeRequest { method: HttpMethod::Post, url: "https://auth.exemple.fr/token".to_string(), - headers: vec![( - "Content-Type".to_string(), - "application/x-www-form-urlencoded".to_string(), - )], + headers: vec![("Content-Type".to_string(), "application/x-www-form-urlencoded".to_string())], basic: Some(("billing-web".to_string(), "{{clientSecret}}".to_string())), body: CodeBody::Form(vec![ ("grant_type".to_string(), "client_credentials".to_string()), @@ -460,11 +415,7 @@ pub(crate) mod golden { headers: Vec::new(), basic: None, body: CodeBody::Multipart(vec![ - CodePart { - name: "title".to_string(), - value: "Facture".to_string(), - file: false, - }, + CodePart { name: "title".to_string(), value: "Facture".to_string(), file: false }, CodePart { name: "scan".to_string(), value: "C:/Users/ada/facture.pdf".to_string(), @@ -476,21 +427,12 @@ pub(crate) mod golden { let file = CodeRequest { method: HttpMethod::Post, url: "https://api.exemple.fr/upload".to_string(), - headers: vec![( - "Content-Type".to_string(), - "application/octet-stream".to_string(), - )], + headers: vec![("Content-Type".to_string(), "application/octet-stream".to_string())], basic: None, body: CodeBody::File("/tmp/archive.zip".to_string()), follow_redirects: false, }; - vec![ - ("get", get), - ("json", json), - ("form", form), - ("multipart", multipart), - ("file", file), - ] + vec![("get", get), ("json", json), ("form", form), ("multipart", multipart), ("file", file)] } /// The file under `golden/`, or written there when `GOLDEN_WRITE` is set. @@ -519,55 +461,27 @@ mod tests { use crate::http::variables::VariableScope; fn row(key: &str, value: &str) -> KeyValue { - KeyValue { - key: key.to_string(), - value: value.to_string(), - ..KeyValue::default() - } + KeyValue { key: key.to_string(), value: value.to_string(), ..KeyValue::default() } } fn off(key: &str) -> KeyValue { - KeyValue { - enabled: false, - ..row(key, "x") - } + KeyValue { enabled: false, ..row(key, "x") } } fn part(key: &str, value: &str, file: bool, enabled: bool) -> FormPart { - FormPart { - enabled, - key: key.to_string(), - value: value.to_string(), - file, - ..FormPart::default() - } + FormPart { enabled, key: key.to_string(), value: value.to_string(), file, ..FormPart::default() } } fn http(document: &RequestDocument) -> CodeRequest { - request_of( - RequestKind::Http, - HttpMethod::Post, - document, - &inherit(&[]), - false, - ) + request_of(RequestKind::Http, HttpMethod::Post, document, &inherit(&[]), false) } fn layer(variables: Vec) -> VariableLayer { - VariableLayer { - scope: VariableScope::Environment, - from: "Prod".to_string(), - variables, - } + VariableLayer { scope: VariableScope::Environment, from: "Prod".to_string(), variables } } fn variable(name: &str, value: &str, kind: VariableKind) -> Variable { - Variable { - name: name.to_string(), - value: value.to_string(), - kind, - ..Variable::default() - } + Variable { name: name.to_string(), value: value.to_string(), kind, ..Variable::default() } } /// What a snippet of each target is saved as; the three that build no multipart body say so. @@ -577,10 +491,7 @@ mod tests { assert_eq!(target.as_str().parse::(), Ok(target)); assert_eq!( target.sends_multipart(), - !matches!( - target, - CodeTarget::Wget | CodeTarget::Java | CodeTarget::Swift - ), + !matches!(target, CodeTarget::Wget | CodeTarget::Java | CodeTarget::Swift), "{target:?}" ); } @@ -613,10 +524,7 @@ mod tests { }, ..RequestDocument::default() }; - let variable = RequestDocument { - url: "{{base}}/a".to_string(), - ..RequestDocument::default() - }; + let variable = RequestDocument { url: "{{base}}/a".to_string(), ..RequestDocument::default() }; let unnamed_key = RequestDocument { url: "https://shop.test/".to_string(), auth: RequestAuth::ApiKey { @@ -639,10 +547,7 @@ mod tests { let document = RequestDocument { url: "https://shop.test/".to_string(), headers: vec![row("X-Trace", "1")], - auth: RequestAuth::Basic { - username: "ada".to_string(), - password: "pw".to_string(), - }, + auth: RequestAuth::Basic { username: "ada".to_string(), password: "pw".to_string() }, ..RequestDocument::default() }; @@ -659,22 +564,10 @@ mod tests { fn the_body_is_what_a_send_would_write() { for (body, expected) in [ (RequestBody::None, CodeBody::None), + (RequestBody::Json { text: String::new() }, CodeBody::None), + (RequestBody::Text { text: "t".to_string() }, CodeBody::Text("t".to_string())), ( - RequestBody::Json { - text: String::new(), - }, - CodeBody::None, - ), - ( - RequestBody::Text { - text: "t".to_string(), - }, - CodeBody::Text("t".to_string()), - ), - ( - RequestBody::Form { - fields: vec![row(" a ", "1"), off("b"), row(" ", "x")], - }, + RequestBody::Form { fields: vec![row(" a ", "1"), off("b"), row(" ", "x")] }, CodeBody::Form(vec![("a".to_string(), "1".to_string())]), ), ( @@ -691,23 +584,13 @@ mod tests { file: true, }]), ), + (RequestBody::Binary { path: " ".to_string() }, CodeBody::None), ( - RequestBody::Binary { - path: " ".to_string(), - }, - CodeBody::None, - ), - ( - RequestBody::Binary { - path: " /dump.bin ".to_string(), - }, + RequestBody::Binary { path: " /dump.bin ".to_string() }, CodeBody::File("/dump.bin".to_string()), ), ] { - let document = RequestDocument { - body, - ..RequestDocument::default() - }; + let document = RequestDocument { body, ..RequestDocument::default() }; assert_eq!(http(&document).body, expected); } @@ -717,45 +600,23 @@ mod tests { /// query, whatever method the document holds. #[test] fn a_graphql_request_is_written_as_it_is_sent() { - let mut document = RequestDocument { - url: "https://shop.test/graphql".to_string(), - ..RequestDocument::default() - }; + let mut document = + RequestDocument { url: "https://shop.test/graphql".to_string(), ..RequestDocument::default() }; document.graphql.query = "{ me }".to_string(); document.graphql.variables = "{\"a\":1}".to_string(); document.graphql.operation_name = Some("Me".to_string()); - let posted = request_of( - RequestKind::Graphql, - HttpMethod::Delete, - &document, - &inherit(&[]), - true, - ); + let posted = request_of(RequestKind::Graphql, HttpMethod::Delete, &document, &inherit(&[]), true); document.graphql.as_get = true; - let got = request_of( - RequestKind::Graphql, - HttpMethod::Delete, - &document, - &inherit(&[]), - true, - ); + let got = request_of(RequestKind::Graphql, HttpMethod::Delete, &document, &inherit(&[]), true); document.graphql.operation_name = Some(String::new()); document.graphql.variables = "[not an object]".to_string(); - let bare = request_of( - RequestKind::Graphql, - HttpMethod::Delete, - &document, - &inherit(&[]), - true, - ); + let bare = request_of(RequestKind::Graphql, HttpMethod::Delete, &document, &inherit(&[]), true); assert_eq!(posted.method, HttpMethod::Post); assert_eq!( posted.body, - CodeBody::Text( - r#"{"query":"{ me }","variables":{"a":1},"operationName":"Me"}"#.to_string() - ) + CodeBody::Text(r#"{"query":"{ me }","variables":{"a":1},"operationName":"Me"}"#.to_string()) ); assert!(posted.follow_redirects); assert_eq!((got.method, &got.body), (HttpMethod::Get, &CodeBody::None)); @@ -779,10 +640,7 @@ mod tests { } fn document_using(names: &str) -> RequestDocument { - RequestDocument { - url: format!("https://shop.test/{names}"), - ..RequestDocument::default() - } + RequestDocument { url: format!("https://shop.test/{names}"), ..RequestDocument::default() } } /// A secret stays its `{{name}}` and is named, unless asked for in clear; a name nothing @@ -794,14 +652,8 @@ mod tests { variable("token", "t0k3n", VariableKind::Secret), ])]; let document = document_using("{{host}}/{{token}}/{{nowhere}}"); - let resolve = CodeOptions { - resolve_variables: true, - ..CodeOptions::default() - }; - let in_clear = CodeOptions { - include_secrets: true, - ..resolve - }; + let resolve = CodeOptions { resolve_variables: true, ..CodeOptions::default() }; + let in_clear = CodeOptions { include_secrets: true, ..resolve }; let generate_with = |options| { generate( CodeTarget::Curl, @@ -818,30 +670,14 @@ mod tests { let clear = generate_with(in_clear); let typed = generate_with(CodeOptions::default()); - assert!( - masked - .code - .contains("https://shop.test/h/{{token}}/{{nowhere}}"), - "{}", - masked.code - ); + assert!(masked.code.contains("https://shop.test/h/{{token}}/{{nowhere}}"), "{}", masked.code); assert_eq!( (masked.secrets, masked.unresolved), (vec!["token".to_string()], vec!["nowhere".to_string()]) ); - assert!( - clear.code.contains("https://shop.test/h/t0k3n/{{nowhere}}"), - "{}", - clear.code - ); + assert!(clear.code.contains("https://shop.test/h/t0k3n/{{nowhere}}"), "{}", clear.code); assert!(clear.secrets.is_empty()); - assert!( - typed - .code - .contains("https://shop.test/{{host}}/{{token}}/{{nowhere}}"), - "{}", - typed.code - ); + assert!(typed.code.contains("https://shop.test/{{host}}/{{token}}/{{nowhere}}"), "{}", typed.code); assert_eq!(masked.language, Language::Sh); } @@ -849,9 +685,7 @@ mod tests { #[test] fn a_target_that_cannot_send_a_multipart_body_says_so() { let document = RequestDocument { - body: RequestBody::Multipart { - parts: vec![part("a", "1", false, true)], - }, + body: RequestBody::Multipart { parts: vec![part("a", "1", false, true)] }, ..document_using("") }; let notice = |target| { @@ -900,11 +734,7 @@ mod tests { &[], ); - assert!( - code.code.contains("shop.test/orders"), - "{target:?}: {}", - code.code - ); + assert!(code.code.contains("shop.test/orders"), "{target:?}: {}", code.code); assert_eq!(code.language, target.language()); } } @@ -921,23 +751,14 @@ mod tests { fn arguments_are_written_on_one_line_or_one_a_line() { let arguments = ["-X POST".to_string(), "'https://shop.test/'".to_string()]; - assert_eq!( - shell_lines("curl", &arguments, false), - "curl -X POST 'https://shop.test/'" - ); - assert_eq!( - shell_lines("curl", &arguments, true), - "curl \\\n -X POST \\\n 'https://shop.test/'" - ); + assert_eq!(shell_lines("curl", &arguments, false), "curl -X POST 'https://shop.test/'"); + assert_eq!(shell_lines("curl", &arguments, true), "curl \\\n -X POST \\\n 'https://shop.test/'"); assert_eq!(shell_lines("curl", &[], true), "curl"); } #[test] fn a_form_is_encoded_as_it_is_sent() { - let fields = [ - ("a b".to_string(), "x&y=z".to_string()), - ("c".to_string(), String::new()), - ]; + let fields = [("a b".to_string(), "x&y=z".to_string()), ("c".to_string(), String::new())]; assert_eq!(form_encoded(&fields), "a+b=x%26y%3Dz&c="); } diff --git a/crates/engine/src/http/codegen/angular.rs b/crates/engine/src/http/codegen/angular.rs index f38533ab2..d9c04125d 100644 --- a/crates/engine/src/http/codegen/angular.rs +++ b/crates/engine/src/http/codegen/angular.rs @@ -39,14 +39,9 @@ pub fn write(request: &CodeRequest) -> String { CodeBody::None => None, CodeBody::Text(text) => Some(string(text)), CodeBody::Form(fields) => { - let entries: Vec<(String, String)> = fields - .iter() - .map(|(name, value)| (name.clone(), string(value))) - .collect(); - Some(format!( - "new URLSearchParams({}).toString()", - object(&entries, " ") - )) + let entries: Vec<(String, String)> = + fields.iter().map(|(name, value)| (name.clone(), string(value))).collect(); + Some(format!("new URLSearchParams({}).toString()", object(&entries, " "))) } CodeBody::Multipart(parts) => { for part in parts.iter().filter(|part| part.file) { @@ -54,11 +49,7 @@ pub fn write(request: &CodeRequest) -> String { } lines.push("const form = new FormData();".to_string()); for part in parts { - let value = if part.file { - identifier(&part.name) - } else { - string(&part.value) - }; + let value = if part.file { identifier(&part.name) } else { string(&part.value) }; lines.push(format!("form.append({}, {value});", string(&part.name))); } Some("form".to_string()) @@ -73,10 +64,7 @@ pub fn write(request: &CodeRequest) -> String { } let mut options = Vec::new(); if !headers.is_empty() { - options.push(( - "headers".to_string(), - format!("new HttpHeaders({})", object(&headers, " ")), - )); + options.push(("headers".to_string(), format!("new HttpHeaders({})", object(&headers, " ")))); } if let Some(body) = body { options.push(("body".to_string(), body)); diff --git a/crates/engine/src/http/codegen/axios.rs b/crates/engine/src/http/codegen/axios.rs index ddf05c2dc..3ae8ad991 100644 --- a/crates/engine/src/http/codegen/axios.rs +++ b/crates/engine/src/http/codegen/axios.rs @@ -28,10 +28,7 @@ pub fn write(request: &CodeRequest) -> String { options.push(( "auth".to_string(), object( - &[ - ("username".to_string(), string(user)), - ("password".to_string(), string(password)), - ], + &[("username".to_string(), string(user)), ("password".to_string(), string(password))], " ", ), )); @@ -44,10 +41,7 @@ pub fn write(request: &CodeRequest) -> String { } // An answer of 4xx or 5xx is an answer to print, not an exception to catch. options.push(("validateStatus".to_string(), "() => true".to_string())); - lines.push(format!( - "const response = await axios.request({});", - object(&options, "") - )); + lines.push(format!("const response = await axios.request({});", object(&options, ""))); lines.push("console.log(response.status, response.data);".to_string()); lines.join("\n") } diff --git a/crates/engine/src/http/codegen/csharp.rs b/crates/engine/src/http/codegen/csharp.rs index 74a8504cf..186302af4 100644 --- a/crates/engine/src/http/codegen/csharp.rs +++ b/crates/engine/src/http/codegen/csharp.rs @@ -40,11 +40,7 @@ pub fn write(request: &CodeRequest) -> String { .iter() .filter(|(name, _)| !name.eq_ignore_ascii_case("content-type")) { - lines.push(format!( - "request.Headers.TryAddWithoutValidation({}, {});", - quoted(name), - quoted(value) - )); + lines.push(format!("request.Headers.TryAddWithoutValidation({}, {});", quoted(name), quoted(value))); } if let Some((user, password)) = &request.basic { lines.push(format!( @@ -61,8 +57,7 @@ pub fn write(request: &CodeRequest) -> String { )), CodeBody::Form(fields) => { lines.push( - "request.Content = new FormUrlEncodedContent(new Dictionary" - .to_string(), + "request.Content = new FormUrlEncodedContent(new Dictionary".to_string(), ); lines.push("{".to_string()); for (name, value) in fields { @@ -91,10 +86,7 @@ pub fn write(request: &CodeRequest) -> String { lines.push("request.Content = form;".to_string()); } CodeBody::File(path) => { - lines.push(format!( - "request.Content = new StreamContent(File.OpenRead({}));", - quoted(path) - )); + lines.push(format!("request.Content = new StreamContent(File.OpenRead({}));", quoted(path))); if let Some(content_type) = content_type { lines.push(format!( "request.Content.Headers.ContentType = new MediaTypeHeaderValue({});", diff --git a/crates/engine/src/http/codegen/curl.rs b/crates/engine/src/http/codegen/curl.rs index 71c3454eb..d2635f351 100644 --- a/crates/engine/src/http/codegen/curl.rs +++ b/crates/engine/src/http/codegen/curl.rs @@ -18,26 +18,17 @@ pub fn write(request: &CodeRequest, multiline: bool) -> String { arguments.push("--location".to_string()); } for (name, value) in &request.headers { - arguments.push(format!( - "--header {}", - shell_quoted(&format!("{name}: {value}")) - )); + arguments.push(format!("--header {}", shell_quoted(&format!("{name}: {value}")))); } if let Some((user, password)) = &request.basic { - arguments.push(format!( - "--user {}", - shell_quoted(&format!("{user}:{password}")) - )); + arguments.push(format!("--user {}", shell_quoted(&format!("{user}:{password}")))); } match &request.body { CodeBody::None => {} CodeBody::Text(text) => arguments.push(format!("--data-raw {}", shell_quoted(text))), CodeBody::Form(fields) => { for (name, value) in fields { - arguments.push(format!( - "--data-urlencode {}", - shell_quoted(&format!("{name}={value}")) - )); + arguments.push(format!("--data-urlencode {}", shell_quoted(&format!("{name}={value}")))); } } CodeBody::Multipart(parts) => { @@ -52,10 +43,7 @@ pub fn write(request: &CodeRequest, multiline: bool) -> String { } } CodeBody::File(path) => { - arguments.push(format!( - "--data-binary {}", - shell_quoted(&format!("@{path}")) - )); + arguments.push(format!("--data-binary {}", shell_quoted(&format!("@{path}")))); } } shell_lines(&first, &arguments, multiline) @@ -78,10 +66,7 @@ mod tests { follow_redirects: false, }; - let text = write( - &request(CodeBody::Text("@/etc/hostname".to_string())), - false, - ); + let text = write(&request(CodeBody::Text("@/etc/hostname".to_string())), false); let form = write( &request(CodeBody::Multipart(vec![super::super::CodePart { name: "a".to_string(), diff --git a/crates/engine/src/http/codegen/dart.rs b/crates/engine/src/http/codegen/dart.rs index 59afb2cda..2affd661c 100644 --- a/crates/engine/src/http/codegen/dart.rs +++ b/crates/engine/src/http/codegen/dart.rs @@ -27,19 +27,12 @@ pub fn write(request: &CodeRequest) -> String { lines.push("Future main() async {".to_string()); lines.push(format!( " final request = http.{}({}, Uri.parse({}));", - if multipart { - "MultipartRequest" - } else { - "Request" - }, + if multipart { "MultipartRequest" } else { "Request" }, quoted(request.method.as_str()), quoted(&request.url) )); if !request.headers.is_empty() { - lines.push(format!( - " request.headers.addAll({});", - map(&request.headers) - )); + lines.push(format!(" request.headers.addAll({});", map(&request.headers))); } if let Some((user, password)) = &request.basic { lines.push(format!( @@ -68,18 +61,12 @@ pub fn write(request: &CodeRequest) -> String { } } } - CodeBody::File(path) => lines.push(format!( - " request.bodyBytes = await File({}).readAsBytes();", - quoted(path) - )), + CodeBody::File(path) => { + lines.push(format!(" request.bodyBytes = await File({}).readAsBytes();", quoted(path))); + } } - lines.push(format!( - " request.followRedirects = {};", - request.follow_redirects - )); - lines.push( - " final response = await http.Response.fromStream(await request.send());".to_string(), - ); + lines.push(format!(" request.followRedirects = {};", request.follow_redirects)); + lines.push(" final response = await http.Response.fromStream(await request.send());".to_string()); lines.push(" print('${response.statusCode} ${response.body}');".to_string()); lines.push("}".to_string()); lines.join("\n") diff --git a/crates/engine/src/http/codegen/fetch.rs b/crates/engine/src/http/codegen/fetch.rs index 9fb4e9f09..b3293e71d 100644 --- a/crates/engine/src/http/codegen/fetch.rs +++ b/crates/engine/src/http/codegen/fetch.rs @@ -23,11 +23,7 @@ pub fn write(request: &CodeRequest) -> String { if !request.follow_redirects { options.push(("redirect".to_string(), string("manual"))); } - lines.push(format!( - "const response = await fetch({}, {});", - string(&request.url), - object(&options, "") - )); + lines.push(format!("const response = await fetch({}, {});", string(&request.url), object(&options, ""))); lines.push("console.log(response.status, await response.text());".to_string()); lines.join("\n") } diff --git a/crates/engine/src/http/codegen/go.rs b/crates/engine/src/http/codegen/go.rs index 806b818aa..87a5aaf92 100644 --- a/crates/engine/src/http/codegen/go.rs +++ b/crates/engine/src/http/codegen/go.rs @@ -46,9 +46,8 @@ pub fn write(request: &CodeRequest) -> String { } } body_lines.push("writer.Close()".to_string()); - after_request.push( - "request.Header.Set(\"Content-Type\", writer.FormDataContentType())".to_string(), - ); + after_request + .push("request.Header.Set(\"Content-Type\", writer.FormDataContentType())".to_string()); "&form".to_string() } CodeBody::File(path) => { @@ -68,19 +67,11 @@ pub fn write(request: &CodeRequest) -> String { )); lines.push("if err != nil {\n\t\tpanic(err)\n\t}".to_string()); for (name, value) in &request.headers { - lines.push(format!( - "request.Header.Set({}, {})", - quoted(name), - quoted(value) - )); + lines.push(format!("request.Header.Set({}, {})", quoted(name), quoted(value))); } lines.extend(after_request); if let Some((user, password)) = &request.basic { - lines.push(format!( - "request.SetBasicAuth({}, {})", - quoted(user), - quoted(password) - )); + lines.push(format!("request.SetBasicAuth({}, {})", quoted(user), quoted(password))); } if request.follow_redirects { lines.push("client := &http.Client{}".to_string()); @@ -96,16 +87,9 @@ pub fn write(request: &CodeRequest) -> String { lines.push("answer, _ := io.ReadAll(response.Body)".to_string()); lines.push("fmt.Println(response.StatusCode, string(answer))".to_string()); - let imports: Vec = imports - .into_iter() - .map(|import| format!("\t{}", quoted(import))) - .collect(); + let imports: Vec = imports.into_iter().map(|import| format!("\t{}", quoted(import))).collect(); let body: Vec = lines.into_iter().map(|line| format!("\t{line}")).collect(); - format!( - "package main\n\nimport (\n{}\n)\n\nfunc main() {{\n{}\n}}", - imports.join("\n"), - body.join("\n") - ) + format!("package main\n\nimport (\n{}\n)\n\nfunc main() {{\n{}\n}}", imports.join("\n"), body.join("\n")) } #[cfg(test)] diff --git a/crates/engine/src/http/codegen/guzzle.rs b/crates/engine/src/http/codegen/guzzle.rs index 7c8cd1b7e..49b9d590e 100644 --- a/crates/engine/src/http/codegen/guzzle.rs +++ b/crates/engine/src/http/codegen/guzzle.rs @@ -25,19 +25,14 @@ pub fn write(request: &CodeRequest) -> String { options.push(("headers".to_string(), array(&headers, " "))); } if let Some((user, password)) = &request.basic { - options.push(( - "auth".to_string(), - format!("[{}, {}]", quoted(user), quoted(password)), - )); + options.push(("auth".to_string(), format!("[{}, {}]", quoted(user), quoted(password)))); } match &request.body { CodeBody::None => {} CodeBody::Text(text) => options.push(("body".to_string(), quoted(text))), CodeBody::Form(fields) => { - let fields: Vec<(String, String)> = fields - .iter() - .map(|(name, value)| (name.clone(), quoted(value))) - .collect(); + let fields: Vec<(String, String)> = + fields.iter().map(|(name, value)| (name.clone(), quoted(value))).collect(); options.push(("form_params".to_string(), array(&fields, " "))); } CodeBody::Multipart(parts) => { @@ -49,25 +44,16 @@ pub fn write(request: &CodeRequest) -> String { } else { quoted(&part.value) }; - format!( - " ['name' => {}, 'contents' => {contents}],", - quoted(&part.name) - ) + format!(" ['name' => {}, 'contents' => {contents}],", quoted(&part.name)) }) .collect(); - options.push(( - "multipart".to_string(), - format!("[\n{}\n ]", lines.join("\n")), - )); + options.push(("multipart".to_string(), format!("[\n{}\n ]", lines.join("\n")))); } CodeBody::File(path) => { options.push(("body".to_string(), format!("fopen({}, 'r')", quoted(path)))); } } - options.push(( - "allow_redirects".to_string(), - request.follow_redirects.to_string(), - )); + options.push(("allow_redirects".to_string(), request.follow_redirects.to_string())); options.push(("http_errors".to_string(), "false".to_string())); format!( "request({}, {}, {});\necho $response->getStatusCode(), ' ', $response->getBody();", diff --git a/crates/engine/src/http/codegen/httpie.rs b/crates/engine/src/http/codegen/httpie.rs index ed1a49fa4..173d37c38 100644 --- a/crates/engine/src/http/codegen/httpie.rs +++ b/crates/engine/src/http/codegen/httpie.rs @@ -10,10 +10,7 @@ pub fn write(request: &CodeRequest, multiline: bool) -> String { arguments.push("--follow".to_string()); } if let Some((user, password)) = &request.basic { - arguments.push(format!( - "--auth {}", - shell_quoted(&format!("{user}:{password}")) - )); + arguments.push(format!("--auth {}", shell_quoted(&format!("{user}:{password}")))); } match &request.body { CodeBody::Form(_) => arguments.push("--form".to_string()), @@ -33,20 +30,13 @@ pub fn write(request: &CodeRequest, multiline: bool) -> String { CodeBody::Multipart(parts) => { for part in parts { let separator = if part.file { "@" } else { "=" }; - arguments.push(shell_quoted(&format!( - "{}{separator}{}", - part.name, part.value - ))); + arguments.push(shell_quoted(&format!("{}{separator}{}", part.name, part.value))); } } CodeBody::File(path) => arguments.push(format!("< {}", shell_quoted(path))), CodeBody::None | CodeBody::Text(_) => {} } - let first = format!( - "http {} {}", - request.method.as_str(), - shell_quoted(&request.url) - ); + let first = format!("http {} {}", request.method.as_str(), shell_quoted(&request.url)); shell_lines(&first, &arguments, multiline) } diff --git a/crates/engine/src/http/codegen/java.rs b/crates/engine/src/http/codegen/java.rs index 371f69dc9..1c24edb91 100644 --- a/crates/engine/src/http/codegen/java.rs +++ b/crates/engine/src/http/codegen/java.rs @@ -14,20 +14,14 @@ pub fn write(request: &CodeRequest) -> String { "java.net.http.HttpResponse", ]; let publisher = match &request.body { - CodeBody::None | CodeBody::Multipart(_) => { - "HttpRequest.BodyPublishers.noBody()".to_string() - } + CodeBody::None | CodeBody::Multipart(_) => "HttpRequest.BodyPublishers.noBody()".to_string(), CodeBody::Text(text) => format!("HttpRequest.BodyPublishers.ofString({})", quoted(text)), - CodeBody::Form(fields) => format!( - "HttpRequest.BodyPublishers.ofString({})", - quoted(&form_encoded(fields)) - ), + CodeBody::Form(fields) => { + format!("HttpRequest.BodyPublishers.ofString({})", quoted(&form_encoded(fields))) + } CodeBody::File(path) => { imports.push("java.nio.file.Path"); - format!( - "HttpRequest.BodyPublishers.ofFile(Path.of({}))", - quoted(path) - ) + format!("HttpRequest.BodyPublishers.ofFile(Path.of({}))", quoted(path)) } }; if request.basic.is_some() { @@ -35,34 +29,20 @@ pub fn write(request: &CodeRequest) -> String { } imports.sort_unstable(); - let mut lines: Vec = imports - .iter() - .map(|import| format!("import {import};")) - .collect(); + let mut lines: Vec = imports.iter().map(|import| format!("import {import};")).collect(); lines.push(String::new()); lines.push("public class Main {".to_string()); lines.push(" public static void main(String[] args) throws Exception {".to_string()); lines.push(" HttpClient client = HttpClient.newBuilder()".to_string()); lines.push(format!( " .followRedirects(HttpClient.Redirect.{})", - if request.follow_redirects { - "NORMAL" - } else { - "NEVER" - } + if request.follow_redirects { "NORMAL" } else { "NEVER" } )); lines.push(" .build();".to_string()); lines.push(" HttpRequest request = HttpRequest.newBuilder()".to_string()); - lines.push(format!( - " .uri(URI.create({}))", - quoted(&request.url) - )); + lines.push(format!(" .uri(URI.create({}))", quoted(&request.url))); for (name, value) in &request.headers { - lines.push(format!( - " .header({}, {})", - quoted(name), - quoted(value) - )); + lines.push(format!(" .header({}, {})", quoted(name), quoted(value))); } if let Some((user, password)) = &request.basic { lines.push(format!( @@ -70,18 +50,13 @@ pub fn write(request: &CodeRequest) -> String { quoted(&format!("{user}:{password}")) )); } - lines.push(format!( - " .method({}, {publisher})", - quoted(request.method.as_str()) - )); + lines.push(format!(" .method({}, {publisher})", quoted(request.method.as_str()))); lines.push(" .build();".to_string()); lines.push( " HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());" .to_string(), ); - lines.push( - " System.out.println(response.statusCode() + \" \" + response.body());".to_string(), - ); + lines.push(" System.out.println(response.statusCode() + \" \" + response.body());".to_string()); lines.push(" }".to_string()); lines.push("}".to_string()); lines.join("\n") diff --git a/crates/engine/src/http/codegen/javascript.rs b/crates/engine/src/http/codegen/javascript.rs index ad1f35633..218f39f2a 100644 --- a/crates/engine/src/http/codegen/javascript.rs +++ b/crates/engine/src/http/codegen/javascript.rs @@ -8,10 +8,7 @@ use super::{CodeBody, CodeRequest}; #[must_use] pub fn string(text: &str) -> String { if text.contains('\n') { - let escaped = text - .replace('\\', "\\\\") - .replace('`', "\\`") - .replace("${", "\\${"); + let escaped = text.replace('\\', "\\\\").replace('`', "\\`").replace("${", "\\${"); return format!("`{escaped}`"); } let escaped = text @@ -30,11 +27,7 @@ pub fn key(name: &str) -> String { .next() .is_some_and(|first| first.is_ascii_alphabetic() || first == '_' || first == '$') && chars.all(|next| next.is_ascii_alphanumeric() || next == '_' || next == '$'); - if identifier { - name.to_string() - } else { - string(name) - } + if identifier { name.to_string() } else { string(name) } } /// `{ a: 'b', 'c-d': e }` laid out a key a line at `indent`, the values already written. @@ -62,10 +55,7 @@ pub fn headers(request: &CodeRequest) -> Vec<(String, String)> { if let Some((user, password)) = &request.basic { headers.push(( "Authorization".to_string(), - format!( - "`Basic ${{btoa({})}}`", - string(&format!("{user}:{password}")) - ), + format!("`Basic ${{btoa({})}}`", string(&format!("{user}:{password}"))), )); } headers @@ -104,11 +94,7 @@ pub fn form_data(body: &CodeBody) -> Vec { string(&file_name(&part.value)) )); } else { - lines.push(format!( - "form.append({}, {});", - string(&part.name), - string(&part.value) - )); + lines.push(format!("form.append({}, {});", string(&part.name), string(&part.value))); } } lines @@ -121,10 +107,8 @@ pub fn body(body: &CodeBody, indent: &str) -> Option { CodeBody::None => None, CodeBody::Text(text) => Some(string(text)), CodeBody::Form(fields) => { - let entries: Vec<(String, String)> = fields - .iter() - .map(|(name, value)| (name.clone(), string(value))) - .collect(); + let entries: Vec<(String, String)> = + fields.iter().map(|(name, value)| (name.clone(), string(value))).collect(); Some(format!("new URLSearchParams({})", object(&entries, indent))) } CodeBody::Multipart(_) => Some("form".to_string()), @@ -140,10 +124,7 @@ mod tests { fn a_string_is_quoted_for_a_line_and_a_template_for_several() { assert_eq!(string("O'Brien"), r"'O\'Brien'"); assert_eq!(string("a\\b"), r"'a\\b'"); - assert_eq!( - string("{\n \"a\": `${x}`\n}"), - "`{\n \"a\": \\`\\${x}\\`\n}`" - ); + assert_eq!(string("{\n \"a\": `${x}`\n}"), "`{\n \"a\": \\`\\${x}\\`\n}`"); } #[test] diff --git a/crates/engine/src/http/codegen/okhttp.rs b/crates/engine/src/http/codegen/okhttp.rs index 15f9757ee..df862b772 100644 --- a/crates/engine/src/http/codegen/okhttp.rs +++ b/crates/engine/src/http/codegen/okhttp.rs @@ -8,16 +8,10 @@ use super::{CodeBody, CodeRequest}; use crate::http::model::HttpMethod; /// The body as `.method` takes it, what builds it written into `prelude`. -fn body_of( - request: &CodeRequest, - imports: &mut BTreeSet<&'static str>, - prelude: &mut Vec, -) -> String { +fn body_of(request: &CodeRequest, imports: &mut BTreeSet<&'static str>, prelude: &mut Vec) -> String { let content_type = request.content_type().unwrap_or("application/octet-stream"); match &request.body { - CodeBody::None if matches!(request.method, HttpMethod::Get | HttpMethod::Head) => { - "null".to_string() - } + CodeBody::None if matches!(request.method, HttpMethod::Get | HttpMethod::Head) => "null".to_string(), CodeBody::None => { imports.insert("okhttp3.RequestBody.Companion.toRequestBody"); "ByteArray(0).toRequestBody()".to_string() @@ -25,11 +19,7 @@ fn body_of( CodeBody::Text(text) => { imports.insert("okhttp3.MediaType.Companion.toMediaType"); imports.insert("okhttp3.RequestBody.Companion.toRequestBody"); - format!( - "{}.toRequestBody({}.toMediaType())", - quoted(text), - quoted(content_type) - ) + format!("{}.toRequestBody({}.toMediaType())", quoted(text), quoted(content_type)) } CodeBody::Form(fields) => { imports.insert("okhttp3.FormBody"); @@ -69,36 +59,24 @@ fn body_of( imports.insert("java.io.File"); imports.insert("okhttp3.MediaType.Companion.toMediaType"); imports.insert("okhttp3.RequestBody.Companion.asRequestBody"); - format!( - "File({}).asRequestBody({}.toMediaType())", - quoted(path), - quoted(content_type) - ) + format!("File({}).asRequestBody({}.toMediaType())", quoted(path), quoted(content_type)) } } } #[must_use] pub fn write(request: &CodeRequest) -> String { - let mut imports: BTreeSet<&str> = ["okhttp3.OkHttpClient", "okhttp3.Request"] - .into_iter() - .collect(); + let mut imports: BTreeSet<&str> = ["okhttp3.OkHttpClient", "okhttp3.Request"].into_iter().collect(); let mut prelude = Vec::new(); let body = body_of(request, &mut imports, &mut prelude); if request.basic.is_some() { imports.insert("okhttp3.Credentials"); } - let mut lines: Vec = imports - .iter() - .map(|import| format!("import {import}")) - .collect(); + let mut lines: Vec = imports.iter().map(|import| format!("import {import}")).collect(); lines.push(String::new()); lines.push("val client = OkHttpClient.Builder()".to_string()); - lines.push(format!( - " .followRedirects({})", - request.follow_redirects - )); + lines.push(format!(" .followRedirects({})", request.follow_redirects)); lines.push(" .build()".to_string()); lines.extend(prelude); lines.push("val request = Request.Builder()".to_string()); @@ -118,10 +96,7 @@ pub fn write(request: &CodeRequest) -> String { quoted(password) )); } - lines.push(format!( - " .method({}, {body})", - quoted(request.method.as_str()) - )); + lines.push(format!(" .method({}, {body})", quoted(request.method.as_str()))); lines.push(" .build()".to_string()); lines.push("client.newCall(request).execute().use { response ->".to_string()); lines.push(" println(\"${response.code} ${response.body?.string()}\")".to_string()); diff --git a/crates/engine/src/http/codegen/powershell.rs b/crates/engine/src/http/codegen/powershell.rs index 588d25f43..706680be0 100644 --- a/crates/engine/src/http/codegen/powershell.rs +++ b/crates/engine/src/http/codegen/powershell.rs @@ -72,10 +72,8 @@ pub fn write(request: &CodeRequest, multiline: bool) -> String { } let mut lines = Vec::new(); - let mut parameters = vec![ - format!("-Uri {}", quoted(&request.url)), - format!("-Method {}", method(request.method)), - ]; + let mut parameters = + vec![format!("-Uri {}", quoted(&request.url)), format!("-Method {}", method(request.method))]; if !headers.is_empty() { lines.push(format!("$headers = {}", hashtable(&headers, multiline))); parameters.push("-Headers $headers".to_string()); @@ -92,10 +90,8 @@ pub fn write(request: &CodeRequest, multiline: bool) -> String { parameters.push("-Body $body".to_string()); } CodeBody::Form(fields) => { - let entries: Vec<(String, String)> = fields - .iter() - .map(|(name, value)| (name.clone(), quoted(value))) - .collect(); + let entries: Vec<(String, String)> = + fields.iter().map(|(name, value)| (name.clone(), quoted(value))).collect(); lines.push(format!("$body = {}", hashtable(&entries, multiline))); parameters.push("-Body $body".to_string()); } @@ -126,13 +122,7 @@ pub fn write(request: &CodeRequest, multiline: bool) -> String { let last = call.len() - 1; call.iter() .enumerate() - .map(|(at, line)| { - if at == last { - line.clone() - } else { - format!("{line} `") - } - }) + .map(|(at, line)| if at == last { line.clone() } else { format!("{line} `") }) .collect::>() .join("\n") } else { diff --git a/crates/engine/src/http/codegen/python.rs b/crates/engine/src/http/codegen/python.rs index 34ff83da2..48bcd2a7d 100644 --- a/crates/engine/src/http/codegen/python.rs +++ b/crates/engine/src/http/codegen/python.rs @@ -44,10 +44,8 @@ fn write(request: &CodeRequest, library: Library) -> String { CodeBody::None => {} CodeBody::Text(text) => arguments.push(format!("{raw}={}", quoted(text))), CodeBody::Form(fields) => { - let fields: Vec<(String, String)> = fields - .iter() - .map(|(name, value)| (name.clone(), quoted(value))) - .collect(); + let fields: Vec<(String, String)> = + fields.iter().map(|(name, value)| (name.clone(), quoted(value))).collect(); arguments.push(format!("data={}", dict(&fields))); } CodeBody::Multipart(parts) => { @@ -59,12 +57,7 @@ fn write(request: &CodeRequest, library: Library) -> String { let files: Vec<(String, String)> = parts .iter() .filter(|part| part.file) - .map(|part| { - ( - part.name.clone(), - format!("open({}, \"rb\")", quoted(&part.value)), - ) - }) + .map(|part| (part.name.clone(), format!("open({}, \"rb\")", quoted(&part.value)))) .collect(); if !texts.is_empty() { arguments.push(format!("data={}", dict(&texts))); @@ -77,19 +70,12 @@ fn write(request: &CodeRequest, library: Library) -> String { arguments.push(format!("{raw}=open({}, \"rb\")", quoted(path))); } } - let follow = if request.follow_redirects { - "True" - } else { - "False" - }; + let follow = if request.follow_redirects { "True" } else { "False" }; arguments.push(match library { Library::Requests => format!("allow_redirects={follow}"), Library::Httpx => format!("follow_redirects={follow}"), }); - let arguments: Vec = arguments - .into_iter() - .map(|argument| format!(" {argument},")) - .collect(); + let arguments: Vec = arguments.into_iter().map(|argument| format!(" {argument},")).collect(); format!( "import {name}\n\nresponse = {name}.request(\n{}\n)\nprint(response.status_code, response.text)", arguments.join("\n") diff --git a/crates/engine/src/http/codegen/req.rs b/crates/engine/src/http/codegen/req.rs index 330ee944d..c263636b8 100644 --- a/crates/engine/src/http/codegen/req.rs +++ b/crates/engine/src/http/codegen/req.rs @@ -28,19 +28,14 @@ pub fn write(request: &CodeRequest) -> String { options.push(format!("headers: {}", pairs(&headers))); } if let Some((user, password)) = &request.basic { - options.push(format!( - "auth: {{:basic, {}}}", - quoted(&format!("{user}:{password}")) - )); + options.push(format!("auth: {{:basic, {}}}", quoted(&format!("{user}:{password}")))); } match &request.body { CodeBody::None => {} CodeBody::Text(text) => options.push(format!("body: {}", quoted(text))), CodeBody::Form(fields) => { - let fields: Vec<(String, String)> = fields - .iter() - .map(|(name, value)| (name.clone(), quoted(value))) - .collect(); + let fields: Vec<(String, String)> = + fields.iter().map(|(name, value)| (name.clone(), quoted(value))).collect(); options.push(format!("form: {}", pairs(&fields))); } CodeBody::Multipart(parts) => { @@ -61,10 +56,7 @@ pub fn write(request: &CodeRequest) -> String { } options.push(format!("redirect: {}", request.follow_redirects)); options.push("retry: false".to_string()); - let options: Vec = options - .into_iter() - .map(|option| format!(" {option}")) - .collect(); + let options: Vec = options.into_iter().map(|option| format!(" {option}")).collect(); format!( "response =\n Req.request!(\n{}\n )\n\nIO.puts(\"#{{response.status}} #{{inspect(response.body)}}\")", options.join(",\n") diff --git a/crates/engine/src/http/codegen/reqwest.rs b/crates/engine/src/http/codegen/reqwest.rs index cfd2e7fcb..32720010f 100644 --- a/crates/engine/src/http/codegen/reqwest.rs +++ b/crates/engine/src/http/codegen/reqwest.rs @@ -40,17 +40,9 @@ pub fn write(request: &CodeRequest) -> String { for (at, part) in parts.iter().enumerate() { let end = if at == last { ";" } else { "" }; if part.file { - lines.push(format!( - " .file({}, {})?{end}", - quoted(&part.name), - quoted(&part.value) - )); + lines.push(format!(" .file({}, {})?{end}", quoted(&part.name), quoted(&part.value))); } else { - lines.push(format!( - " .text({}, {}){end}", - quoted(&part.name), - quoted(&part.value) - )); + lines.push(format!(" .text({}, {}){end}", quoted(&part.name), quoted(&part.value))); } } } @@ -61,18 +53,10 @@ pub fn write(request: &CodeRequest) -> String { quoted(&request.url) )); for (name, value) in &request.headers { - lines.push(format!( - " .header({}, {})", - quoted(name), - quoted(value) - )); + lines.push(format!(" .header({}, {})", quoted(name), quoted(value))); } if let Some((user, password)) = &request.basic { - lines.push(format!( - " .basic_auth({}, Some({}))", - quoted(user), - quoted(password) - )); + lines.push(format!(" .basic_auth({}, Some({}))", quoted(user), quoted(password))); } match &request.body { CodeBody::None => {} @@ -86,10 +70,7 @@ pub fn write(request: &CodeRequest) -> String { } CodeBody::Multipart(_) => lines.push(" .multipart(form)".to_string()), CodeBody::File(path) => { - lines.push(format!( - " .body(std::fs::File::open({})?)", - quoted(path) - )); + lines.push(format!(" .body(std::fs::File::open({})?)", quoted(path))); } } lines.push(" .send()?;".to_string()); diff --git a/crates/engine/src/http/codegen/ruby.rs b/crates/engine/src/http/codegen/ruby.rs index 0fa2cf3fb..7e6ad1ad0 100644 --- a/crates/engine/src/http/codegen/ruby.rs +++ b/crates/engine/src/http/codegen/ruby.rs @@ -30,11 +30,7 @@ pub fn write(request: &CodeRequest) -> String { lines.push(format!("request[{}] = {}", quoted(name), quoted(value))); } if let Some((user, password)) = &request.basic { - lines.push(format!( - "request.basic_auth({}, {})", - quoted(user), - quoted(password) - )); + lines.push(format!("request.basic_auth({}, {})", quoted(user), quoted(password))); } match &request.body { CodeBody::None => {} @@ -58,10 +54,7 @@ pub fn write(request: &CodeRequest) -> String { format!("[{}, {value}]", quoted(&part.name)) }) .collect(); - lines.push(format!( - "request.set_form([{}], 'multipart/form-data')", - pairs.join(", ") - )); + lines.push(format!("request.set_form([{}], 'multipart/form-data')", pairs.join(", "))); } CodeBody::File(path) => { lines.push(format!("request.body = File.binread({})", quoted(path))); diff --git a/crates/engine/src/http/codegen/source.rs b/crates/engine/src/http/codegen/source.rs index 8fbde7652..2e09913ca 100644 --- a/crates/engine/src/http/codegen/source.rs +++ b/crates/engine/src/http/codegen/source.rs @@ -43,13 +43,7 @@ pub fn single_quoted(text: &str) -> String { pub fn dart(text: &str) -> String { let inner = double_quoted(text); let inner = &inner[1..inner.len() - 1]; - format!( - "'{}'", - inner - .replace("\\\"", "\"") - .replace('\'', "\\'") - .replace('$', "\\$") - ) + format!("'{}'", inner.replace("\\\"", "\"").replace('\'', "\\'").replace('$', "\\$")) } /// The last part of a path: what a file part is sent as. diff --git a/crates/engine/src/http/codegen/swift.rs b/crates/engine/src/http/codegen/swift.rs index 897f45a36..4214a1168 100644 --- a/crates/engine/src/http/codegen/swift.rs +++ b/crates/engine/src/http/codegen/swift.rs @@ -10,18 +10,11 @@ pub fn write(request: &CodeRequest) -> String { let mut lines = vec![ "import Foundation".to_string(), String::new(), - format!( - "var request = URLRequest(url: URL(string: {})!)", - quoted(&request.url) - ), + format!("var request = URLRequest(url: URL(string: {})!)", quoted(&request.url)), format!("request.httpMethod = {}", quoted(request.method.as_str())), ]; for (name, value) in &request.headers { - lines.push(format!( - "request.setValue({}, forHTTPHeaderField: {})", - quoted(value), - quoted(name) - )); + lines.push(format!("request.setValue({}, forHTTPHeaderField: {})", quoted(value), quoted(name))); } if let Some((user, password)) = &request.basic { lines.push(format!( @@ -34,19 +27,15 @@ pub fn write(request: &CodeRequest) -> String { CodeBody::Text(text) => { lines.push(format!("request.httpBody = Data({}.utf8)", quoted(text))); } - CodeBody::Form(fields) => lines.push(format!( - "request.httpBody = Data({}.utf8)", - quoted(&form_encoded(fields)) - )), - CodeBody::File(path) => lines.push(format!( - "request.httpBody = try Data(contentsOf: URL(fileURLWithPath: {}))", - quoted(path) - )), + CodeBody::Form(fields) => { + lines.push(format!("request.httpBody = Data({}.utf8)", quoted(&form_encoded(fields)))); + } + CodeBody::File(path) => lines + .push(format!("request.httpBody = try Data(contentsOf: URL(fileURLWithPath: {}))", quoted(path))), } lines.push("let (data, response) = try await URLSession.shared.data(for: request)".to_string()); lines.push( - "print((response as! HTTPURLResponse).statusCode, String(decoding: data, as: UTF8.self))" - .to_string(), + "print((response as! HTTPURLResponse).statusCode, String(decoding: data, as: UTF8.self))".to_string(), ); lines.join("\n") } diff --git a/crates/engine/src/http/codegen/wget.rs b/crates/engine/src/http/codegen/wget.rs index d924bae8c..50a0dec12 100644 --- a/crates/engine/src/http/codegen/wget.rs +++ b/crates/engine/src/http/codegen/wget.rs @@ -11,10 +11,7 @@ pub fn write(request: &CodeRequest, multiline: bool) -> String { arguments.push("--max-redirect 0".to_string()); } for (name, value) in &request.headers { - arguments.push(format!( - "--header {}", - shell_quoted(&format!("{name}: {value}")) - )); + arguments.push(format!("--header {}", shell_quoted(&format!("{name}: {value}")))); } if let Some((user, password)) = &request.basic { // Without it, wget sends its credentials only once a server has asked for them. @@ -25,10 +22,7 @@ pub fn write(request: &CodeRequest, multiline: bool) -> String { match &request.body { CodeBody::Text(text) => arguments.push(format!("--body-data {}", shell_quoted(text))), CodeBody::Form(fields) => { - arguments.push(format!( - "--body-data {}", - shell_quoted(&form_encoded(fields)) - )); + arguments.push(format!("--body-data {}", shell_quoted(&form_encoded(fields)))); } CodeBody::File(path) => arguments.push(format!("--body-file {}", shell_quoted(path))), CodeBody::None | CodeBody::Multipart(_) => {} diff --git a/crates/engine/src/http/collection_run.rs b/crates/engine/src/http/collection_run.rs index 37233a9ae..efa7ab81a 100644 --- a/crates/engine/src/http/collection_run.rs +++ b/crates/engine/src/http/collection_run.rs @@ -28,15 +28,7 @@ pub(super) async fn run_step( step: RunStep<'_>, overlay: &mut Vec, ) -> Option<(runner::RunResult, Option)> { - let RunStep { - run, - iteration, - iterations, - index, - steps, - placed, - row, - } = step; + let RunStep { run, iteration, iterations, index, steps, placed, row } = step; say_run( engine, &run.id, @@ -88,13 +80,7 @@ pub(super) async fn run_step( if matches!(&answer, Err(error) if error.code == crate::error::ErrorCode::HttpCancelled) { return None; } - let result = runner::result_of( - iteration, - &request, - placed.path.clone(), - answer, - run.keep_responses, - ); + let result = runner::result_of(iteration, &request, placed.path.clone(), answer, run.keep_responses); Some((result, next)) } @@ -112,8 +98,5 @@ pub(super) async fn wait(runs: &runner::Runs, id: &str, millis: u32) -> bool { } pub(super) fn say_run(engine: &Engine, id: &str, step: runner::RunStep) { - engine.emit(EngineEvent::Run(runner::RunEvent { - id: id.to_string(), - step, - })); + engine.emit(EngineEvent::Run(runner::RunEvent { id: id.to_string(), step })); } diff --git a/crates/engine/src/http/console.rs b/crates/engine/src/http/console.rs index eef316d7e..dca07a344 100644 --- a/crates/engine/src/http/console.rs +++ b/crates/engine/src/http/console.rs @@ -28,14 +28,8 @@ pub struct ConsoleOrigin { impl ConsoleOrigin { #[must_use] pub fn of(id: Option<&str>, scripts: &[Script]) -> Option { - let script = scripts - .iter() - .find(|script| Some(script.id.as_str()) == id)?; - Some(Self { - kind: script.kind, - level: script.level, - name: script.name.clone(), - }) + let script = scripts.iter().find(|script| Some(script.id.as_str()) == id)?; + Some(Self { kind: script.kind, level: script.level, name: script.name.clone() }) } } @@ -126,18 +120,9 @@ pub fn secret_segments(text: &str) -> Vec<(String, bool)> { /// A request as the console shows it: each secret in force written as its name, an auth or a /// cookie header masked as the history masks it. #[must_use] -pub fn out( - exchange: &Exchange, - secrets: &[(String, String)], - by: Option, -) -> ConsoleLine { +pub fn out(exchange: &Exchange, secrets: &[(String, String)], by: Option) -> ConsoleLine { let shown = history::shown(exchange, secrets); - ConsoleLine::Out { - method: shown.method.to_string(), - url: shown.url, - headers: shown.headers, - by, - } + ConsoleLine::Out { method: shown.method.to_string(), url: shown.url, headers: shown.headers, by } } #[must_use] @@ -153,11 +138,7 @@ pub fn answered(response: &SentResponse, by: Option) -> ConsoleLi #[must_use] pub fn failed(error: AppError, by: Option) -> ConsoleLine { - ConsoleLine::Failed { - code: error.code, - params: error.params, - by, - } + ConsoleLine::Failed { code: error.code, params: error.params, by } } /// What a phase leaves in the console, in the order it happened: its logs and its sends, then @@ -205,12 +186,7 @@ pub fn phase( .map(|test| (now, tested(test, scripts, secrets))), ); if let Some(failure) = &outcome.failure { - lines.push(( - now, - ConsoleLine::Stopped { - stop: ScriptStop::of(failure, scripts), - }, - )); + lines.push((now, ConsoleLine::Stopped { stop: ScriptStop::of(failure, scripts) })); } lines } @@ -234,13 +210,7 @@ mod tests { use crate::http::send::{SendError, SentBody}; fn script(id: &str, kind: ScriptKind, level: ScriptLevel, name: &str) -> Script { - Script { - id: id.to_string(), - kind, - level, - name: name.to_string(), - ..Script::default() - } + Script { id: id.to_string(), kind, level, name: name.to_string(), ..Script::default() } } fn scripts() -> [Script; 2] { @@ -251,28 +221,15 @@ mod tests { } fn origin(script: &Script) -> ConsoleOrigin { - ConsoleOrigin { - kind: script.kind, - level: script.level, - name: script.name.clone(), - } + ConsoleOrigin { kind: script.kind, level: script.level, name: script.name.clone() } } fn header(key: &str, value: &str) -> KeyValue { - KeyValue { - key: key.to_string(), - value: value.to_string(), - ..KeyValue::default() - } + KeyValue { key: key.to_string(), value: value.to_string(), ..KeyValue::default() } } fn exchange(url: &str, headers: Vec) -> Exchange { - Exchange { - method: HttpMethod::Delete, - url: url.to_string(), - headers, - body: SentBody::None, - } + Exchange { method: HttpMethod::Delete, url: url.to_string(), headers, body: SentBody::None } } fn secrets() -> [(String, String); 1] { @@ -312,24 +269,14 @@ mod tests { #[test] fn a_request_leaves_with_its_secrets_written_as_their_names_and_its_auth_masked() { - let headers = vec![ - header("Authorization", "Bearer s3cr3t"), - header("X-Trace", "s3cr3t-1"), - ]; + let headers = vec![header("Authorization", "Bearer s3cr3t"), header("X-Trace", "s3cr3t-1")]; - let line = out( - &exchange("https://shop.test/me?key=s3cr3t", headers), - &secrets(), - None, - ); + let line = out(&exchange("https://shop.test/me?key=s3cr3t", headers), &secrets(), None); let expected = ConsoleLine::Out { method: "DELETE".to_string(), url: "https://shop.test/me?key={{token}}".to_string(), - headers: vec![ - header("Authorization", "Bearer ••••••••"), - header("X-Trace", "{{token}}-1"), - ], + headers: vec![header("Authorization", "Bearer ••••••••"), header("X-Trace", "{{token}}-1")], by: None, }; assert_eq!(line, expected); @@ -353,10 +300,7 @@ mod tests { by: Some(origin(&scripts()[0])), }; assert_eq!(answered(&response, Some(origin(&scripts()[0]))), expected); - assert_eq!( - lines(Vec::new(), vec![sent(Ok(response))], &Outcome::default())[1], - expected - ); + assert_eq!(lines(Vec::new(), vec![sent(Ok(response))], &Outcome::default())[1], expected); } /// The order it happened in: a script's send around what it logged meanwhile. @@ -364,11 +308,7 @@ mod tests { fn a_phase_says_its_logs_and_its_sends_in_the_order_they_came() { let logs = vec![log("s3cr3t between", "s1", 2), log("last", "gone", 4)]; - let said = lines( - logs, - vec![sent(Err(SendError::Refused("down".to_string())))], - &Outcome::default(), - ); + let said = lines(logs, vec![sent(Err(SendError::Refused("down".to_string())))], &Outcome::default()); let by = Some(origin(&scripts()[0])); let expected = [ @@ -378,21 +318,9 @@ mod tests { headers: Vec::new(), by: by.clone(), }, - ConsoleLine::Log { - level: LogLevel::Warn, - text: "{{token}} between".to_string(), - by: by.clone(), - }, - ConsoleLine::Failed { - code: ErrorCode::HttpRefused, - params: BTreeMap::new(), - by, - }, - ConsoleLine::Log { - level: LogLevel::Warn, - text: "last".to_string(), - by: None, - }, + ConsoleLine::Log { level: LogLevel::Warn, text: "{{token}} between".to_string(), by: by.clone() }, + ConsoleLine::Failed { code: ErrorCode::HttpRefused, params: BTreeMap::new(), by }, + ConsoleLine::Log { level: LogLevel::Warn, text: "last".to_string(), by: None }, ]; assert_eq!(said, expected); } @@ -437,14 +365,8 @@ mod tests { }; let outcome = Outcome { tests: vec![ - TestResult { - passed: true, - ..test("passes") - }, - TestResult { - skipped: true, - ..test("later") - }, + TestResult { passed: true, ..test("passes") }, + TestResult { skipped: true, ..test("later") }, failed, ], failure: Some(failure.clone()), @@ -462,12 +384,7 @@ mod tests { }; assert_eq!(said.len(), 3); assert_eq!(said[1], expected); - assert_eq!( - said[2], - ConsoleLine::Stopped { - stop: ScriptStop::of(&failure, &scripts()) - } - ); + assert_eq!(said[2], ConsoleLine::Stopped { stop: ScriptStop::of(&failure, &scripts()) }); } #[test] @@ -476,27 +393,13 @@ mod tests { ("", vec![]), ("plain", vec![("plain", false)]), ("{{token}}", vec![("{{token}}", true)]), - ( - "a {{b}} c {{d}}", - vec![ - ("a ", false), - ("{{b}}", true), - (" c ", false), - ("{{d}}", true), - ], - ), + ("a {{b}} c {{d}}", vec![("a ", false), ("{{b}}", true), (" c ", false), ("{{d}}", true)]), ("open {{b", vec![("open {{b", false)]), ("{{}} x", vec![("{{", false), ("}} x", false)]), - ( - "{{a{{b}}", - vec![("{{", false), ("a", false), ("{{b}}", true)], - ), + ("{{a{{b}}", vec![("{{", false), ("a", false), ("{{b}}", true)]), ] { let cut = secret_segments(text); - let cut: Vec<(&str, bool)> = cut - .iter() - .map(|(part, secret)| (part.as_str(), *secret)) - .collect(); + let cut: Vec<(&str, bool)> = cut.iter().map(|(part, secret)| (part.as_str(), *secret)).collect(); assert_eq!(cut, parts, "{text}"); } } diff --git a/crates/engine/src/http/cookies.rs b/crates/engine/src/http/cookies.rs index 1e1a5072e..ff912c431 100644 --- a/crates/engine/src/http/cookies.rs +++ b/crates/engine/src/http/cookies.rs @@ -59,25 +59,18 @@ fn is_public_suffix(domain: &str) -> bool { /// between —, read token by token: the first time, day, month and year found, a two-digit year /// taken to 1970–2069. `None` for a date that does not read: the cookie lasts the session. fn cookie_date(text: &str) -> Option> { - const MONTHS: [&str; 12] = [ - "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec", - ]; + const MONTHS: [&str; 12] = + ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]; let delimiter = |character: char| matches!(character, '\t' | ' '..='/' | ';'..='@' | '['..='`' | '{'..='~'); let leading_digits = |token: &str, at_most: usize| -> Option { let digits: String = token.chars().take_while(char::is_ascii_digit).collect(); - (1..=at_most) - .contains(&digits.len()) - .then(|| digits.parse().ok()) - .flatten() + (1..=at_most).contains(&digits.len()).then(|| digits.parse().ok()).flatten() }; let (mut time, mut day, mut month, mut year) = (None, None, None, None); for token in text.split(delimiter).filter(|token| !token.is_empty()) { if time.is_none() { - let parts: Vec> = token - .splitn(3, ':') - .map(|part| leading_digits(part, 2)) - .collect(); + let parts: Vec> = token.splitn(3, ':').map(|part| leading_digits(part, 2)).collect(); if let [Some(hour), Some(minute), Some(second)] = parts[..] { time = Some((hour, minute, second)); continue; @@ -122,16 +115,12 @@ fn cookie_date(text: &str) -> Option> { } fn domain_matches(host: &str, domain: &str) -> bool { - host == domain - || host - .strip_suffix(domain) - .is_some_and(|rest| rest.ends_with('.')) + host == domain || host.strip_suffix(domain).is_some_and(|rest| rest.ends_with('.')) } fn path_matches(path: &str, cookie: &str) -> bool { path == cookie - || (path.starts_with(cookie) - && (cookie.ends_with('/') || path[cookie.len()..].starts_with('/'))) + || (path.starts_with(cookie) && (cookie.ends_with('/') || path[cookie.len()..].starts_with('/'))) } /// The directory of the request's path: `/api/users` → `/api`. @@ -168,9 +157,7 @@ fn parse(line: &str, url: &Url, now: DateTime) -> Option { for attribute in parts { let (key, value) = attribute .split_once('=') - .map_or((attribute.trim(), ""), |(key, value)| { - (key.trim(), value.trim()) - }); + .map_or((attribute.trim(), ""), |(key, value)| (key.trim(), value.trim())); match key.to_ascii_lowercase().as_str() { "domain" if !value.is_empty() => { let domain = value.trim_start_matches('.').to_ascii_lowercase(); @@ -205,11 +192,7 @@ fn parse(line: &str, url: &Url, now: DateTime) -> Option { if let Some(seconds) = max_age { cookie.expires = Some(now + TimeDelta::seconds(seconds.max(0))); } - Some(if cookie.expired(now) { - Change::Remove(cookie) - } else { - Change::Set(cookie) - }) + Some(if cookie.expired(now) { Change::Remove(cookie) } else { Change::Set(cookie) }) } fn is_secure(url: &Url) -> bool { @@ -238,16 +221,10 @@ pub fn received(headers: &[KeyValue], url: &Url, now: DateTime) -> Vec, changes: &[Change]) { for change in changes { let (Change::Set(cookie) | Change::Remove(cookie)) = change; - let replaced = jar - .iter() - .find(|known| known.same_as(cookie)) - .and_then(|known| known.created); + let replaced = jar.iter().find(|known| known.same_as(cookie)).and_then(|known| known.created); jar.retain(|known| !known.same_as(cookie)); if let Change::Set(cookie) = change { - jar.push(JarCookie { - created: replaced.or(cookie.created), - ..cookie.clone() - }); + jar.push(JarCookie { created: replaced.or(cookie.created), ..cookie.clone() }); } } } @@ -259,19 +236,15 @@ pub fn matching<'a>(jar: &'a [JarCookie], url: &Url, now: DateTime) -> Vec< return Vec::new(); }; let secure = is_secure(url); - let mut sent: Vec<&JarCookie> = jar - .iter() - .filter(|cookie| !cookie.expired(now)) - .filter(|cookie| { - if cookie.host_only { - host == cookie.domain - } else { - domain_matches(&host, &cookie.domain) - } - }) - .filter(|cookie| path_matches(url.path(), &cookie.path)) - .filter(|cookie| secure || !cookie.secure) - .collect(); + let mut sent: Vec<&JarCookie> = + jar.iter() + .filter(|cookie| !cookie.expired(now)) + .filter(|cookie| { + if cookie.host_only { host == cookie.domain } else { domain_matches(&host, &cookie.domain) } + }) + .filter(|cookie| path_matches(url.path(), &cookie.path)) + .filter(|cookie| secure || !cookie.secure) + .collect(); sent.sort_by_key(|cookie| (std::cmp::Reverse(cookie.path.len()), cookie.created)); sent } @@ -300,11 +273,7 @@ mod tests { } fn set_cookie(value: &str) -> KeyValue { - KeyValue { - key: "Set-Cookie".to_string(), - value: value.to_string(), - ..KeyValue::default() - } + KeyValue { key: "Set-Cookie".to_string(), value: value.to_string(), ..KeyValue::default() } } /// The one change a `Set-Cookie` line makes, answered by `at`. @@ -347,14 +316,8 @@ mod tests { fn a_cookie_without_attributes_is_the_host_s_for_its_directory() { let cookie = set("sid=\"abc=1\"", "https://API.Shop.test/v1/users?x=1"); - assert_eq!( - (cookie.name.as_str(), cookie.value.as_str()), - ("sid", "abc=1") - ); - assert_eq!( - (cookie.domain.as_str(), cookie.host_only), - ("api.shop.test", true) - ); + assert_eq!((cookie.name.as_str(), cookie.value.as_str()), ("sid", "abc=1")); + assert_eq!((cookie.domain.as_str(), cookie.host_only), ("api.shop.test", true)); assert_eq!((cookie.path.as_str(), cookie.expires), ("/v1", None)); assert_eq!(set("a=1", "https://shop.test/users").path, "/"); assert_eq!(set("a=1", "https://shop.test").path, "/"); @@ -366,15 +329,8 @@ mod tests { fn an_answer_s_cookies_are_read_in_their_order() { let headers = [ set_cookie("first=1; HttpOnly; SameSite=Strict"), - KeyValue { - key: "Content-Type".to_string(), - value: "a=b".to_string(), - ..KeyValue::default() - }, - KeyValue { - key: "set-cookie".to_string(), - ..set_cookie("second=2; SameSite=") - }, + KeyValue { key: "Content-Type".to_string(), value: "a=b".to_string(), ..KeyValue::default() }, + KeyValue { key: "set-cookie".to_string(), ..set_cookie("second=2; SameSite=") }, set_cookie("no equals sign"), set_cookie(" =nameless"), ]; @@ -395,10 +351,7 @@ mod tests { (Some(now()), Some(now() + TimeDelta::microseconds(1))) ); assert!(read[0].http_only && !read[1].http_only); - assert_eq!( - (read[0].same_site.as_deref(), read[1].same_site.as_deref()), - (Some("Strict"), None) - ); + assert_eq!((read[0].same_site.as_deref(), read[1].same_site.as_deref()), (Some("Strict"), None)); } /// A server sets a cookie for itself or a domain above it, never for another, an address, @@ -410,19 +363,10 @@ mod tests { let empty = set("a=1; Domain=", "https://api.shop.test/"); let registered = set("a=1; Domain=exemple.co.uk", "https://api.exemple.co.uk/"); - assert_eq!( - (above.domain.as_str(), above.host_only), - ("shop.test", false) - ); - assert_eq!( - (itself.domain.as_str(), itself.host_only), - ("api.shop.test", true) - ); + assert_eq!((above.domain.as_str(), above.host_only), ("shop.test", false)); + assert_eq!((itself.domain.as_str(), itself.host_only), ("api.shop.test", true)); assert!(empty.host_only); - assert_eq!( - (registered.domain.as_str(), registered.host_only), - ("exemple.co.uk", false) - ); + assert_eq!((registered.domain.as_str(), registered.host_only), ("exemple.co.uk", false)); for (line, at) in [ ("a=1; Domain=other.test", "https://shop.test/"), ("a=1; Domain=api.shop.test", "https://shop.test/"), @@ -461,40 +405,21 @@ mod tests { let in_a_minute = Some(now() + TimeDelta::seconds(60)); assert_eq!( - set( - "a=1; Max-Age=60; Expires=Wed, 21 Oct 2026 07:28:00 GMT", - "https://shop.test/" - ) - .expires, + set("a=1; Max-Age=60; Expires=Wed, 21 Oct 2026 07:28:00 GMT", "https://shop.test/").expires, in_a_minute ); assert_eq!( - set( - "a=1; Expires=Wed, 21 Oct 2026 07:28:00 GMT; Max-Age=60", - "https://shop.test/" - ) - .expires, + set("a=1; Expires=Wed, 21 Oct 2026 07:28:00 GMT; Max-Age=60", "https://shop.test/").expires, in_a_minute ); assert_eq!(set("a=1; Max-Age=soon", "https://shop.test/").expires, None); let october = crate::db::iso8601::parse("2026-10-21T07:28:00.000Z").ok(); assert_eq!( - set( - "a=1; Expires=Wed, 21 Oct 2026 07:28:00 GMT; Expires=garbage", - "https://shop.test/" - ) - .expires, + set("a=1; Expires=Wed, 21 Oct 2026 07:28:00 GMT; Expires=garbage", "https://shop.test/").expires, october ); - for line in [ - "a=1; Max-Age=0", - "a=1; Max-Age=-5", - "a=1; Expires=Thu, 01 Jan 2026 00:00:00 GMT", - ] { - assert!( - matches!(one(line, "https://shop.test/"), Some(Change::Remove(_))), - "{line}" - ); + for line in ["a=1; Max-Age=0", "a=1; Max-Age=-5", "a=1; Expires=Thu, 01 Jan 2026 00:00:00 GMT"] { + assert!(matches!(one(line, "https://shop.test/"), Some(Change::Remove(_))), "{line}"); } } @@ -509,10 +434,7 @@ mod tests { ("Wednesday, 21-Oct-26 07:28:00 GMT", october), ("Wed Oct 21 07:28:00 2026", october), ("21 october 2026 7:28:0", october), - ( - "Sun, 01-Jan-69 00:00:01 GMT", - crate::db::iso8601::parse("2069-01-01T00:00:01.000Z").ok(), - ), + ("Sun, 01-Jan-69 00:00:01 GMT", crate::db::iso8601::parse("2069-01-01T00:00:01.000Z").ok()), ("mér., 21 oct. 2026 07:28:00", october), ("Wed, 21 Oct 2026 25:00:00 GMT", None), ("Wed, 31 Feb 2026 07:28:00 GMT", None), @@ -528,10 +450,7 @@ mod tests { assert_eq!(read.expires, expected, "{date}"); } assert!(matches!( - one( - "a=1; Expires=Thu, 01-Jan-70 00:00:01 GMT", - "https://shop.test/" - ), + one("a=1; Expires=Thu, 01-Jan-70 00:00:01 GMT", "https://shop.test/"), Some(Change::Remove(_)) )); } @@ -540,41 +459,21 @@ mod tests { /// a removal takes it away; another path is another cookie. #[test] fn a_change_replaces_or_removes_the_same_cookie() { - let mut jar = vec![ - cookie("a", "shop.test", "/"), - cookie("a", "shop.test", "/api"), - ]; + let mut jar = vec![cookie("a", "shop.test", "/"), cookie("a", "shop.test", "/api")]; let newer = JarCookie { value: "new".to_string(), created: Some(now() + TimeDelta::hours(1)), ..cookie("a", "shop.test", "/") }; - apply( - &mut jar, - &[ - Change::Set(newer), - Change::Set(cookie("b", "shop.test", "/")), - ], - ); + apply(&mut jar, &[Change::Set(newer), Change::Set(cookie("b", "shop.test", "/"))]); assert_eq!(jar.len(), 3); - let replaced = jar - .iter() - .find(|known| known.path == "/" && known.name == "a") - .unwrap(); - assert_eq!( - (replaced.value.as_str(), replaced.created), - ("new", Some(now())) - ); + let replaced = jar.iter().find(|known| known.path == "/" && known.name == "a").unwrap(); + assert_eq!((replaced.value.as_str(), replaced.created), ("new", Some(now()))); - apply( - &mut jar, - &[Change::Remove(cookie("a", "shop.test", "/api"))], - ); - let left: Vec<(&str, &str)> = jar - .iter() - .map(|known| (known.name.as_str(), known.path.as_str())) - .collect(); + apply(&mut jar, &[Change::Remove(cookie("a", "shop.test", "/api"))]); + let left: Vec<(&str, &str)> = + jar.iter().map(|known| (known.name.as_str(), known.path.as_str())).collect(); assert_eq!(left, [("a", "/"), ("b", "/")]); } @@ -583,10 +482,7 @@ mod tests { #[test] fn a_cookie_is_sent_to_its_host_or_below_its_domain() { let jar = [ - JarCookie { - host_only: true, - ..cookie("host", "shop.test", "/") - }, + JarCookie { host_only: true, ..cookie("host", "shop.test", "/") }, cookie("domain", "shop.test", "/"), ]; @@ -599,10 +495,7 @@ mod tests { /// A path and what lies under it, never a name that merely starts like it. #[test] fn a_cookie_is_sent_under_its_path() { - let jar = [ - cookie("api", "shop.test", "/api"), - cookie("slash", "shop.test", "/v1/"), - ]; + let jar = [cookie("api", "shop.test", "/api"), cookie("slash", "shop.test", "/v1/")]; assert_eq!(sent(&jar, "https://shop.test/api"), ["api"]); assert_eq!(sent(&jar, "https://shop.test/api/users"), ["api"]); @@ -615,18 +508,9 @@ mod tests { #[test] fn an_expired_or_secure_cookie_is_held_back() { let jar = [ - JarCookie { - expires: Some(now()), - ..cookie("expired", "shop.test", "/") - }, - JarCookie { - expires: Some(now() + TimeDelta::seconds(1)), - ..cookie("later", "shop.test", "/") - }, - JarCookie { - secure: true, - ..cookie("secure", "shop.test", "/") - }, + JarCookie { expires: Some(now()), ..cookie("expired", "shop.test", "/") }, + JarCookie { expires: Some(now() + TimeDelta::seconds(1)), ..cookie("later", "shop.test", "/") }, + JarCookie { secure: true, ..cookie("secure", "shop.test", "/") }, ]; assert_eq!(sent(&jar, "http://shop.test/"), ["later"]); @@ -639,10 +523,7 @@ mod tests { #[test] fn the_cookie_header_sends_the_longest_paths_first_then_the_oldest() { let jar = [ - JarCookie { - created: Some(now() + TimeDelta::seconds(2)), - ..cookie("young", "shop.test", "/") - }, + JarCookie { created: Some(now() + TimeDelta::seconds(2)), ..cookie("young", "shop.test", "/") }, cookie("old", "shop.test", "/"), cookie("deep", "shop.test", "/api"), ]; diff --git a/crates/engine/src/http/cookies/store.rs b/crates/engine/src/http/cookies/store.rs index 04cad0e50..3092c38e2 100644 --- a/crates/engine/src/http/cookies/store.rs +++ b/crates/engine/src/http/cookies/store.rs @@ -24,18 +24,12 @@ pub struct CookieDomain { } fn open(vault: &Vault, id: String, sealed: &str) -> Result { - let cookie = - serde_json::from_str(&vault.open(sealed)?).map_err(|_| StorageError::CorruptRow { - id: id.clone(), - field: "cookie", - })?; + let cookie = serde_json::from_str(&vault.open(sealed)?) + .map_err(|_| StorageError::CorruptRow { id: id.clone(), field: "cookie" })?; Ok(StoredCookie { id, cookie }) } -fn read( - connection: &mut SqliteConnection, - vault: &Vault, -) -> Result, StorageError> { +fn read(connection: &mut SqliteConnection, vault: &Vault) -> Result, StorageError> { http_cookies::table .select((http_cookies::id, http_cookies::cookie)) .load::<(String, String)>(connection)? @@ -56,11 +50,7 @@ pub fn jar(connection: &mut Library, now: DateTime) -> Result, -) -> Result<(), StorageError> { +pub fn apply(connection: &mut Library, changes: &[Change], now: DateTime) -> Result<(), StorageError> { if changes.is_empty() { return Ok(()); } @@ -76,10 +66,7 @@ pub fn apply( known.retain(|stored| !stored.cookie.same_as(cookie)); if let Change::Set(cookie) = change { // As the jar held in memory does: a replaced cookie keeps its place. - let cookie = &JarCookie { - created: replaced.or(cookie.created), - ..cookie.clone() - }; + let cookie = &JarCookie { created: replaced.or(cookie.created), ..cookie.clone() }; let id = Uuid::new_v4().to_string(); let json = serde_json::to_string(cookie) .map_err(|error| StorageError::Vault(format!("unwritable cookie: {error}")))?; @@ -90,16 +77,11 @@ pub fn apply( http_cookies::cookie.eq(vault.seal(&json)?), )) .execute(connection)?; - known.push(StoredCookie { - id, - cookie: cookie.clone(), - }); + known.push(StoredCookie { id, cookie: cookie.clone() }); } } - diesel::delete( - http_cookies::table.filter(http_cookies::expires_at.le(iso8601::format(now))), - ) - .execute(connection)?; + diesel::delete(http_cookies::table.filter(http_cookies::expires_at.le(iso8601::format(now)))) + .execute(connection)?; Ok(()) }) } @@ -119,10 +101,7 @@ pub fn by_domain(connection: &mut Library) -> Result, StorageE for stored in cookies { match domains.last_mut() { Some(last) if last.domain == stored.cookie.domain => last.cookies.push(stored), - _ => domains.push(CookieDomain { - domain: stored.cookie.domain.clone(), - cookies: vec![stored], - }), + _ => domains.push(CookieDomain { domain: stored.cookie.domain.clone(), cookies: vec![stored] }), } } Ok(domains) @@ -134,9 +113,7 @@ fn removed(count: usize) -> u32 { pub fn delete(connection: &mut Library, id: &str) -> Result { let (connection, _) = connection.split(); - Ok(removed( - diesel::delete(http_cookies::table.find(id)).execute(connection)?, - )) + Ok(removed(diesel::delete(http_cookies::table.find(id)).execute(connection)?)) } /// A domain's cookies, answering how many went. @@ -147,10 +124,7 @@ pub fn delete_domain(connection: &mut Library, domain: &str) -> Result Result { @@ -161,9 +135,7 @@ pub fn count(connection: &mut Library) -> Result { pub fn clear(connection: &mut Library) -> Result { let (connection, _) = connection.split(); - Ok(removed( - diesel::delete(http_cookies::table).execute(connection)?, - )) + Ok(removed(diesel::delete(http_cookies::table).execute(connection)?)) } #[cfg(test)] @@ -191,10 +163,7 @@ mod tests { } fn lasting(name: &str, seconds: i64) -> JarCookie { - JarCookie { - expires: Some(now() + TimeDelta::seconds(seconds)), - ..cookie(name, "shop.test", "/") - } + JarCookie { expires: Some(now() + TimeDelta::seconds(seconds)), ..cookie(name, "shop.test", "/") } } fn names(jar: &[JarCookie]) -> Vec<&str> { @@ -227,33 +196,20 @@ mod tests { }; let later = now() + TimeDelta::seconds(10); - apply( - &mut library, - &[ - Change::Set(newer), - Change::Remove(cookie("b", "shop.test", "/")), - ], - later, - ) - .unwrap(); + apply(&mut library, &[Change::Set(newer), Change::Remove(cookie("b", "shop.test", "/"))], later) + .unwrap(); let jar = jar(&mut library, now()).unwrap(); assert_eq!(names(&jar), ["a"]); - assert_eq!( - (jar[0].value.as_str(), jar[0].created), - ("new", Some(now())) - ); + assert_eq!((jar[0].value.as_str(), jar[0].created), ("new", Some(now()))); assert_eq!(count(&mut library).unwrap(), 1); } /// What has expired is never sent, even before a write sweeps it. #[test] fn the_jar_read_leaves_out_what_has_expired() { - let mut library = library_with(&[ - lasting("expired", 0), - lasting("later", 1), - cookie("session", "shop.test", "/"), - ]); + let mut library = + library_with(&[lasting("expired", 0), lasting("later", 1), cookie("session", "shop.test", "/")]); let jar = jar(&mut library, now()).unwrap(); @@ -295,10 +251,7 @@ mod tests { .collect(); assert_eq!( shown, - [ - ("a.test", vec![("a", "/"), ("b", "/"), ("b", "/x")]), - ("b.test", vec![("a", "/")]), - ] + [("a.test", vec![("a", "/"), ("b", "/"), ("b", "/x")]), ("b.test", vec![("a", "/")]),] ); } @@ -331,13 +284,7 @@ mod tests { .execute(library.db()) .unwrap(); - assert!(matches!( - jar(&mut library, now()), - Err(StorageError::CorruptRow { - field: "cookie", - .. - }) - )); + assert!(matches!(jar(&mut library, now()), Err(StorageError::CorruptRow { field: "cookie", .. }))); } /// Sealed whole: neither a name nor a value, nor its domain, is in the database in the clear. @@ -345,10 +292,8 @@ mod tests { fn a_cookie_is_sealed_whole() { let mut library = library_with(&[cookie("session_id", "bank.test", "/")]); - let stored: Vec = http_cookies::table - .select(http_cookies::cookie) - .load(library.db()) - .unwrap(); + let stored: Vec = + http_cookies::table.select(http_cookies::cookie).load(library.db()).unwrap(); assert_eq!(stored.len(), 1); for clear in ["session_id", "bank.test"] { diff --git a/crates/engine/src/http/environments.rs b/crates/engine/src/http/environments.rs index c1f3fa143..a3137932c 100644 --- a/crates/engine/src/http/environments.rs +++ b/crates/engine/src/http/environments.rs @@ -191,25 +191,15 @@ mod tests { use super::*; fn variable(name: &str, value: &str) -> Variable { - Variable { - name: name.to_string(), - value: value.to_string(), - ..Variable::default() - } + Variable { name: name.to_string(), value: value.to_string(), ..Variable::default() } } fn number(name: &str, value: &str) -> Variable { - Variable { - kind: VariableKind::Number, - ..variable(name, value) - } + Variable { kind: VariableKind::Number, ..variable(name, value) } } fn secret(name: &str) -> Variable { - Variable { - kind: VariableKind::Secret, - ..variable(name, "s") - } + Variable { kind: VariableKind::Secret, ..variable(name, "s") } } /// What a `{{…}}` can hold: letters, digits, `_` and `-`, as a snippet's field. @@ -242,10 +232,7 @@ mod tests { number("many", "many"), number("endless", "inf"), variable(" host ", "again"), - Variable { - enabled: false, - ..variable("bad name", "x") - }, + Variable { enabled: false, ..variable("bad name", "x") }, variable(" ", "unnamed"), ]; @@ -269,20 +256,9 @@ mod tests { #[test] fn a_set_counts_its_named_variables_and_its_secrets() { - let counts = variable_counts(&[ - variable("a", "1"), - secret("b"), - secret(" "), - variable("", "x"), - ]); + let counts = variable_counts(&[variable("a", "1"), secret("b"), secret(" "), variable("", "x")]); - assert_eq!( - counts, - VariableCounts { - count: 2, - secrets: 1 - } - ); + assert_eq!(counts, VariableCounts { count: 2, secrets: 1 }); } /// What reads without changing anything goes unasked; a socket asks before it opens, @@ -300,10 +276,7 @@ mod tests { !method.changes_nothing(), "{method:?}" ); - assert!( - asks_before_sending(RequestKind::Websocket, method), - "{method:?}" - ); + assert!(asks_before_sending(RequestKind::Websocket, method), "{method:?}"); } } @@ -316,10 +289,7 @@ mod tests { protected: false, variables: vec![variable("host", "staging")], }; - let patch = EnvironmentPatch { - protected: Some(true), - ..EnvironmentPatch::default() - }; + let patch = EnvironmentPatch { protected: Some(true), ..EnvironmentPatch::default() }; let full = EnvironmentPatch { name: Some("ignored".to_string()), colour: Some(FolderColour::Red), @@ -330,13 +300,7 @@ mod tests { let protected = document.clone().patched(&patch, None); let renamed = document.clone().patched(&full, Some("Production")); - assert_eq!( - protected, - EnvironmentDocument { - protected: true, - ..document - } - ); + assert_eq!(protected, EnvironmentDocument { protected: true, ..document }); assert_eq!( renamed, EnvironmentDocument { diff --git a/crates/engine/src/http/environments/store.rs b/crates/engine/src/http/environments/store.rs index cb23f82ea..84cdcc63b 100644 --- a/crates/engine/src/http/environments/store.rs +++ b/crates/engine/src/http/environments/store.rs @@ -26,10 +26,8 @@ struct EnvironmentRow { impl EnvironmentRow { fn document(&self, vault: &Vault) -> Result { - serde_json::from_str(&vault.open(&self.document)?).map_err(|_| StorageError::CorruptRow { - id: self.id.clone(), - field: "document", - }) + serde_json::from_str(&vault.open(&self.document)?) + .map_err(|_| StorageError::CorruptRow { id: self.id.clone(), field: "document" }) } fn open(self, vault: &Vault) -> Result { @@ -58,10 +56,7 @@ fn rows(connection: &mut SqliteConnection) -> Result, Storag .load(connection)?) } -fn environments( - connection: &mut SqliteConnection, - vault: &Vault, -) -> Result, StorageError> { +fn environments(connection: &mut SqliteConnection, vault: &Vault) -> Result, StorageError> { rows(connection)? .into_iter() .filter(|row| row.kind == ENVIRONMENT) @@ -80,11 +75,7 @@ fn find(connection: &mut SqliteConnection, id: &str) -> Result, -) -> Result<(), StorageError> { +fn refuse_taken(held: &[Environment], name: &str, except_id: Option<&str>) -> Result<(), StorageError> { let pairs = held .iter() .map(|environment| (environment.id.as_str(), environment.name.as_str())); @@ -105,10 +96,7 @@ pub fn list(connection: &mut Library) -> Result environments.push(row.open(vault)?); } } - Ok(HttpEnvironments { - globals, - environments, - }) + Ok(HttpEnvironments { globals, environments }) } /// One environment, for the send that resolves from it. @@ -138,11 +126,7 @@ fn insert( } /// Last, in the next of the five colours: two made one after the other differ. -pub fn create( - connection: &mut Library, - name: &str, - now: DateTime, -) -> Result { +pub fn create(connection: &mut Library, name: &str, now: DateTime) -> Result { connection.transaction(|connection, vault| { let held = environments(connection, vault)?; refuse_taken(&held, name, None)?; @@ -189,15 +173,11 @@ pub fn save_globals( connection.transaction(|connection, vault| { let document = seal( vault, - &EnvironmentDocument { - variables: variables.to_vec(), - ..EnvironmentDocument::default() - }, + &EnvironmentDocument { variables: variables.to_vec(), ..EnvironmentDocument::default() }, )?; - let changed = - diesel::update(http_environments::table.filter(http_environments::kind.eq(GLOBALS))) - .set(http_environments::document.eq(&document)) - .execute(connection)?; + let changed = diesel::update(http_environments::table.filter(http_environments::kind.eq(GLOBALS))) + .set(http_environments::document.eq(&document)) + .execute(connection)?; if changed == 0 { diesel::insert_into(http_environments::table) .values(( @@ -224,10 +204,7 @@ pub fn duplicate( connection.transaction(|connection, vault| { let original = find(connection, id)?; refuse_taken(&environments(connection, vault)?, name, None)?; - let document = EnvironmentDocument { - name: name.to_string(), - ..original.document(vault)? - }; + let document = EnvironmentDocument { name: name.to_string(), ..original.document(vault)? }; diesel::update( http_environments::table .filter(http_environments::kind.eq(ENVIRONMENT)) diff --git a/crates/engine/src/http/error.rs b/crates/engine/src/http/error.rs index 0386ec8a4..a1565f128 100644 --- a/crates/engine/src/http/error.rs +++ b/crates/engine/src/http/error.rs @@ -42,31 +42,22 @@ impl From for AppError { .and("unit", unit) .set_by(&limit.set_by) } - SendError::TooManyRedirects(limit) => { - Self::new(ErrorCode::HttpTooManyRedirects, detail) - .and("count", &limit.value.to_string()) - .set_by(&limit.set_by) - } + SendError::TooManyRedirects(limit) => Self::new(ErrorCode::HttpTooManyRedirects, detail) + .and("count", &limit.value.to_string()) + .set_by(&limit.set_by), SendError::FileUnreadable(path) => { Self::with(ErrorCode::HttpFileUnreadable, detail, "path", &path) } - SendError::FileTooLarge(path) => { - Self::with(ErrorCode::HttpFileTooLarge, detail, "path", &path) - .and("limit", &crate::http::send::SENT_FILE_MEGABYTES.to_string()) - } + SendError::FileTooLarge(path) => Self::with(ErrorCode::HttpFileTooLarge, detail, "path", &path) + .and("limit", &crate::http::send::SENT_FILE_MEGABYTES.to_string()), SendError::Cancelled => Self::new(ErrorCode::HttpCancelled, detail), SendError::Fell => Self::new(ErrorCode::HttpFell, detail), SendError::GraphqlVariables(_) => Self::new(ErrorCode::HttpGraphqlVariables, detail), - SendError::Handshake(status) => Self::with( - ErrorCode::HttpWebsocketRefused, - detail, - "status", - &status.to_string(), - ), - // The cause's own words: « Erreur réseau » alone tells nothing. - SendError::Network(cause) => { - Self::with(ErrorCode::HttpNetwork, detail, "cause", &cause) + SendError::Handshake(status) => { + Self::with(ErrorCode::HttpWebsocketRefused, detail, "status", &status.to_string()) } + // The cause's own words: « Erreur réseau » alone tells nothing. + SendError::Network(cause) => Self::with(ErrorCode::HttpNetwork, detail, "cause", &cause), SendError::SocketScheme { twin } => { let refused = Self::new(ErrorCode::HttpWebsocketScheme, detail); match twin { @@ -74,11 +65,7 @@ impl From for AppError { None => refused, } } - SendError::Header { - name, - fault, - set_by, - } => { + SendError::Header { name, fault, set_by } => { let code = match fault { HeaderFault::Name => ErrorCode::HttpHeaderName, HeaderFault::Value => ErrorCode::HttpHeaderValue, @@ -107,12 +94,8 @@ impl From for AppError { match error { ScriptError::Stopped(stop) => { - let mut refused = Self::with( - ErrorCode::HttpScript, - detail, - "failure", - &stop.kind.to_string(), - ); + let mut refused = + Self::with(ErrorCode::HttpScript, detail, "failure", &stop.kind.to_string()); for (key, value) in [ ("level", stop.level.map(|level| level.to_string())), ("name", stop.name), @@ -131,19 +114,11 @@ impl From for AppError { } ScriptError::Skipped => Self::new(ErrorCode::HttpScriptSkipped, detail), ScriptError::File(path) => Self::with(ErrorCode::HttpScriptFile, detail, "path", &path), - ScriptError::Method(method) => { - Self::with(ErrorCode::HttpScriptMethod, detail, "method", &method) + ScriptError::Method(method) => Self::with(ErrorCode::HttpScriptMethod, detail, "method", &method), + ScriptError::Protected { method, environment } => { + Self::with(ErrorCode::HttpScriptProtected, detail, "method", &method.to_string()) + .and("environment", &environment) } - ScriptError::Protected { - method, - environment, - } => Self::with( - ErrorCode::HttpScriptProtected, - detail, - "method", - &method.to_string(), - ) - .and("environment", &environment), } } } diff --git a/crates/engine/src/http/extract.rs b/crates/engine/src/http/extract.rs index f81814295..2031d7f6c 100644 --- a/crates/engine/src/http/extract.rs +++ b/crates/engine/src/http/extract.rs @@ -105,11 +105,7 @@ pub fn variable_name_of(path: &str) -> String { name.push(c); } } - if name.starts_with(|c: char| c.is_ascii_alphabetic()) { - name - } else { - format!("value{name}") - } + if name.starts_with(|c: char| c.is_ascii_alphabetic()) { name } else { format!("value{name}") } } /// What a key reads as when it holds something to keep out of sight. diff --git a/crates/engine/src/http/flight.rs b/crates/engine/src/http/flight.rs index 30e1ef108..0736b22d3 100644 --- a/crates/engine/src/http/flight.rs +++ b/crates/engine/src/http/flight.rs @@ -8,16 +8,15 @@ use chrono::Utc; use super::scripts::around::{self, Around}; use super::scripts::model::{ - Extracted, FailureKind, Job, LayerScope, LogEntry, Outcome, Phase, RequestFault, Script, - ScriptError, ScriptFailure, ScriptInfo, ScriptLayer, ScriptRequest, ScriptStop, VariableWrite, - WriteScope, + Extracted, FailureKind, Job, LayerScope, LogEntry, Outcome, Phase, RequestFault, Script, ScriptError, + ScriptFailure, ScriptInfo, ScriptLayer, ScriptRequest, ScriptStop, VariableWrite, WriteScope, }; use super::scripts::network::{self, Network}; use super::scripts::process::ScriptProcess; use super::scripts::session::Session; use super::{ - console, cookies, environments, extract, history, inherited_of, layers_for, model, runner, - send, settings, store, transport, variables, + console, cookies, environments, extract, history, inherited_of, layers_for, model, runner, send, + settings, store, transport, variables, }; use crate::db::{self, lock, lock_library}; use crate::error::AppError; @@ -93,10 +92,7 @@ impl Flight { confirmed: false, files: Vec::new(), collection_id: None, - info: ScriptInfo { - iteration_count: 1, - ..ScriptInfo::default() - }, + info: ScriptInfo { iteration_count: 1, ..ScriptInfo::default() }, by: environments::FilledBy::default(), heard: (Vec::new(), Vec::new()), record: true, @@ -110,10 +106,7 @@ impl Flight { } } - pub(super) async fn send( - &mut self, - request: send::SendRequest, - ) -> Result { + pub(super) async fn send(&mut self, request: send::SendRequest) -> Result { let send::SendRequest { id, kind, @@ -127,20 +120,8 @@ impl Flight { confirmed, files, } = request; - let Prepared { - inherited, - mut layers, - environment, - jar, - library, - } = prepare( - &self.engine, - &document, - collection_id.clone(), - folder_id, - environment_id, - ) - .await?; + let Prepared { inherited, mut layers, environment, jar, library } = + prepare(&self.engine, &document, collection_id.clone(), folder_id, environment_id).await?; let around = Around::of(&document.scripts, &name, &inherited); self.jar = jar; self.library = library; @@ -153,12 +134,7 @@ impl Flight { self.layered(&mut layers); // What the request reads as the user wrote it: a file the scripts add waits for a yes. let own = (!around.before.is_empty()).then(|| files_read(&document, &inherited, &layers)); - let mut going = Going { - kind, - method, - document, - layers, - }; + let mut going = Going { kind, method, document, layers }; if !around.before.is_empty() { self.before(&around.before, &mut going).await?; } @@ -215,10 +191,8 @@ impl Flight { fn named(&mut self, name: &str, request_id: Option<&str>) { self.info.request_name = name.to_string(); self.info.request_id = request_id.map(str::to_string); - self.by = environments::FilledBy { - request_id: request_id.map(str::to_string), - name: name.to_string(), - }; + self.by = + environments::FilledBy { request_id: request_id.map(str::to_string), name: name.to_string() }; } /// What a run lays over the levels read: what its scripts wrote, kept for it alone, and @@ -231,12 +205,10 @@ impl Flight { } fn sent_environment(&self) -> Option { - self.environment - .as_ref() - .map(|environment| history::SentEnvironment { - name: environment.name.clone(), - colour: environment.colour, - }) + self.environment.as_ref().map(|environment| history::SentEnvironment { + name: environment.name.clone(), + colour: environment.colour, + }) } /// The request sent, the lock free; `Err` alone when « Annuler » stopped it, a failure to @@ -246,11 +218,7 @@ impl Flight { id: &str, outgoing: send::Outgoing, ) -> Result, AppError> { - let (answer, cookies_set) = self - .engine - .sending - .run(&self.engine.runtime, id, outgoing) - .await; + let (answer, cookies_set) = self.engine.sending.run(&self.engine.runtime, id, outgoing).await; if matches!(answer, Err(send::SendError::Cancelled)) { return Err(send::SendError::Cancelled.into()); } @@ -260,11 +228,9 @@ impl Flight { Utc::now(), match &answer { Ok(response) => console::answered(response, None), - Err(error) => console::ConsoleLine::Failed { - code: error.code, - params: error.params.clone(), - by: None, - }, + Err(error) => { + console::ConsoleLine::Failed { code: error.code, params: error.params.clone(), by: None } + } }, ); Ok(answer) @@ -287,18 +253,11 @@ impl Flight { let finished = outcome.is_some(); if let Some(outcome) = outcome { let extractions = std::mem::take(&mut going.document.extractions); - response.scripts.extracted = self - .extract(&extractions, response, &mut going.layers) - .await; + response.scripts.extracted = self.extract(&extractions, response, &mut going.layers).await; // Said once the extractions ran: a value one makes a secret is hidden in the logs. self.report(&answered, &outcome, &going.layers); self.follow(&outcome); - for missed in response - .scripts - .extracted - .iter() - .filter(|extracted| !extracted.found) - { + for missed in response.scripts.extracted.iter().filter(|extracted| !extracted.found) { self.say( Utc::now(), console::ConsoleLine::Missed { @@ -323,10 +282,7 @@ impl Flight { request: ScriptRequest::of(going.kind, going.method, &going.document), response: None, layers: self.script_layers(going), - environment: self - .environment - .as_ref() - .map(|environment| environment.name.clone()), + environment: self.environment.as_ref().map(|environment| environment.name.clone()), cookies: network::cookies_for(self.jar().as_deref(), url), info: self.info.clone(), } @@ -337,11 +293,7 @@ impl Flight { if !self.data.is_empty() { layers.insert( 0, - ScriptLayer { - scope: LayerScope::Data, - from: String::new(), - values: self.data.clone(), - }, + ScriptLayer { scope: LayerScope::Data, from: String::new(), values: self.data.clone() }, ); } layers @@ -355,10 +307,7 @@ impl Flight { self.write(&outcome.writes, &mut going.layers).await; self.report(scripts, &outcome, &going.layers); self.follow(&outcome); - let refused = self - .session - .as_mut() - .and_then(|session| session.network.refused_file.take()); + let refused = self.session.as_mut().and_then(|session| session.network.refused_file.take()); if let Some(path) = refused { return Err(ScriptError::File(path).into()); } @@ -386,9 +335,7 @@ impl Flight { .into()); } if !outcome.locals.is_empty() { - going - .layers - .insert(0, around::locals_layer(&outcome.locals)); + going.layers.insert(0, around::locals_layer(&outcome.locals)); } Ok(()) } @@ -408,10 +355,7 @@ impl Flight { let outcome = self.run(job).await.ok()?; self.write(&outcome.writes, &mut going.layers).await; response.scripts.tests.clone_from(&outcome.tests); - response.scripts.failure = outcome - .failure - .as_ref() - .map(|failure| ScriptStop::of(failure, scripts)); + response.scripts.failure = outcome.failure.as_ref().map(|failure| ScriptStop::of(failure, scripts)); Some(outcome) } @@ -426,10 +370,7 @@ impl Flight { self.transport, self.jar.take(), self.confirmed - || !self - .environment - .as_ref() - .is_some_and(|environment| environment.protected), + || !self.environment.as_ref().is_some_and(|environment| environment.protected), ); network.files.clone_from(&self.files); Session::new(host, network) @@ -451,10 +392,7 @@ impl Flight { let outcome = match ran { Ok((mut session, outcome)) => { self.changes.append(&mut session.network.changes); - self.heard = ( - std::mem::take(&mut session.logs), - std::mem::take(&mut session.network.sent), - ); + self.heard = (std::mem::take(&mut session.logs), std::mem::take(&mut session.network.sent)); self.session = Some(session); outcome } @@ -475,11 +413,7 @@ impl Flight { response: &send::SentResponse, layers: &mut [variables::VariableLayer], ) -> Vec { - let scope = if self.environment.is_some() { - WriteScope::Environment - } else { - WriteScope::Globals - }; + let scope = if self.environment.is_some() { WriteScope::Environment } else { WriteScope::Globals }; let mut writes = Vec::new(); let extracted = extractions .iter() @@ -516,11 +450,7 @@ impl Flight { /// What the send did to the jar, for the scripts after it to read. fn received(&mut self, changes: Vec) { - if let Some(jar) = self - .session - .as_mut() - .and_then(|session| session.network.jar.as_mut()) - { + if let Some(jar) = self.session.as_mut().and_then(|session| session.network.jar.as_mut()) { cookies::apply(jar, &changes); } self.changes.extend(changes); @@ -550,12 +480,7 @@ impl Flight { /// What the last phase logged and sent, the tests that failed and what stopped it, each /// secret in force — those the phase wrote included — written as its name. - fn report( - &mut self, - scripts: &[Script], - outcome: &Outcome, - layers: &[variables::VariableLayer], - ) { + fn report(&mut self, scripts: &[Script], outcome: &Outcome, layers: &[variables::VariableLayer]) { let (logs, sends) = std::mem::take(&mut self.heard); let secrets = variables::Resolver::new(layers).secrets(); for (at, line) in console::phase(logs, sends, outcome, scripts, &secrets) { @@ -574,10 +499,7 @@ impl Flight { return; } let writes = writes.to_vec(); - let environment_id = self - .environment - .as_ref() - .map(|environment| environment.id.clone()); + let environment_id = self.environment.as_ref().map(|environment| environment.id.clone()); let collection_id = self.collection_id.clone(); let by = self.by.clone(); let library = self.library; @@ -607,13 +529,7 @@ impl Flight { /// The history and the jar, written under the lock again, and never at the answer's expense. pub(super) async fn keep(self) { - let Self { - engine, - library, - sent, - changes, - .. - } = self; + let Self { engine, library, sent, changes, .. } = self; if sent.is_none() && changes.is_empty() { return; } @@ -626,23 +542,14 @@ impl Flight { }; if let Some(sent) = &sent { let (summary, record) = history::record_of(sent); - history::store::record( - &mut connection, - sent.request_id.as_deref(), - &summary, - &record, - now, - )?; + history::store::record(&mut connection, sent.request_id.as_deref(), &summary, &record, now)?; } cookies::store::apply(&mut connection, &changes, now)?; Ok(()) }) .await; if let Err(error) = kept { - log::warn!( - "A send's history or cookies were not kept: {}", - error.for_log() - ); + log::warn!("A send's history or cookies were not kept: {}", error.for_log()); engine.emit(EngineEvent::SendNotKept); } } @@ -678,11 +585,7 @@ async fn prepare( db::run(Arc::clone(engine), move |engine| { let db = &engine.db; let mut connection = lock(db)?; - let inherited = inherited_of( - &mut connection, - collection_id.as_deref(), - folder_id.as_deref(), - )?; + let inherited = inherited_of(&mut connection, collection_id.as_deref(), folder_id.as_deref())?; let layers = layers_for(&mut connection, &own, &inherited, environment_id.as_deref())?; let environment = environment_id .as_deref() @@ -695,13 +598,7 @@ async fn prepare( } else { None }; - Ok(Prepared { - inherited, - layers, - environment, - jar, - library: connection.number(), - }) + Ok(Prepared { inherited, layers, environment, jar, library: connection.number() }) }) .await } @@ -734,27 +631,17 @@ fn keep_writes( } if wrote_to(WriteScope::Globals) { let globals = environments::store::list(connection)?.globals; - let globals = around::written( - &globals, - around::writes_to(writes, WriteScope::Globals), - Some(by), - ); + let globals = around::written(&globals, around::writes_to(writes, WriteScope::Globals), Some(by)); environments::store::save_globals(connection, &globals, Utc::now())?; wrote = true; } if let Some(id) = collection_id && wrote_to(WriteScope::Collection) { - let item = model::HttpItem { - kind: model::HttpItemKind::Collection, - id: id.to_string(), - }; + let item = model::HttpItem { kind: model::HttpItemKind::Collection, id: id.to_string() }; let mut held = store::settings(connection, &item)?; - held.variables = around::written( - &held.variables, - around::writes_to(writes, WriteScope::Collection), - Some(by), - ); + held.variables = + around::written(&held.variables, around::writes_to(writes, WriteScope::Collection), Some(by)); store::save_settings(connection, &item, &held)?; wrote = true; } diff --git a/crates/engine/src/http/graphql.rs b/crates/engine/src/http/graphql.rs index 840a66d12..6ab6f41b1 100644 --- a/crates/engine/src/http/graphql.rs +++ b/crates/engine/src/http/graphql.rs @@ -117,8 +117,7 @@ impl Reader<'_> { } fn word(&mut self) -> String { - std::iter::from_fn(|| self.next_if(|next| next.is_ascii_alphanumeric() || next == '_')) - .collect() + std::iter::from_fn(|| self.next_if(|next| next.is_ascii_alphanumeric() || next == '_')).collect() } fn skip_spaces(&mut self) { @@ -164,11 +163,7 @@ impl Reader<'_> { /// One pass over a query, past its strings and comments: its operations with what each /// declares, and the first brace, parenthesis or string that does not pair. fn scan(query: &str) -> Scanned { - let mut reader = Reader { - chars: query.chars().peekable(), - line: 1, - column: 1, - }; + let mut reader = Reader { chars: query.chars().peekable(), line: 1, column: 1 }; let mut scanned = Scanned::default(); // What is open, and where it was opened. let mut open: Vec<(char, u32, u32)> = Vec::new(); @@ -177,11 +172,7 @@ fn scan(query: &str) -> Scanned { // The depth at which the operation being read declares its variables. let mut declaring: Option = None; let fault = |scanned: &mut Scanned, fault, line, column| { - scanned.problem.get_or_insert(QueryProblem { - fault, - line, - column, - }); + scanned.problem.get_or_insert(QueryProblem { fault, line, column }); }; while let Some((read, line, column)) = reader.next() { @@ -209,11 +200,8 @@ fn scan(query: &str) -> Scanned { if open.last().is_some_and(|(opened, ..)| *opened == pair) { open.pop(); } else { - let stray = if read == '}' { - QueryFault::StrayBrace - } else { - QueryFault::StrayParenthesis - }; + let stray = + if read == '}' { QueryFault::StrayBrace } else { QueryFault::StrayParenthesis }; fault(&mut scanned, stray, line, column); } if declaring.is_some_and(|depth| open.len() < depth) { @@ -223,10 +211,7 @@ fn scan(query: &str) -> Scanned { '$' if declaring == Some(open.len()) => { let name = reader.word(); if let (Some(operation), false) = (scanned.operations.last_mut(), name.is_empty()) { - operation.variables.push(Variable { - name, - has_default: false, - }); + operation.variables.push(Variable { name, has_default: false }); } } '=' if declaring == Some(open.len()) => { @@ -259,11 +244,8 @@ fn scan(query: &str) -> Scanned { } // Left open at the end: the innermost, the one nearest to where the typing stopped. if let Some((opened, line, column)) = open.last().copied() { - let unclosed = if opened == '{' { - QueryFault::UnclosedBrace - } else { - QueryFault::UnclosedParenthesis - }; + let unclosed = + if opened == '{' { QueryFault::UnclosedBrace } else { QueryFault::UnclosedParenthesis }; fault(&mut scanned, unclosed, line, column); } scanned @@ -284,11 +266,7 @@ fn sent<'a>(operations: &'a [Operation], document: &GraphqlDocument) -> Option<& .operation_name .as_deref() .filter(|name| !name.is_empty()) - .and_then(|name| { - operations - .iter() - .find(|operation| operation.name.as_deref() == Some(name)) - }) + .and_then(|name| operations.iter().find(|operation| operation.name.as_deref() == Some(name))) .or_else(|| operations.first()) } @@ -306,10 +284,8 @@ fn given(variables: &str) -> Option> { pub fn describe(document: &GraphqlDocument) -> GraphqlAnswer { let scanned = scan(&document.query); let (mut missing, mut unknown) = (Vec::new(), Vec::new()); - if let (Some(operation), Some(given)) = ( - sent(&scanned.operations, document), - given(&document.variables), - ) { + if let (Some(operation), Some(given)) = (sent(&scanned.operations, document), given(&document.variables)) + { missing = operation .variables .iter() @@ -318,20 +294,11 @@ pub fn describe(document: &GraphqlDocument) -> GraphqlAnswer { .collect(); unknown = given .into_iter() - .filter(|key| { - !operation - .variables - .iter() - .any(|variable| &variable.name == key) - }) + .filter(|key| !operation.variables.iter().any(|variable| &variable.name == key)) .collect(); } GraphqlAnswer { - operations: scanned - .operations - .into_iter() - .filter_map(|operation| operation.name) - .collect(), + operations: scanned.operations.into_iter().filter_map(|operation| operation.name).collect(), variables_problem: if document.variables.trim().is_empty() { None } else { @@ -388,11 +355,7 @@ pub(crate) fn body(document: &GraphqlDocument, variables: Option<&str>) -> Strin body.push_str(",\"variables\":"); body.push_str(variables); } - if let Some(name) = document - .operation_name - .as_deref() - .filter(|name| !name.is_empty()) - { + if let Some(name) = document.operation_name.as_deref().filter(|name| !name.is_empty()) { body.push_str(",\"operationName\":"); body.push_str("ed(name)); } @@ -513,23 +476,14 @@ mod tests { fn a_sign_the_query_leaves_unpaired_is_said_where_it_stands() { for (query, expected) in [ ("{ a { b }", Some((QueryFault::UnclosedBrace, 1, 1))), - ( - "query Q {\n a(x: 1 {\n}", - Some((QueryFault::UnclosedParenthesis, 2, 4)), - ), + ("query Q {\n a(x: 1 {\n}", Some((QueryFault::UnclosedParenthesis, 2, 4))), ("{ a(x: \"open) }", Some((QueryFault::UnclosedString, 1, 8))), ("{ a }\n}", Some((QueryFault::StrayBrace, 2, 1))), ("{ a(x: 1}) }", Some((QueryFault::StrayBrace, 1, 9))), ("{ a ) }", Some((QueryFault::StrayParenthesis, 1, 5))), ("{ a(x: \"\"\"one\ntwo \\\"\"\" three\"\"\") }", None), - ( - "{ a(x: \"\"\"never closed) }", - Some((QueryFault::UnclosedString, 1, 8)), - ), - ( - "{ a(x: \"quote \\\" inside\") } # } stray in a comment", - None, - ), + ("{ a(x: \"\"\"never closed) }", Some((QueryFault::UnclosedString, 1, 8))), + ("{ a(x: \"quote \\\" inside\") } # } stray in a comment", None), ("{ a(x: \"\") }", None), ] { assert_eq!(problem(query), expected, "{query:?}"); @@ -540,18 +494,14 @@ mod tests { /// keys given that it does not declare. #[test] fn the_variables_say_what_the_operation_lacks_and_what_it_does_not_take() { - let query = - "query Orders($first: Int = 10, $after: String, $status: Status!) { orders { id } }"; + let query = "query Orders($first: Int = 10, $after: String, $status: Status!) { orders { id } }"; let answer = describe(&document(query, r#"{"status": "PAID", "extra": 1}"#, None)); assert_eq!(answer.operations, ["Orders"]); assert_eq!(answer.missing, ["after"]); assert_eq!(answer.unknown, ["extra"]); - assert_eq!( - (answer.variables_problem, answer.query_problem), - (None, None) - ); + assert_eq!((answer.variables_problem, answer.query_problem), (None, None)); } /// The operation named, or the first as the server takes it; a variable used in a selection @@ -584,10 +534,7 @@ mod tests { assert!(broken.variables_problem.is_some()); assert!(broken.missing.is_empty() && array.missing.is_empty()); assert_eq!(array.variables_problem, None); - assert_eq!( - (empty.variables_problem, empty.missing), - (None, vec!["id".to_string()]) - ); + assert_eq!((empty.variables_problem, empty.missing), (None, vec!["id".to_string()])); } /// A `null` for each value lacking, written at the end of the object as typed — nothing @@ -596,19 +543,12 @@ mod tests { fn the_values_lacking_are_added_as_null_at_the_end_of_the_object() { let query = "query Q($a: Int, $b: String, $c: Int = 1) { x }"; - let typed = with_missing(&document( - query, - "{\n \"big\": 12345678901234567890\n}", - None, - )); + let typed = with_missing(&document(query, "{\n \"big\": 12345678901234567890\n}", None)); let blank = with_missing(&document(query, "", None)); let empty = with_missing(&document(query, " { } ", None)); let whole = with_missing(&document(query, "{\"a\": 1, \"b\": \"x\"}", None)); - assert_eq!( - typed, - "{\n \"big\": 12345678901234567890,\n \"a\": null,\n \"b\": null\n}" - ); + assert_eq!(typed, "{\n \"big\": 12345678901234567890,\n \"a\": null,\n \"b\": null\n}"); assert_eq!(blank, "{\n \"a\": null,\n \"b\": null\n}"); assert_eq!(empty, blank); assert_eq!(whole, "{\"a\": 1, \"b\": \"x\"}"); @@ -618,10 +558,7 @@ mod tests { /// refused. #[test] fn the_variables_sent_are_the_object_as_typed() { - assert_eq!( - variables(&document("", " {\"n\": 1.10} ", None)), - Ok(Some("{\"n\": 1.10}")) - ); + assert_eq!(variables(&document("", " {\"n\": 1.10} ", None)), Ok(Some("{\"n\": 1.10}"))); assert_eq!(variables(&document("", " ", None)), Ok(None)); assert!(variables(&document("", "[1]", None)).is_err()); assert!(variables(&document("", "{\"a\":", None)).is_err()); @@ -656,16 +593,8 @@ mod tests { path: Some("orders[0].total".to_string()), location: Some("3:5".to_string()), }, - GraphqlError { - message: "bare".to_string(), - path: Some("[0]".to_string()), - location: None, - }, - GraphqlError { - message: String::new(), - path: None, - location: None, - }, + GraphqlError { message: "bare".to_string(), path: Some("[0]".to_string()), location: None }, + GraphqlError { message: String::new(), path: None, location: None }, ] ); assert_eq!(null_data.data, None); diff --git a/crates/engine/src/http/history.rs b/crates/engine/src/http/history.rs index b5200029c..962ec7240 100644 --- a/crates/engine/src/http/history.rs +++ b/crates/engine/src/http/history.rs @@ -91,9 +91,7 @@ pub fn url_parts(url: &str) -> (String, String) { let end = rest.find(['/', '?', '#']).unwrap_or(rest.len()); let (authority, tail) = rest.split_at(end); // Its credentials are nothing a list has to show. - let host = authority - .rsplit_once('@') - .map_or(authority, |(_, host)| host); + let host = authority.rsplit_once('@').map_or(authority, |(_, host)| host); (host.to_string(), tail.to_string()) } @@ -129,10 +127,7 @@ pub struct Sent { fn is_secret(name: &str, secrets: &[String]) -> bool { let name = name.trim().to_ascii_lowercase(); - matches!( - name.as_str(), - "authorization" | "proxy-authorization" | "cookie" - ) || secrets.contains(&name) + matches!(name.as_str(), "authorization" | "proxy-authorization" | "cookie") || secrets.contains(&name) } /// `Bearer abc` keeps its scheme: what kind of auth left is worth knowing, the token is not. @@ -210,9 +205,7 @@ pub fn mask(exchange: &Exchange, secrets: &[String]) -> Exchange { /// `session=abc; Path=/; HttpOnly` keeps its name and what it is set for. fn masked_set_cookie(value: &str) -> String { - let (pair, attributes) = value - .split_once(';') - .map_or((value, None), |(pair, rest)| (pair, Some(rest))); + let (pair, attributes) = value.split_once(';').map_or((value, None), |(pair, rest)| (pair, Some(rest))); let name = pair.split_once('=').map_or(pair, |(name, _)| name); match attributes { Some(rest) => format!("{name}={MASK};{rest}"), @@ -249,22 +242,14 @@ fn masked_answer(response: &SentResponse, secrets: &[String]) -> SentResponse { ..header.clone() }) .collect(), - cookies: response - .cookies - .iter() - .map(|cookie| masked_cookie(cookie, secrets)) - .collect(), + cookies: response.cookies.iter().map(|cookie| masked_cookie(cookie, secrets)).collect(), redirects: response .redirects .iter() .map(|hop| Redirect { url: masked_url(&hop.url, secrets), from: masked_url(&hop.from, secrets), - cookies: hop - .cookies - .iter() - .map(|cookie| masked_cookie(cookie, secrets)) - .collect(), + cookies: hop.cookies.iter().map(|cookie| masked_cookie(cookie, secrets)).collect(), ..hop.clone() }) .collect(), @@ -294,10 +279,12 @@ pub fn sent_secrets(exchange: &Exchange, secrets: &[String]) -> Vec { } let name = header.key.trim().to_ascii_lowercase(); if name == "cookie" { - found.extend(header.value.split(';').filter_map(|pair| { - pair.split_once('=') - .map(|(_, value)| value.trim().to_string()) - })); + found.extend( + header + .value + .split(';') + .filter_map(|pair| pair.split_once('=').map(|(_, value)| value.trim().to_string())), + ); } else { if let Some((_, token)) = header.value.split_once(' ') { found.push(token.trim().to_string()); @@ -309,9 +296,7 @@ pub fn sent_secrets(exchange: &Exchange, secrets: &[String]) -> Vec { let query = query.split_once('#').map_or(query, |(query, _)| query); found.extend(query.split('&').filter_map(|pair| { let (key, value) = pair.split_once('=')?; - secrets - .contains(&key.to_ascii_lowercase()) - .then(|| value.to_string()) + secrets.contains(&key.to_ascii_lowercase()).then(|| value.to_string()) })); } // A secret variable is already written as its `{{name}}`, which stays readable. @@ -324,9 +309,8 @@ pub fn sent_secrets(exchange: &Exchange, secrets: &[String]) -> Vec { /// Each value the request sent as a secret, masked wherever the text says it back. #[must_use] pub fn masked_echo(text: &str, sent: &[String]) -> String { - sent.iter().fold(text.to_string(), |text, value| { - text.replace(value.as_str(), MASK) - }) + sent.iter() + .fold(text.to_string(), |text, value| text.replace(value.as_str(), MASK)) } /// A secret variable's value, wherever the answer repeats it — a server echoing a token in its @@ -353,31 +337,21 @@ fn rewritten(response: &SentResponse, hide: impl Fn(&str) -> String) -> SentResp headers: response .headers .iter() - .map(|header| KeyValue { - value: hide(&header.value), - ..header.clone() - }) + .map(|header| KeyValue { value: hide(&header.value), ..header.clone() }) .collect(), body: hide(&response.body), pretty: response.pretty.as_deref().map(&hide), redirects: response .redirects .iter() - .map(|hop| Redirect { - url: hide(&hop.url), - from: hide(&hop.from), - ..hop.clone() - }) + .map(|hop| Redirect { url: hide(&hop.url), from: hide(&hop.from), ..hop.clone() }) .collect(), graphql: response.graphql.as_ref().map(|graphql| GraphqlResult { data: graphql.data.as_deref().map(&hide), errors: graphql .errors .iter() - .map(|error| GraphqlError { - message: hide(&error.message), - ..error.clone() - }) + .map(|error| GraphqlError { message: hide(&error.message), ..error.clone() }) .collect(), }), ..response.clone() @@ -393,10 +367,7 @@ fn hidden_exchange(exchange: &Exchange, secrets: &[(String, String)]) -> Exchang headers: exchange .headers .iter() - .map(|header| KeyValue { - value: hide(&header.value), - ..header.clone() - }) + .map(|header| KeyValue { value: hide(&header.value), ..header.clone() }) .collect(), body: match &exchange.body { SentBody::Text { text } => SentBody::Text { text: hide(text) }, @@ -415,10 +386,7 @@ pub fn shown(exchange: &Exchange, secrets: &[(String, String)]) -> Exchange { /// What is sealed: the request masked, its body and the answer's cut to `BODY_KEPT`. pub fn record_of(sent: &Sent) -> (HistorySummary, HistoryRecord) { - let mut exchange = mask( - &hidden_exchange(&sent.exchange, &sent.secret_values), - &sent.secrets, - ); + let mut exchange = mask(&hidden_exchange(&sent.exchange, &sent.secret_values), &sent.secrets); if let SentBody::Text { text } = &exchange.body { exchange.body = SentBody::Text { text: cut(text).0 }; } @@ -427,11 +395,7 @@ pub fn record_of(sent: &Sent) -> (HistorySummary, HistoryRecord) { let response = &echo_masked(&hidden_answer(response, &sent.secret_values), &echoed); let (body, shortened) = cut(&response.body); SentResponse { - pretty: if shortened { - None - } else { - response.pretty.clone() - }, + pretty: if shortened { None } else { response.pretty.clone() }, cut: response.cut || shortened, body, exchange: exchange.clone(), @@ -476,17 +440,9 @@ fn draft_url(url: &str) -> String { Some((head, query)) => { let kept: Vec<&str> = query .split('&') - .filter(|pair| { - !pair - .split_once('=') - .is_some_and(|(_, value)| value.starts_with(MASK)) - }) + .filter(|pair| !pair.split_once('=').is_some_and(|(_, value)| value.starts_with(MASK))) .collect(); - if kept.is_empty() { - head.to_string() - } else { - format!("{head}?{}", kept.join("&")) - } + if kept.is_empty() { head.to_string() } else { format!("{head}?{}", kept.join("&")) } } None => url, } @@ -511,10 +467,7 @@ pub fn draft_of(entry: &HistoryEntry) -> HistoryDraft { && !header.key.eq_ignore_ascii_case("content-type") && !send::is_default(&header.key, &header.value) }) - .map(|header| KeyValue { - enabled: true, - ..header.clone() - }) + .map(|header| KeyValue { enabled: true, ..header.clone() }) .collect(); let body = match &exchange.body { SentBody::Text { text } if typed.as_deref().is_some_and(|kind| kind.contains("json")) => { @@ -528,13 +481,7 @@ pub fn draft_of(entry: &HistoryEntry) -> HistoryDraft { name: entry.item.summary.name.clone(), kind: RequestKind::Http, method: exchange.method, - document: RequestDocument { - url, - params, - headers, - body, - ..RequestDocument::default() - }, + document: RequestDocument { url, params, headers, body, ..RequestDocument::default() }, }; // A GraphQL send back in its two boxes, when it still reads as one. if entry.item.summary.kind == RequestKind::Graphql @@ -579,10 +526,7 @@ fn graphql_of(exchange: &Exchange) -> Option<(GraphqlDocument, String)> { )); } let mut url = Url::parse(&exchange.url).ok()?; - let mut document = GraphqlDocument { - as_get: true, - ..GraphqlDocument::default() - }; + let mut document = GraphqlDocument { as_get: true, ..GraphqlDocument::default() }; let mut kept: Vec<(String, String)> = Vec::new(); for (key, value) in url.query_pairs() { match key.as_ref() { @@ -611,11 +555,7 @@ fn graphql_of(exchange: &Exchange) -> Option<(GraphqlDocument, String)> { /// it has one: never the dots as a value. Set by the auth or handed down, it has no row here, /// and what set it is still there. A header its folder or collection hands down today, with /// the value that was sent, is no change of the request's either. -pub fn onto( - entry: &HistoryEntry, - current: &HttpRequest, - above: &[InheritedHeader], -) -> HistoryDraft { +pub fn onto(entry: &HistoryEntry, current: &HttpRequest, above: &[InheritedHeader]) -> HistoryDraft { let sent = draft_of(entry); let exchange = &entry.record.exchange; let mut document = current.document.clone(); @@ -628,8 +568,7 @@ pub fn onto( }; let handed_down = |header: &KeyValue| { above.iter().any(|known| { - known.header.key.trim().eq_ignore_ascii_case(&header.key) - && known.header.value == header.value + known.header.key.trim().eq_ignore_ascii_case(&header.key) && known.header.value == header.value }) }; document.headers = exchange @@ -645,9 +584,7 @@ pub fn onto( .find(|kept| kept.key == header.key && !handed_down(kept)) // Its description is the request's, which the record never held. .map(|kept| KeyValue { - description: own(&kept.key) - .map(|row| row.description.clone()) - .unwrap_or_default(), + description: own(&kept.key).map(|row| row.description.clone()).unwrap_or_default(), ..kept.clone() }) }) @@ -672,18 +609,13 @@ pub fn onto( } } } - HistoryDraft { - name: current.name.clone(), - kind: current.kind, - method, - document, - } + HistoryDraft { name: current.name.clone(), kind: current.kind, method, document } } /// Retention holds even when the history is never opened. Never fatal. pub fn sweep_at_startup(db: &crate::db::Db) { - let purged = crate::db::lock(db) - .and_then(|mut connection| store::purge_expired(&mut connection, Utc::now())); + let purged = + crate::db::lock(db).and_then(|mut connection| store::purge_expired(&mut connection, Utc::now())); if let Err(error) = purged { log::warn!("Expired HTTP history not purged: {error}"); } @@ -694,17 +626,10 @@ pub fn by_day(items: Vec, tz_offset_minutes: i32) -> Vec = Vec::new(); for item in items { - let day = item - .sent_at - .with_timezone(&offset) - .format("%Y-%m-%d") - .to_string(); + let day = item.sent_at.with_timezone(&offset).format("%Y-%m-%d").to_string(); match days.last_mut() { Some(last) if last.day == day => last.items.push(item), - _ => days.push(HistoryDay { - day, - items: vec![item], - }), + _ => days.push(HistoryDay { day, items: vec![item] }), } } days @@ -718,26 +643,15 @@ mod tests { use crate::notes::language::Language; fn header(key: &str, value: &str) -> KeyValue { - KeyValue { - key: key.to_string(), - value: value.to_string(), - ..KeyValue::default() - } + KeyValue { key: key.to_string(), value: value.to_string(), ..KeyValue::default() } } fn text(body: &str) -> SentBody { - SentBody::Text { - text: body.to_string(), - } + SentBody::Text { text: body.to_string() } } fn exchange(url: &str, headers: Vec, body: SentBody) -> Exchange { - Exchange { - method: HttpMethod::Post, - url: url.to_string(), - headers, - body, - } + Exchange { method: HttpMethod::Post, url: url.to_string(), headers, body } } fn response(body: &str) -> SentResponse { @@ -802,19 +716,12 @@ mod tests { url_head: String::new(), url_tail: String::new(), }, - record: HistoryRecord { - exchange, - response: None, - }, + record: HistoryRecord { exchange, response: None }, } } fn value_of<'a>(headers: &'a [KeyValue], key: &str) -> &'a str { - &headers - .iter() - .find(|header| header.key == key) - .unwrap() - .value + &headers.iter().find(|header| header.key == key).unwrap().value } /// What repeats is the host, what tells sends apart follows it; its credentials are not @@ -822,14 +729,8 @@ mod tests { #[test] fn a_url_is_listed_as_its_host_and_what_follows() { for (url, parts) in [ - ( - "https://shop.test/orders?page=2", - ("shop.test", "/orders?page=2"), - ), - ( - "https://ada:pw@shop.test:8443#top", - ("shop.test:8443", "#top"), - ), + ("https://shop.test/orders?page=2", ("shop.test", "/orders?page=2")), + ("https://ada:pw@shop.test:8443#top", ("shop.test:8443", "#top")), ("https://shop.test", ("shop.test", "")), ("{{base}}/orders", ("", "{{base}}/orders")), ] { @@ -858,33 +759,12 @@ mod tests { let kept = mask(&leaving, &["x-api-key".to_string(), "api_key".to_string()]); - assert_eq!( - kept.url, - format!("https://ada:{MASK}@shop.test/a?api_key={MASK}&page=2#top") - ); - let values: Vec<&str> = kept - .headers - .iter() - .map(|header| header.value.as_str()) - .collect(); - assert_eq!( - values, - [ - format!("Bearer {MASK}").as_str(), - MASK, - MASK, - MASK, - MASK, - "application/json" - ] - ); + assert_eq!(kept.url, format!("https://ada:{MASK}@shop.test/a?api_key={MASK}&page=2#top")); + let values: Vec<&str> = kept.headers.iter().map(|header| header.value.as_str()).collect(); + assert_eq!(values, [format!("Bearer {MASK}").as_str(), MASK, MASK, MASK, MASK, "application/json"]); assert_eq!(kept.body, text("{}")); assert_eq!( - mask( - &exchange("https://shop.test/a", Vec::new(), SentBody::None), - &[] - ) - .url, + mask(&exchange("https://shop.test/a", Vec::new(), SentBody::None), &[]).url, "https://shop.test/a" ); } @@ -895,10 +775,7 @@ mod tests { fn a_request_is_shown_with_its_secrets_as_their_names() { let leaving = exchange( "https://shop.test/?t=t0k3n", - vec![ - header("X-Token", "t0k3n"), - header("Authorization", "Bearer t0k3n"), - ], + vec![header("X-Token", "t0k3n"), header("Authorization", "Bearer t0k3n")], text("{\"token\":\"t0k3n\"}"), ); @@ -906,10 +783,7 @@ mod tests { assert_eq!(shown.url, "https://shop.test/?t={{token}}"); assert_eq!(value_of(&shown.headers, "X-Token"), "{{token}}"); - assert_eq!( - value_of(&shown.headers, "Authorization"), - format!("Bearer {MASK}") - ); + assert_eq!(value_of(&shown.headers, "Authorization"), format!("Bearer {MASK}")); assert_eq!(shown.body, text("{\"token\":\"{{token}}\"}")); } @@ -932,20 +806,8 @@ mod tests { let found = sent_secrets(&leaving, &["x-api-key".to_string(), "api_key".to_string()]); - assert_eq!( - found, - [ - "k3y-in-header", - "Bearer t0k3n", - "k3y-in-url", - "s1d-value", - "t0k3n" - ] - ); - assert_eq!( - masked_echo("echo t0k3n and s1d-value", &found), - format!("echo {MASK} and {MASK}") - ); + assert_eq!(found, ["k3y-in-header", "Bearer t0k3n", "k3y-in-url", "s1d-value", "t0k3n"]); + assert_eq!(masked_echo("echo t0k3n and s1d-value", &found), format!("echo {MASK} and {MASK}")); } /// ⚠️ What an answer sets is what the next request sends: a `Set-Cookie` keeps its name and @@ -974,10 +836,7 @@ mod tests { from: "https://shop.test/login?api_key=k3y".to_string(), cookies: vec![set], }]; - let mut leaving = sent( - exchange("https://shop.test/login", Vec::new(), SentBody::None), - Ok(answer), - ); + let mut leaving = sent(exchange("https://shop.test/login", Vec::new(), SentBody::None), Ok(answer)); leaving.secrets = vec!["api_key".to_string()]; let (_, record) = record_of(&leaving); @@ -985,23 +844,11 @@ mod tests { let kept = record.response.unwrap(); let masked = format!("api_key={MASK}"); assert!(kept.url.ends_with(&masked)); - assert_eq!( - value_of(&kept.headers, "Set-Cookie"), - format!("sid={MASK}; Path=/; HttpOnly") - ); - assert_eq!( - value_of(&kept.headers, "set-cookie"), - format!("bare={MASK}") - ); + assert_eq!(value_of(&kept.headers, "Set-Cookie"), format!("sid={MASK}; Path=/; HttpOnly")); + assert_eq!(value_of(&kept.headers, "set-cookie"), format!("bare={MASK}")); assert!(value_of(&kept.headers, "Location").ends_with(&masked)); assert_eq!(value_of(&kept.headers, "Server"), "test"); - assert_eq!( - ( - kept.cookies[0].name.as_str(), - kept.cookies[0].value.as_str() - ), - ("sid", MASK) - ); + assert_eq!((kept.cookies[0].name.as_str(), kept.cookies[0].value.as_str()), ("sid", MASK)); assert!(kept.cookies[0].from.as_deref().unwrap().ends_with(&masked)); let hop = &kept.redirects[0]; assert!(hop.url.ends_with(&masked) && hop.from.ends_with(&masked)); @@ -1024,18 +871,10 @@ mod tests { }]; answer.graphql = Some(GraphqlResult { data: Some("{\"me\":\"abc-123\"}".to_string()), - errors: vec![GraphqlError { - message: "bad token t0k3n".to_string(), - path: None, - location: None, - }], + errors: vec![GraphqlError { message: "bad token t0k3n".to_string(), path: None, location: None }], }); let mut leaving = sent( - exchange( - "https://shop.test/", - vec![header("Authorization", "Bearer abc-123")], - SentBody::None, - ), + exchange("https://shop.test/", vec![header("Authorization", "Bearer abc-123")], SentBody::None), Ok(answer), ); leaving.secret_values = vec![("token".to_string(), "t0k3n".to_string())]; @@ -1043,31 +882,16 @@ mod tests { let (_, record) = record_of(&leaving); let kept = record.response.unwrap(); - assert_eq!( - kept.body, - format!("{{\"token\":\"{{{{token}}}}\",\"auth\":\"{MASK}\"}}") - ); - assert_eq!( - kept.pretty.as_deref(), - Some(format!("{{{{token}}}} {MASK}").as_str()) - ); + assert_eq!(kept.body, format!("{{\"token\":\"{{{{token}}}}\",\"auth\":\"{MASK}\"}}")); + assert_eq!(kept.pretty.as_deref(), Some(format!("{{{{token}}}} {MASK}").as_str())); assert_eq!(value_of(&kept.headers, "X-Echo"), MASK); assert_eq!(kept.url, "https://shop.test/?t={{token}}"); assert_eq!( - ( - kept.redirects[0].url.as_str(), - kept.redirects[0].from.as_str() - ), - ( - format!("https://shop.test/{MASK}").as_str(), - "https://shop.test/{{token}}" - ) + (kept.redirects[0].url.as_str(), kept.redirects[0].from.as_str()), + (format!("https://shop.test/{MASK}").as_str(), "https://shop.test/{{token}}") ); let graphql = kept.graphql.unwrap(); - assert_eq!( - graphql.data.as_deref(), - Some(format!("{{\"me\":\"{MASK}\"}}").as_str()) - ); + assert_eq!(graphql.data.as_deref(), Some(format!("{{\"me\":\"{MASK}\"}}").as_str())); assert_eq!(graphql.errors[0].message, "bad token {{token}}"); } @@ -1092,10 +916,7 @@ mod tests { let (summary, record) = record_of(&leaving); assert_eq!(record.exchange.url, "https://shop.test/?q={{token}}"); - assert_eq!( - value_of(&record.exchange.headers, "Authorization"), - format!("Bearer {MASK}") - ); + assert_eq!(value_of(&record.exchange.headers, "Authorization"), format!("Bearer {MASK}")); assert_eq!(record.exchange.body, text(&"a".repeat(BODY_KEPT - 1))); let kept = record.response.unwrap(); assert_eq!(kept.body.len(), BODY_KEPT - 1); @@ -1109,14 +930,10 @@ mod tests { /// code and what its sentence states, and no answer. #[test] fn a_send_s_summary_says_how_it_went() { - let environment = SentEnvironment { - name: "Prod".to_string(), - colour: crate::folders::model::FolderColour::Red, - }; - let mut answered = sent( - exchange("https://shop.test/", Vec::new(), SentBody::None), - Ok(response("ok")), - ); + let environment = + SentEnvironment { name: "Prod".to_string(), colour: crate::folders::model::FolderColour::Red }; + let mut answered = + sent(exchange("https://shop.test/", Vec::new(), SentBody::None), Ok(response("ok"))); answered.kind = RequestKind::Graphql; answered.environment = Some(environment.clone()); let params = BTreeMap::from([("delay".to_string(), "30 s".to_string())]); @@ -1213,12 +1030,7 @@ mod tests { .collect(); assert_eq!(params, [("page", "2")]); assert_eq!(draft.document.headers, [header("X-Trace", "1")]); - assert_eq!( - draft.document.body, - RequestBody::Json { - text: "{\"a\":1}".to_string() - } - ); + assert_eq!(draft.document.body, RequestBody::Json { text: "{\"a\":1}".to_string() }); } /// A text without a JSON type is text; a file or a multipart was not kept; a query of @@ -1235,31 +1047,12 @@ mod tests { let plain = body(text("hello"), vec![header("Content-Type", "text/plain")]); - assert_eq!( - plain.body, - RequestBody::Text { - text: "hello".to_string() - } - ); + assert_eq!(plain.body, RequestBody::Text { text: "hello".to_string() }); assert_eq!(plain.url, "https://shop.test/"); + assert_eq!(body(text("{}"), Vec::new()).body, RequestBody::Text { text: "{}".to_string() }); + assert_eq!(body(SentBody::Bytes { size: 3 }, Vec::new()).body, RequestBody::None); assert_eq!( - body(text("{}"), Vec::new()).body, - RequestBody::Text { - text: "{}".to_string() - } - ); - assert_eq!( - body(SentBody::Bytes { size: 3 }, Vec::new()).body, - RequestBody::None - ); - assert_eq!( - body( - SentBody::Multipart { - fields: vec!["a".to_string()] - }, - Vec::new() - ) - .body, + body(SentBody::Multipart { fields: vec!["a".to_string()] }, Vec::new()).body, RequestBody::None ); } @@ -1290,16 +1083,10 @@ mod tests { assert_eq!(from_post.kind, RequestKind::Graphql); assert_eq!(from_post.document.graphql.query, "{ me { id } }"); assert_eq!(from_post.document.graphql.variables, "{\n \"id\": 7\n}"); - assert_eq!( - from_post.document.graphql.operation_name.as_deref(), - Some("Me") - ); + assert_eq!(from_post.document.graphql.operation_name.as_deref(), Some("Me")); assert!(!from_post.document.graphql.as_get && from_post.document.body == RequestBody::None); assert_eq!( - ( - from_get.document.graphql.query.as_str(), - from_get.document.graphql.as_get - ), + (from_get.document.graphql.query.as_str(), from_get.document.graphql.as_get), ("{ me }", true) ); assert_eq!(from_get.document.graphql.variables, "{\n \"a\": 1\n}"); @@ -1344,21 +1131,11 @@ mod tests { let mine = RequestDocument { url: "https://shop.test/a".to_string(), headers: vec![ - KeyValue { - description: "the key".to_string(), - ..header("x-api-key", "{{key}}") - }, - KeyValue { - description: "which trace".to_string(), - ..header("X-Trace", "1") - }, + KeyValue { description: "the key".to_string(), ..header("x-api-key", "{{key}}") }, + KeyValue { description: "which trace".to_string(), ..header("X-Trace", "1") }, ], - body: RequestBody::Binary { - path: "/dump.bin".to_string(), - }, - auth: RequestAuth::Bearer { - token: "{{token}}".to_string(), - }, + body: RequestBody::Binary { path: "/dump.bin".to_string() }, + auth: RequestAuth::Bearer { token: "{{token}}".to_string() }, ..RequestDocument::default() }; let above = [InheritedHeader { @@ -1370,11 +1147,8 @@ mod tests { }, }]; - let put_back = onto( - &entry(RequestKind::Http, recorded), - ¤t(RequestKind::Http, mine.clone()), - &above, - ); + let put_back = + onto(&entry(RequestKind::Http, recorded), ¤t(RequestKind::Http, mine.clone()), &above); assert_eq!( (put_back.name.as_str(), put_back.kind, put_back.method), @@ -1386,16 +1160,10 @@ mod tests { put_back.document.headers, [ mine.headers[0].clone(), - KeyValue { - description: "which trace".to_string(), - ..header("X-Trace", "2") - }, + KeyValue { description: "which trace".to_string(), ..header("X-Trace", "2") }, ] ); - assert_eq!( - (&put_back.document.body, &put_back.document.auth), - (&mine.body, &mine.auth) - ); + assert_eq!((&put_back.document.body, &put_back.document.auth), (&mine.body, &mine.auth)); } /// A text body or none goes over the request's; a GraphQL request takes its query back and @@ -1403,39 +1171,18 @@ mod tests { #[test] fn a_send_put_back_takes_its_body_or_its_graphql() { let mine = RequestDocument { - body: RequestBody::Json { - text: "{\"old\":1}".to_string(), - }, + body: RequestBody::Json { text: "{\"old\":1}".to_string() }, ..RequestDocument::default() }; let texted = exchange("https://shop.test/", Vec::new(), text("new")); - let posted = exchange( - "https://shop.test/graphql?x=1", - Vec::new(), - text(r#"{"query":"{ me }"}"#), - ); + let posted = exchange("https://shop.test/graphql?x=1", Vec::new(), text(r#"{"query":"{ me }"}"#)); - let http = onto( - &entry(RequestKind::Http, texted), - ¤t(RequestKind::Http, mine.clone()), - &[], - ); - let graphql = onto( - &entry(RequestKind::Graphql, posted), - ¤t(RequestKind::Graphql, mine.clone()), - &[], - ); + let http = onto(&entry(RequestKind::Http, texted), ¤t(RequestKind::Http, mine.clone()), &[]); + let graphql = + onto(&entry(RequestKind::Graphql, posted), ¤t(RequestKind::Graphql, mine.clone()), &[]); - assert_eq!( - http.document.body, - RequestBody::Text { - text: "new".to_string() - } - ); - assert_eq!( - (graphql.method, graphql.document.graphql.query.as_str()), - (HttpMethod::Get, "{ me }") - ); + assert_eq!(http.document.body, RequestBody::Text { text: "new".to_string() }); + assert_eq!((graphql.method, graphql.document.graphql.query.as_str()), (HttpMethod::Get, "{ me }")); assert_eq!(graphql.document.url, "https://shop.test/graphql?x=1"); assert_eq!(graphql.document.body, mine.body); } @@ -1447,11 +1194,7 @@ mod tests { let item = |id: &str, at: &str| HistoryItem { id: id.to_string(), sent_at: crate::db::iso8601::parse(at).unwrap(), - ..entry( - RequestKind::Http, - exchange("https://shop.test/", Vec::new(), SentBody::None), - ) - .item + ..entry(RequestKind::Http, exchange("https://shop.test/", Vec::new(), SentBody::None)).item }; let items = vec![ item("late", "2026-07-25T23:30:00.000Z"), @@ -1464,27 +1207,16 @@ mod tests { let grouped = |days: &[HistoryDay]| -> Vec<(String, Vec)> { days.iter() - .map(|day| { - ( - day.day.clone(), - day.items.iter().map(|item| item.id.clone()).collect(), - ) - }) + .map(|day| (day.day.clone(), day.items.iter().map(|item| item.id.clone()).collect())) .collect() }; assert_eq!( grouped(&utc), [ - ( - "2026-07-25".to_string(), - vec!["late".to_string(), "evening".to_string()] - ), + ("2026-07-25".to_string(), vec!["late".to_string(), "evening".to_string()]), ("2026-07-24".to_string(), vec!["before".to_string()]) ] ); - assert_eq!( - grouped(&east)[0], - ("2026-07-26".to_string(), vec!["late".to_string()]) - ); + assert_eq!(grouped(&east)[0], ("2026-07-26".to_string(), vec!["late".to_string()])); } } diff --git a/crates/engine/src/http/history/store.rs b/crates/engine/src/http/history/store.rs index e6e07f33d..fcd90c03c 100644 --- a/crates/engine/src/http/history/store.rs +++ b/crates/engine/src/http/history/store.rs @@ -5,8 +5,7 @@ use diesel::prelude::*; use uuid::Uuid; use super::{ - HistoryEntry, HistoryItem, HistoryRecord, HistorySummary, KEPT_AT_MOST, RETENTION_DAYS, - url_parts, + HistoryEntry, HistoryItem, HistoryRecord, HistorySummary, KEPT_AT_MOST, RETENTION_DAYS, url_parts, }; use crate::db::schema::http_history; use crate::db::{Library, iso8601}; @@ -23,10 +22,7 @@ struct Row { } fn corrupt(id: &str, field: &'static str) -> StorageError { - StorageError::CorruptRow { - id: id.to_string(), - field, - } + StorageError::CorruptRow { id: id.to_string(), field } } fn open_json( @@ -62,10 +58,7 @@ impl Row { } /// A request deleted since it was sent is history without its link. -fn still_there<'a>( - connection: &mut SqliteConnection, - request_id: Option<&'a str>, -) -> Option<&'a str> { +fn still_there<'a>(connection: &mut SqliteConnection, request_id: Option<&'a str>) -> Option<&'a str> { request_id.filter(|id| { crate::db::schema::http_requests::table .find(*id) @@ -130,15 +123,15 @@ pub fn restore(connection: &mut Library, entry: &HistoryEntry) -> Result<(), Sto /// Older than the retention, or past the count from the newest. fn purge(connection: &mut SqliteConnection, now: DateTime) -> Result { let horizon = iso8601::format(now - TimeDelta::days(RETENTION_DAYS)); - let aged = diesel::delete(http_history::table.filter(http_history::sent_at.lt(horizon))) - .execute(connection)?; + let aged = + diesel::delete(http_history::table.filter(http_history::sent_at.lt(horizon))).execute(connection)?; let kept: Vec = http_history::table .select(http_history::id) .order((http_history::sent_at.desc(), http_history::id.desc())) .limit(KEPT_AT_MOST) .load(connection)?; - let counted = diesel::delete(http_history::table.filter(http_history::id.ne_all(kept))) - .execute(connection)?; + let counted = + diesel::delete(http_history::table.filter(http_history::id.ne_all(kept))).execute(connection)?; Ok(aged + counted) } @@ -168,10 +161,7 @@ pub fn entry(connection: &mut Library, id: &str) -> Result Result { @@ -224,21 +214,12 @@ mod tests { } } - fn write( - library: &mut Library, - name: &str, - request_id: Option<&str>, - at: DateTime, - ) -> String { + fn write(library: &mut Library, name: &str, request_id: Option<&str>, at: DateTime) -> String { super::record(library, request_id, &summary(name), &record(), at).unwrap() } fn names(library: &mut Library) -> Vec { - list(library) - .unwrap() - .into_iter() - .map(|item| item.summary.name) - .collect() + list(library).unwrap().into_iter().map(|item| item.summary.name).collect() } fn a_request(library: &mut Library) -> String { @@ -251,9 +232,7 @@ mod tests { method: HttpMethod::Get, document: crate::http::model::RequestDocument::default(), }; - crate::http::store::create_request(library, &draft, "Orders", now()) - .unwrap() - .id + crate::http::store::create_request(library, &draft, "Orders", now()).unwrap().id } /// Newest first; of one instant, the one written last; read back with what a list shows, @@ -267,20 +246,11 @@ mod tests { let items = list(&mut library).unwrap(); - let shown: Vec<&str> = items - .iter() - .map(|item| item.summary.name.as_str()) - .collect(); + let shown: Vec<&str> = items.iter().map(|item| item.summary.name.as_str()).collect(); assert_eq!(shown, ["second", "first", "earlier"]); let item = &items[0]; - assert_eq!( - (item.sent_at, item.method, item.status), - (now(), HttpMethod::Delete, Some(401)) - ); - assert_eq!( - (item.url_head.as_str(), item.url_tail.as_str()), - ("api.shop.test", "/orders/42") - ); + assert_eq!((item.sent_at, item.method, item.status), (now(), HttpMethod::Delete, Some(401))); + assert_eq!((item.url_head.as_str(), item.url_tail.as_str()), ("api.shop.test", "/orders/42")); } /// A request deleted since it was sent is history without its link. @@ -291,11 +261,8 @@ mod tests { write(&mut library, "linked", Some(&request), now()); write(&mut library, "gone", Some("deleted-since"), now()); - let links: Vec> = list(&mut library) - .unwrap() - .into_iter() - .map(|item| item.request_id) - .collect(); + let links: Vec> = + list(&mut library).unwrap().into_iter().map(|item| item.request_id).collect(); assert_eq!(links, [None, Some(request)]); } @@ -310,12 +277,7 @@ mod tests { None, now() - TimeDelta::days(RETENTION_DAYS) - TimeDelta::seconds(1), ); - write( - &mut library, - "at the edge", - None, - now() - TimeDelta::days(RETENTION_DAYS), - ); + write(&mut library, "at the edge", None, now() - TimeDelta::days(RETENTION_DAYS)); write(&mut library, "today", None, now()); @@ -340,12 +302,7 @@ mod tests { #[test] fn the_retention_is_swept_at_launch_without_a_write() { let mut library = crate::db::open_in_memory().unwrap(); - write( - &mut library, - "old", - None, - Utc::now() - TimeDelta::days(RETENTION_DAYS + 1), - ); + write(&mut library, "old", None, Utc::now() - TimeDelta::days(RETENTION_DAYS + 1)); write(&mut library, "kept", None, Utc::now()); let db: crate::db::Db = std::sync::Mutex::new(Some(library)); @@ -381,10 +338,8 @@ mod tests { let request = a_request(&mut library); let id = write(&mut library, "linked", Some(&request), now()); let removed = delete(&mut library, &id).unwrap(); - let gone = crate::http::model::HttpItem { - kind: crate::http::model::HttpItemKind::Request, - id: request, - }; + let gone = + crate::http::model::HttpItem { kind: crate::http::model::HttpItemKind::Request, id: request }; crate::http::store::delete(&mut library, &gone).unwrap(); restore(&mut library, &removed).unwrap(); @@ -401,10 +356,7 @@ mod tests { assert!( matches!(entry(&mut library, "missing"), Err(StorageError::HttpItemNotFound(id)) if id == "missing") ); - assert!(matches!( - delete(&mut library, "missing"), - Err(StorageError::HttpItemNotFound(_)) - )); + assert!(matches!(delete(&mut library, "missing"), Err(StorageError::HttpItemNotFound(_)))); assert_eq!(clear(&mut library).unwrap(), 2); assert_eq!(count(&mut library).unwrap(), 0); } @@ -422,10 +374,7 @@ mod tests { .unwrap(); for clear in ["DELETE", "Delete", "401", "api.shop.test", "orders"] { - assert!( - !summary.contains(clear) && !sealed.contains(clear), - "{clear} in the clear" - ); + assert!(!summary.contains(clear) && !sealed.contains(clear), "{clear} in the clear"); } } @@ -440,38 +389,17 @@ mod tests { .set(http_history::record.eq(&garbage)) .execute(library.db()) .unwrap(); - assert!(matches!( - entry(&mut library, &id), - Err(StorageError::CorruptRow { - field: "record", - .. - }) - )); + assert!(matches!(entry(&mut library, &id), Err(StorageError::CorruptRow { field: "record", .. }))); diesel::update(http_history::table.find(&id)) .set(http_history::summary.eq(&garbage)) .execute(library.db()) .unwrap(); - assert!(matches!( - list(&mut library), - Err(StorageError::CorruptRow { - field: "summary", - .. - }) - )); + assert!(matches!(list(&mut library), Err(StorageError::CorruptRow { field: "summary", .. }))); let readable = seal_json(library.vault(), &summary("a")).unwrap(); diesel::update(http_history::table.find(&id)) - .set(( - http_history::summary.eq(readable), - http_history::sent_at.eq("not a date"), - )) + .set((http_history::summary.eq(readable), http_history::sent_at.eq("not a date"))) .execute(library.db()) .unwrap(); - assert!(matches!( - list(&mut library), - Err(StorageError::CorruptRow { - field: "sentAt", - .. - }) - )); + assert!(matches!(list(&mut library), Err(StorageError::CorruptRow { field: "sentAt", .. }))); } } diff --git a/crates/engine/src/http/model.rs b/crates/engine/src/http/model.rs index 449145959..70dffa320 100644 --- a/crates/engine/src/http/model.rs +++ b/crates/engine/src/http/model.rs @@ -114,11 +114,7 @@ pub struct RequestScripts { /// What a request sends as its body. A file is a path, read by Rust when the request is sent: /// its bytes never enter the library. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde( - tag = "kind", - rename_all = "camelCase", - rename_all_fields = "camelCase" -)] +#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")] pub enum RequestBody { #[default] None, @@ -162,12 +158,8 @@ impl RequestBody { match self { Self::None => false, Self::Json { text } | Self::Text { text } => !text.is_empty(), - Self::Form { fields } => fields - .iter() - .any(|row| row.enabled && !row.key.trim().is_empty()), - Self::Multipart { parts } => parts - .iter() - .any(|part| part.enabled && !part.key.trim().is_empty()), + Self::Form { fields } => fields.iter().any(|row| row.enabled && !row.key.trim().is_empty()), + Self::Multipart { parts } => parts.iter().any(|part| part.enabled && !part.key.trim().is_empty()), Self::Binary { path } => !path.trim().is_empty(), } } @@ -213,11 +205,7 @@ pub enum KeyPlace { /// `Inherit` takes the auth of the nearest folder, then the collection, that sets one. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde( - tag = "kind", - rename_all = "camelCase", - rename_all_fields = "camelCase" -)] +#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")] pub enum RequestAuth { #[default] Inherit, @@ -274,12 +262,7 @@ pub struct KeyValue { /// Enabled: a row is typed to be sent. impl Default for KeyValue { fn default() -> Self { - Self { - enabled: true, - key: String::new(), - value: String::new(), - description: String::new(), - } + Self { enabled: true, key: String::new(), value: String::new(), description: String::new() } } } @@ -414,13 +397,8 @@ pub struct HttpRequestPatch { #[derive(Debug, Clone, PartialEq, Eq)] pub enum HttpNode { - Folder { - folder: HttpFolder, - children: Vec, - }, - Request { - request: HttpRequestSummary, - }, + Folder { folder: HttpFolder, children: Vec }, + Request { request: HttpRequestSummary }, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -453,9 +431,7 @@ pub struct HttpPlace { /// The type a multipart file part is sent with, read off its name: what an attachment knows, /// and the web's own files besides; `application/octet-stream` for the rest. pub fn part_type(file_name: &str) -> String { - let extension = file_name - .rsplit_once('.') - .map(|(_, extension)| extension.to_ascii_lowercase()); + let extension = file_name.rsplit_once('.').map(|(_, extension)| extension.to_ascii_lowercase()); let web = match extension.as_deref() { Some("html" | "htm") => "text/html", Some("xml") => "application/xml", @@ -484,27 +460,15 @@ mod tests { use super::*; fn row(key: &str, value: &str) -> KeyValue { - KeyValue { - key: key.to_string(), - value: value.to_string(), - ..KeyValue::default() - } + KeyValue { key: key.to_string(), value: value.to_string(), ..KeyValue::default() } } fn part(key: &str, value: &str, file: bool, enabled: bool) -> FormPart { - FormPart { - enabled, - key: key.to_string(), - value: value.to_string(), - file, - ..FormPart::default() - } + FormPart { enabled, key: key.to_string(), value: value.to_string(), file, ..FormPart::default() } } fn json(text: &str) -> RequestBody { - RequestBody::Json { - text: text.to_string(), - } + RequestBody::Json { text: text.to_string() } } /// Stored as written: a method or a kind reads back from its spelling. @@ -548,9 +512,7 @@ mod tests { part("name", "Ada", false, true), ], }; - let binary = RequestBody::Binary { - path: "/dump.bin".to_string(), - }; + let binary = RequestBody::Binary { path: "/dump.bin".to_string() }; assert_eq!(multipart.files(), ["/a.png"]); assert_eq!(binary.files(), ["/dump.bin"]); @@ -561,54 +523,19 @@ mod tests { #[test] fn a_body_carries_something_only_once_filled() { let named = || vec![row("q", "1")]; - let off = || { - vec![KeyValue { - enabled: false, - ..row("q", "1") - }] - }; + let off = || vec![KeyValue { enabled: false, ..row("q", "1") }]; for (body, carries) in [ (RequestBody::None, false), (json(""), false), (json("{}"), true), - ( - RequestBody::Text { - text: "t".to_string(), - }, - true, - ), + (RequestBody::Text { text: "t".to_string() }, true), (RequestBody::Form { fields: named() }, true), (RequestBody::Form { fields: off() }, false), - ( - RequestBody::Form { - fields: vec![row(" ", "1")], - }, - false, - ), - ( - RequestBody::Multipart { - parts: vec![part("a", "", false, true)], - }, - true, - ), - ( - RequestBody::Multipart { - parts: vec![part("a", "", false, false)], - }, - false, - ), - ( - RequestBody::Binary { - path: " ".to_string(), - }, - false, - ), - ( - RequestBody::Binary { - path: "/f".to_string(), - }, - true, - ), + (RequestBody::Form { fields: vec![row(" ", "1")] }, false), + (RequestBody::Multipart { parts: vec![part("a", "", false, true)] }, true), + (RequestBody::Multipart { parts: vec![part("a", "", false, false)] }, false), + (RequestBody::Binary { path: " ".to_string() }, false), + (RequestBody::Binary { path: "/f".to_string() }, true), ] { assert_eq!(body.carries_something(), carries, "{body:?}"); } @@ -650,30 +577,14 @@ mod tests { fn the_rule_agrees_with_what_the_client_builds() { use reqwest::header::{HeaderName, HeaderValue}; - for name in [ - "X-Recette", - "X Recette", - "X:1", - "Clé", - "a(b)", - "x_y", - "a`b", - "", - ] { + for name in ["X-Recette", "X Recette", "X:1", "Clé", "a(b)", "x_y", "a`b", ""] { assert_eq!( header_fault(name, "").is_none(), HeaderName::from_bytes(name.as_bytes()).is_ok(), "{name}" ); } - for value in [ - "plain", - "tab\there", - "Équipe", - "line\nbreak", - "nul\u{0}", - "del\u{7f}", - ] { + for value in ["plain", "tab\there", "Équipe", "line\nbreak", "nul\u{0}", "del\u{7f}"] { assert_eq!( header_fault("X-A", value).is_none(), HeaderValue::from_str(value).is_ok(), @@ -686,8 +597,7 @@ mod tests { /// older version still opens. #[test] fn a_document_written_before_a_field_existed_still_opens() { - let document: RequestDocument = - serde_json::from_str(r#"{"url":"https://exemple.fr"}"#).unwrap(); + let document: RequestDocument = serde_json::from_str(r#"{"url":"https://exemple.fr"}"#).unwrap(); assert_eq!(document.url, "https://exemple.fr"); assert_eq!(document.description, ""); @@ -700,14 +610,7 @@ mod tests { /// Not sent, not judged. #[test] fn a_header_switched_off_or_unnamed_is_not_judged() { - let rows = [ - row("X Id", "x"), - KeyValue { - enabled: false, - ..row("X Id", "x") - }, - row(" ", "a\nb"), - ]; + let rows = [row("X Id", "x"), KeyValue { enabled: false, ..row("X Id", "x") }, row(" ", "a\nb")]; assert_eq!(header_faults(&rows), [Some(HeaderFault::Name), None, None]); } @@ -720,13 +623,7 @@ mod tests { "Accept: application/json\n Referer : https://shop.test/a \nno colon\n:authority: shop.test\n", ); - assert_eq!( - rows, - [ - row("Accept", "application/json"), - row("Referer", "https://shop.test/a"), - ] - ); + assert_eq!(rows, [row("Accept", "application/json"), row("Referer", "https://shop.test/a"),]); } /// The web's own files by their extension, whatever its case; what an attachment knows diff --git a/crates/engine/src/http/query.rs b/crates/engine/src/http/query.rs index f728fdca2..86300e996 100644 --- a/crates/engine/src/http/query.rs +++ b/crates/engine/src/http/query.rs @@ -18,14 +18,8 @@ pub struct SyncedQuery { /// The side that was edited wins; the other is rewritten from it. pub fn sync(url: &str, params: &[KeyValue], edited: QuerySide) -> SyncedQuery { match edited { - QuerySide::Url => SyncedQuery { - url: url.to_string(), - params: params_from_url(url, params), - }, - QuerySide::Params => SyncedQuery { - url: url_with_params(url, params), - params: params.to_vec(), - }, + QuerySide::Url => SyncedQuery { url: url.to_string(), params: params_from_url(url, params) }, + QuerySide::Params => SyncedQuery { url: url_with_params(url, params), params: params.to_vec() }, } } @@ -42,39 +36,21 @@ fn parts(url: &str) -> (&str, Option<&str>, &str) { /// and stays where it was, and a description follows its key. fn params_from_url(url: &str, previous: &[KeyValue]) -> Vec { let (_, query, _) = parts(url); - let mut typed = query - .unwrap_or("") - .split('&') - .filter(|pair| !pair.is_empty()) - .map(|pair| { - let (key, value) = pair.split_once('=').unwrap_or((pair, "")); - (key.to_string(), value.to_string()) - }); + let mut typed = query.unwrap_or("").split('&').filter(|pair| !pair.is_empty()).map(|pair| { + let (key, value) = pair.split_once('=').unwrap_or((pair, "")); + (key.to_string(), value.to_string()) + }); let mut rows = Vec::with_capacity(previous.len()); for row in previous { if !row.enabled { rows.push(row.clone()); } else if let Some((key, value)) = typed.next() { - let description = if key == row.key { - row.description.clone() - } else { - String::new() - }; - rows.push(KeyValue { - enabled: true, - key, - value, - description, - }); + let description = if key == row.key { row.description.clone() } else { String::new() }; + rows.push(KeyValue { enabled: true, key, value, description }); } } - rows.extend(typed.map(|(key, value)| KeyValue { - enabled: true, - key, - value, - description: String::new(), - })); + rows.extend(typed.map(|(key, value)| KeyValue { enabled: true, key, value, description: String::new() })); rows } @@ -98,25 +74,15 @@ mod tests { use super::*; fn row(key: &str, value: &str) -> KeyValue { - KeyValue { - key: key.to_string(), - value: value.to_string(), - ..KeyValue::default() - } + KeyValue { key: key.to_string(), value: value.to_string(), ..KeyValue::default() } } fn described(key: &str, value: &str, description: &str) -> KeyValue { - KeyValue { - description: description.to_string(), - ..row(key, value) - } + KeyValue { description: description.to_string(), ..row(key, value) } } fn off(key: &str, value: &str) -> KeyValue { - KeyValue { - enabled: false, - ..row(key, value) - } + KeyValue { enabled: false, ..row(key, value) } } fn from_url(url: &str, params: &[KeyValue]) -> Vec { @@ -135,15 +101,9 @@ mod tests { /// value, an empty pair is none, and the fragment ends the query. #[test] fn the_url_s_pairs_become_rows_as_typed() { - let rows = from_url( - "https://shop.test/a?q=a%20b&&page={{page}}&flag#top?x=1", - &[], - ); + let rows = from_url("https://shop.test/a?q=a%20b&&page={{page}}&flag#top?x=1", &[]); - assert_eq!( - rows, - [row("q", "a%20b"), row("page", "{{page}}"), row("flag", "")] - ); + assert_eq!(rows, [row("q", "a%20b"), row("page", "{{page}}"), row("flag", "")]); } /// The pairs take the enabled rows' places in order; a row switched off is not in the URL @@ -159,26 +119,14 @@ mod tests { let rows = from_url("https://shop.test/a?q=new&sort=asc", &table); - assert_eq!( - rows, - [ - described("q", "new", "the search"), - off("debug", "1"), - row("sort", "asc"), - ] - ); + assert_eq!(rows, [described("q", "new", "the search"), off("debug", "1"), row("sort", "asc"),]); assert_eq!(from_url("https://shop.test/a", &table), [off("debug", "1")]); } /// The enabled rows with a key, in order; none, no `?`; the fragment stays at the end. #[test] fn the_rows_rewrite_the_url_s_query() { - let table = [ - row("q", "{{term}}"), - off("debug", "1"), - row("", "lost"), - row("page", "2"), - ]; + let table = [row("q", "{{term}}"), off("debug", "1"), row("", "lost"), row("page", "2")]; assert_eq!( from_params("https://shop.test/a?old=1#top", &table), diff --git a/crates/engine/src/http/response.rs b/crates/engine/src/http/response.rs index ff54832ac..dcf5607d5 100644 --- a/crates/engine/src/http/response.rs +++ b/crates/engine/src/http/response.rs @@ -88,9 +88,7 @@ fn cookie(line: &str) -> Option { for attribute in parts { let (key, value) = attribute .split_once('=') - .map_or((attribute.trim(), ""), |(key, value)| { - (key.trim(), value.trim()) - }); + .map_or((attribute.trim(), ""), |(key, value)| (key.trim(), value.trim())); match key.to_ascii_lowercase().as_str() { "domain" => cookie.domain = Some(value.to_string()), "path" => cookie.path = Some(value.to_string()), @@ -171,11 +169,7 @@ mod tests { use super::*; fn header(key: &str, value: &str) -> KeyValue { - KeyValue { - key: key.to_string(), - value: value.to_string(), - ..KeyValue::default() - } + KeyValue { key: key.to_string(), value: value.to_string(), ..KeyValue::default() } } /// Read off its type, whatever its case and parameters; with none, a body that parses as @@ -211,10 +205,7 @@ mod tests { let headers = [ header("Content-Type", "text/plain"), header("X-Not-A-Cookie", "a=b"), - header( - "set-cookie", - "sid=\"abc=1\"; Domain=shop.test; Path=/; HttpOnly; Secure; SameSite=Lax", - ), + header("set-cookie", "sid=\"abc=1\"; Domain=shop.test; Path=/; HttpOnly; Secure; SameSite=Lax"), header("Set-Cookie", "theme=dark"), header("Set-Cookie", "no equals sign"), header("Set-Cookie", " =nameless"), @@ -235,11 +226,7 @@ mod tests { same_site: Some("Lax".to_string()), ..Cookie::default() }, - Cookie { - name: "theme".to_string(), - value: "dark".to_string(), - ..Cookie::default() - }, + Cookie { name: "theme".to_string(), value: "dark".to_string(), ..Cookie::default() }, ] ); } @@ -255,14 +242,8 @@ mod tests { assert_eq!(read[0].expires.as_deref(), Some("Max-Age=60"), "{line}"); } - let expires = cookies(&[header( - "Set-Cookie", - "a=1; expires=Wed, 21 Oct 2026 07:28:00 GMT", - )]); - assert_eq!( - expires[0].expires.as_deref(), - Some("Wed, 21 Oct 2026 07:28:00 GMT") - ); + let expires = cookies(&[header("Set-Cookie", "a=1; expires=Wed, 21 Oct 2026 07:28:00 GMT")]); + assert_eq!(expires[0].expires.as_deref(), Some("Wed, 21 Oct 2026 07:28:00 GMT")); } /// Two spaces a level; an empty object or array stays on its line; what a string holds is diff --git a/crates/engine/src/http/runner.rs b/crates/engine/src/http/runner.rs index 61e386afb..7228663e9 100644 --- a/crates/engine/src/http/runner.rs +++ b/crates/engine/src/http/runner.rs @@ -45,11 +45,7 @@ pub fn read_file(path: &str) -> Result { /// A CSV with its header, or a JSON array of objects: what the file's text reads as. pub fn read_data(text: &str) -> Result { let text = text.trim_start_matches('\u{feff}'); - let data = if text.trim_start().starts_with('[') { - from_json(text)? - } else { - from_csv(text)? - }; + let data = if text.trim_start().starts_with('[') { from_json(text)? } else { from_csv(text)? }; if data.rows.is_empty() { return Err(DataFault::Empty); } @@ -225,12 +221,7 @@ impl RunSummary { #[must_use] pub fn of(results: &[RunResult]) -> Self { let count = |held: usize| u32::try_from(held).unwrap_or(u32::MAX); - let ran = || { - results - .iter() - .flat_map(|result| &result.tests) - .filter(|test| !test.skipped) - }; + let ran = || results.iter().flat_map(|result| &result.tests).filter(|test| !test.skipped); Self { failures: count(results.iter().filter(|result| result.failed()).count()), requests: count(results.len()), @@ -344,10 +335,7 @@ pub fn run_order(saved: &[RunEntry], placed: &[Placed]) -> Vec { } for request in placed { if !order.iter().any(|kept| kept.id == request.id) { - order.push(RunEntry { - id: request.id.clone(), - enabled: true, - }); + order.push(RunEntry { id: request.id.clone(), enabled: true }); } } order @@ -389,10 +377,7 @@ pub fn result_of( } Err(error) if error.code == ErrorCode::HttpScriptSkipped => result.skipped = true, Err(error) => { - result.error = Some(RunError { - code: error.code, - params: error.params, - }); + result.error = Some(RunError { code: error.code, params: error.params }); } } result @@ -412,10 +397,7 @@ pub fn gone(iteration: u32, placed: &Placed, error: AppError) -> RunResult { reason: String::new(), millis: 0, tests: Vec::new(), - error: Some(RunError { - code: error.code, - params: error.params, - }), + error: Some(RunError { code: error.code, params: error.params }), stop: None, skipped: false, response: None, @@ -463,9 +445,7 @@ impl Runs { pub fn cancel_all(&self) { if let Ok(mut running) = self.running.lock() { - running - .values_mut() - .for_each(|(cancelled, _)| *cancelled = true); + running.values_mut().for_each(|(cancelled, _)| *cancelled = true); } } @@ -517,18 +497,13 @@ mod tests { /// as JSON; a byte-order mark before it is no reason to refuse it. #[test] fn a_json_array_of_objects_is_read_a_row_an_object() { - let data = read_data( - "\u{feff} [{\"user\":\"ada\",\"age\":36},{\"admin\":true,\"user\":\"bob\"}]", - ) - .unwrap(); + let data = + read_data("\u{feff} [{\"user\":\"ada\",\"age\":36},{\"admin\":true,\"user\":\"bob\"}]").unwrap(); assert_eq!(columns(&data), ["user", "age", "admin"]); assert_eq!( data.rows, - [ - row(&[("user", "ada"), ("age", "36")]), - row(&[("admin", "true"), ("user", "bob")]) - ] + [row(&[("user", "ada"), ("age", "36")]), row(&[("admin", "true"), ("user", "bob")])] ); } @@ -537,18 +512,13 @@ mod tests { #[test] fn a_csv_with_its_header_is_read_a_row_a_line() { let data = - read_data("user , note,,age\r\nada,\"a, \"\"quoted\"\"\nnote\",x,36\r\n\r\nbob\n") - .unwrap(); + read_data("user , note,,age\r\nada,\"a, \"\"quoted\"\"\nnote\",x,36\r\n\r\nbob\n").unwrap(); assert_eq!(columns(&data), ["user", "note", "", "age"]); assert_eq!( data.rows, [ - row(&[ - ("user", "ada"), - ("note", "a, \"quoted\"\nnote"), - ("age", "36") - ]), + row(&[("user", "ada"), ("note", "a, \"quoted\"\nnote"), ("age", "36")]), row(&[("user", "bob"), ("note", ""), ("age", "")]), ] ); @@ -585,10 +555,7 @@ mod tests { let data = read_file(path.to_str().unwrap()).unwrap(); assert_eq!(data.rows, [row(&[("user", "ada")])]); - assert_eq!( - read_file(missing.to_str().unwrap()).unwrap_err().code, - ErrorCode::FileAccess - ); + assert_eq!(read_file(missing.to_str().unwrap()).unwrap_err().code, ErrorCode::FileAccess); } /// A data file past the cap is refused before it is read whole (a defect once met). @@ -648,11 +615,7 @@ mod tests { "c-1", vec![ request("a"), - folder( - "f-1", - "Auth", - vec![request("b"), folder("f-2", "Deep", vec![request("c")])], - ), + folder("f-1", "Auth", vec![request("b"), folder("f-2", "Deep", vec![request("c")])]), request("d"), ], ), @@ -662,16 +625,10 @@ mod tests { } fn placed(item: HttpItemKind, id: &str) -> Vec<(String, Vec)> { - placed_under( - &tree(), - &HttpItem { - kind: item, - id: id.to_string(), - }, - ) - .into_iter() - .map(|placed| (placed.id, placed.path)) - .collect() + placed_under(&tree(), &HttpItem { kind: item, id: id.to_string() }) + .into_iter() + .map(|placed| (placed.id, placed.path)) + .collect() } /// Each request under a collection or a folder, in the tree's order, with the folders @@ -689,50 +646,26 @@ mod tests { ("d".to_string(), path(&[])), ] ); - assert_eq!( - placed(HttpItemKind::Folder, "f-2"), - [("c".to_string(), path(&[]))] - ); + assert_eq!(placed(HttpItemKind::Folder, "f-2"), [("c".to_string(), path(&[]))]); assert!(placed(HttpItemKind::Folder, "missing").is_empty()); assert!(placed(HttpItemKind::Request, "a").is_empty()); } fn entry(id: &str, enabled: bool) -> RunEntry { - RunEntry { - id: id.to_string(), - enabled, - } + RunEntry { id: id.to_string(), enabled } } /// The order last arranged, less what went since and once each, then what was added since /// in the tree's order, switched on. #[test] fn a_run_takes_the_order_last_arranged_and_what_came_since() { - let here: Vec = placed_under( - &tree(), - &HttpItem { - kind: HttpItemKind::Collection, - id: "c-1".to_string(), - }, - ); - let saved = [ - entry("d", false), - entry("gone", true), - entry("b", true), - entry("d", true), - ]; + let here: Vec = + placed_under(&tree(), &HttpItem { kind: HttpItemKind::Collection, id: "c-1".to_string() }); + let saved = [entry("d", false), entry("gone", true), entry("b", true), entry("d", true)]; let order = run_order(&saved, &here); - assert_eq!( - order, - [ - entry("d", false), - entry("b", true), - entry("a", true), - entry("c", true) - ] - ); + assert_eq!(order, [entry("d", false), entry("b", true), entry("a", true), entry("c", true)]); } /// `run:#.` belongs to its run; any other send to none. @@ -781,31 +714,19 @@ mod tests { body: crate::http::send::SentBody::None, }, graphql: None, - scripts: ScriptsAnswer { - failure, - tests, - ..ScriptsAnswer::default() - }, + scripts: ScriptsAnswer { failure, tests, ..ScriptsAnswer::default() }, } } fn test(name: &str, passed: bool, skipped: bool) -> TestResult { - TestResult { - name: name.to_string(), - passed, - skipped, - ..TestResult::default() - } + TestResult { name: name.to_string(), passed, skipped, ..TestResult::default() } } /// An answer's status, time, tests and stop, its body kept only when asked; a skip is not a /// failure; another error is kept as its code and what it states. #[test] fn a_request_of_a_run_ends_as_its_answer_says() { - let stop = ScriptStop { - message: "boom".to_string(), - ..ScriptStop::default() - }; + let stop = ScriptStop { message: "boom".to_string(), ..ScriptStop::default() }; let answered = result_of( 2, &held("Login"), @@ -813,13 +734,7 @@ mod tests { Ok(answer(vec![test("ok", true, false)], Some(stop.clone()))), false, ); - let kept = result_of( - 1, - &held("Login"), - Vec::new(), - Ok(answer(Vec::new(), None)), - true, - ); + let kept = result_of(1, &held("Login"), Vec::new(), Ok(answer(Vec::new(), None)), true); let skipped = result_of( 1, &held("Login"), @@ -831,39 +746,20 @@ mod tests { 1, &held("Login"), Vec::new(), - Err(AppError::with( - ErrorCode::HttpTimeout, - String::new(), - "delay", - "30 s", - )), + Err(AppError::with(ErrorCode::HttpTimeout, String::new(), "delay", "30 s")), true, ); assert_eq!( - ( - answered.iteration, - answered.request_id.as_str(), - answered.name.as_str() - ), + (answered.iteration, answered.request_id.as_str(), answered.name.as_str()), (2, "login", "Login") ); assert_eq!( (answered.kind, answered.method, answered.path.as_slice()), - ( - RequestKind::Graphql, - HttpMethod::Post, - ["Auth".to_string()].as_slice() - ) - ); - assert_eq!( - (answered.status, answered.reason.as_str(), answered.millis), - (Some(201), "Created", 42) - ); - assert_eq!( - (answered.tests.len(), answered.stop, answered.response), - (1, Some(stop), None) + (RequestKind::Graphql, HttpMethod::Post, ["Auth".to_string()].as_slice()) ); + assert_eq!((answered.status, answered.reason.as_str(), answered.millis), (Some(201), "Created", 42)); + assert_eq!((answered.tests.len(), answered.stop, answered.response), (1, Some(stop), None)); assert!(kept.response.is_some()); assert!(skipped.skipped && skipped.error.is_none() && !skipped.failed()); assert_eq!( @@ -883,31 +779,16 @@ mod tests { 1, &held("A"), Vec::new(), - Ok(answer( - vec![test("ok", true, false), test("later", false, true)], - None, - )), + Ok(answer(vec![test("ok", true, false), test("later", false, true)], None)), false, ); - let failing_test = RunResult { - tests: vec![test("bad", false, false)], - ..base.clone() - }; - let stopped = RunResult { - stop: Some(ScriptStop::default()), - ..base.clone() - }; + let failing_test = RunResult { tests: vec![test("bad", false, false)], ..base.clone() }; + let stopped = RunResult { stop: Some(ScriptStop::default()), ..base.clone() }; let errored = RunResult { - error: Some(RunError { - code: ErrorCode::HttpTimeout, - params: BTreeMap::new(), - }), + error: Some(RunError { code: ErrorCode::HttpTimeout, params: BTreeMap::new() }), ..base.clone() }; - let skipped = RunResult { - skipped: true, - ..failing_test.clone() - }; + let skipped = RunResult { skipped: true, ..failing_test.clone() }; assert!(!base.failed()); assert!(failing_test.failed() && stopped.failed() && errored.failed()); @@ -921,58 +802,27 @@ mod tests { 1, &held("A"), Vec::new(), - Ok(answer( - vec![ - test("a", true, false), - test("b", false, false), - test("c", false, true), - ], - None, - )), + Ok(answer(vec![test("a", true, false), test("b", false, false), test("c", false, true)], None)), false, ); - let clean = RunResult { - tests: vec![test("d", true, false)], - ..base.clone() - }; + let clean = RunResult { tests: vec![test("d", true, false)], ..base.clone() }; let summary = RunSummary::of(&[base, clean]); - assert_eq!( - summary, - RunSummary { - failures: 1, - requests: 2, - passed: 2, - tests: 3 - } - ); + assert_eq!(summary, RunSummary { failures: 1, requests: 2, passed: 2, tests: 3 }); assert_eq!(RunSummary::of(&[]), RunSummary::default()); } /// A request gone when its turn comes ends as the error that says so, under its place. #[test] fn a_request_gone_since_ends_as_its_error() { - let placed = Placed { - id: "r-9".to_string(), - name: "Gone".to_string(), - path: vec!["Auth".to_string()], - }; + let placed = + Placed { id: "r-9".to_string(), name: "Gone".to_string(), path: vec!["Auth".to_string()] }; - let result = gone( - 3, - &placed, - AppError::with(ErrorCode::HttpItemNotFound, String::new(), "id", "r-9"), - ); + let result = + gone(3, &placed, AppError::with(ErrorCode::HttpItemNotFound, String::new(), "id", "r-9")); - assert_eq!( - ( - result.iteration, - result.request_id.as_str(), - result.name.as_str() - ), - (3, "r-9", "Gone") - ); + assert_eq!((result.iteration, result.request_id.as_str(), result.name.as_str()), (3, "r-9", "Gone")); assert_eq!(result.path, ["Auth"]); assert_eq!(result.error.unwrap().code, ErrorCode::HttpItemNotFound); assert_eq!(result.status, None); @@ -984,23 +834,13 @@ mod tests { fn a_run_goes_on_to_the_next_request_or_where_a_script_points() { let order: Vec = ["a", "b", "c"] .iter() - .map(|name| Placed { - id: (*name).to_string(), - name: name.to_uppercase(), - path: Vec::new(), - }) + .map(|name| Placed { id: (*name).to_string(), name: name.to_uppercase(), path: Vec::new() }) .collect(); assert_eq!(next_index(&order, 0, None), Some(1)); assert_eq!(next_index(&order, 2, None), None); - assert_eq!( - next_index(&order, 2, Some(&Next::To("A".to_string()))), - Some(0) - ); - assert_eq!( - next_index(&order, 0, Some(&Next::To("missing".to_string()))), - None - ); + assert_eq!(next_index(&order, 2, Some(&Next::To("A".to_string()))), Some(0)); + assert_eq!(next_index(&order, 0, Some(&Next::To("missing".to_string()))), None); assert_eq!(next_index(&order, 0, Some(&Next::End)), None); } diff --git a/crates/engine/src/http/scripts/around.rs b/crates/engine/src/http/scripts/around.rs index aab49d16a..adefb7d63 100644 --- a/crates/engine/src/http/scripts/around.rs +++ b/crates/engine/src/http/scripts/around.rs @@ -60,17 +60,9 @@ impl Around { scripts: &above.scripts, }) .collect(); - levels.push(Holder { - level: ScriptLevel::Request, - owner: None, - name: request, - scripts: own, - }); + levels.push(Holder { level: ScriptLevel::Request, owner: None, name: request, scripts: own }); Self { - before: levels - .iter() - .filter_map(|level| level.script(ScriptKind::Before)) - .collect(), + before: levels.iter().filter_map(|level| level.script(ScriptKind::Before)).collect(), after: levels .iter() .rev() @@ -112,23 +104,13 @@ pub fn layers_of(layers: &[VariableLayer]) -> Vec { VariableScope::Dynamic => return None, }; let mut values = std::collections::BTreeMap::new(); - for (variable, fault) in layer - .variables - .iter() - .zip(variable_faults(&layer.variables)) - { + for (variable, fault) in layer.variables.iter().zip(variable_faults(&layer.variables)) { let name = variable.name.trim(); if variable.enabled && !name.is_empty() && fault.is_none() { - values - .entry(name.to_string()) - .or_insert_with(|| variable.value.clone()); + values.entry(name.to_string()).or_insert_with(|| variable.value.clone()); } } - Some(ScriptLayer { - scope, - from: layer.from.clone(), - values, - }) + Some(ScriptLayer { scope, from: layer.from.clone(), values }) }) .collect() } @@ -149,10 +131,7 @@ pub fn written<'a>( table.retain(|variable| variable.name.trim() != name); continue; }; - match table - .iter_mut() - .find(|variable| variable.name.trim() == name) - { + match table.iter_mut().find(|variable| variable.name.trim() == name) { Some(variable) => { variable.value.clone_from(value); if write.secret { @@ -166,11 +145,7 @@ pub fn written<'a>( enabled: true, name: name.to_string(), value: value.clone(), - kind: if write.secret { - VariableKind::Secret - } else { - VariableKind::Text - }, + kind: if write.secret { VariableKind::Secret } else { VariableKind::Text }, filled_by: by.cloned(), }), } @@ -179,10 +154,7 @@ pub fn written<'a>( } /// The writes a phase made to one table. -pub fn writes_to( - writes: &[VariableWrite], - scope: WriteScope, -) -> impl Iterator { +pub fn writes_to(writes: &[VariableWrite], scope: WriteScope) -> impl Iterator { writes.iter().filter(move |write| write.scope == scope) } @@ -249,11 +221,7 @@ mod tests { use crate::http::settings::{self, HttpOrigin}; fn scripts(before: &str, after: &str, tests: &str) -> RequestScripts { - RequestScripts { - before: before.to_string(), - after: after.to_string(), - tests: tests.to_string(), - } + RequestScripts { before: before.to_string(), after: after.to_string(), tests: tests.to_string() } } fn above( @@ -262,18 +230,8 @@ mod tests { name: &str, held: RequestScripts, ) -> (HttpOrigin, ContainerSettings) { - let origin = HttpOrigin { - kind, - id: id.to_string(), - name: name.to_string(), - }; - ( - origin, - ContainerSettings { - scripts: held, - ..ContainerSettings::default() - }, - ) + let origin = HttpOrigin { kind, id: id.to_string(), name: name.to_string() }; + (origin, ContainerSettings { scripts: held, ..ContainerSettings::default() }) } /// The collection `API` over the folder `Invoices`, each with its scripts, and the request's. @@ -297,11 +255,7 @@ mod tests { assert_eq!( ids(&around.before), - [ - "collection:c1:before", - "folder:f1:before", - "request:request:before" - ] + ["collection:c1:before", "folder:f1:before", "request:request:before"] ); } @@ -326,11 +280,7 @@ mod tests { #[test] fn a_blank_script_is_not_run() { - let around = around( - scripts(" \n", "", ""), - scripts("a()", "\t", ""), - &scripts("", "b()", " "), - ); + let around = around(scripts(" \n", "", ""), scripts("a()", "\t", ""), &scripts("", "b()", " ")); assert_eq!(ids(&around.before), ["folder:f1:before"]); assert_eq!(ids(&around.answered()), ["request:request:after"]); @@ -339,36 +289,20 @@ mod tests { #[test] fn a_request_with_a_script_of_any_kind_is_not_without_one() { - for own in [ - scripts("a()", "", ""), - scripts("", "a()", ""), - scripts("", "", "a()"), - ] { - assert!( - !Around::of(&own, "Pay", &settings::inherit(&[])).is_empty(), - "{own:?}" - ); + for own in [scripts("a()", "", ""), scripts("", "a()", ""), scripts("", "", "a()")] { + assert!(!Around::of(&own, "Pay", &settings::inherit(&[])).is_empty(), "{own:?}"); } } #[test] fn a_script_says_who_holds_it() { - let around = around( - scripts("c()", "", ""), - scripts("f()", "", ""), - &scripts("r()", "", ""), - ); + let around = around(scripts("c()", "", ""), scripts("f()", "", ""), &scripts("r()", "", "")); let held: Vec<_> = around .before .iter() .map(|script| { - ( - script.level, - script.name.as_str(), - script.owner.as_deref(), - script.source.as_str(), - ) + (script.level, script.name.as_str(), script.owner.as_deref(), script.source.as_str()) }) .collect(); assert_eq!( @@ -379,35 +313,19 @@ mod tests { (ScriptLevel::Request, "Pay", None, "r()"), ] ); - assert!( - around - .before - .iter() - .all(|script| script.kind == ScriptKind::Before) - ); + assert!(around.before.iter().all(|script| script.kind == ScriptKind::Before)); } fn variable(name: &str, value: &str) -> Variable { - Variable { - name: name.to_string(), - value: value.to_string(), - ..Variable::default() - } + Variable { name: name.to_string(), value: value.to_string(), ..Variable::default() } } fn secret(name: &str, value: &str) -> Variable { - Variable { - kind: VariableKind::Secret, - ..variable(name, value) - } + Variable { kind: VariableKind::Secret, ..variable(name, value) } } fn level(scope: VariableScope, variables: Vec) -> VariableLayer { - VariableLayer { - scope, - from: "Staging".to_string(), - variables, - } + VariableLayer { scope, from: "Staging".to_string(), variables } } #[test] @@ -434,23 +352,14 @@ mod tests { LayerScope::Globals ] ); - assert!( - read.iter() - .all(|layer| layer.from == "Staging" && layer.values["a"] == "1") - ); + assert!(read.iter().all(|layer| layer.from == "Staging" && layer.values["a"] == "1")); } /// As the send resolves them. #[test] fn a_row_switched_off_unnamed_or_at_fault_is_no_value_a_script_reads() { - let off = Variable { - enabled: false, - ..variable("off", "x") - }; - let number = Variable { - kind: VariableKind::Number, - ..variable("count", "many") - }; + let off = Variable { enabled: false, ..variable("off", "x") }; + let number = Variable { kind: VariableKind::Number, ..variable("count", "many") }; let rows = vec![ variable(" token ", "first"), variable("token", "second"), @@ -462,34 +371,19 @@ mod tests { let read = layers_of(&[level(VariableScope::Environment, rows)]); - assert_eq!( - read[0].values, - [("token".to_string(), "first".to_string())].into() - ); + assert_eq!(read[0].values, [("token".to_string(), "first".to_string())].into()); } fn set(scope: WriteScope, name: &str, value: &str) -> VariableWrite { - VariableWrite { - scope, - name: name.to_string(), - value: Some(value.to_string()), - secret: false, - } + VariableWrite { scope, name: name.to_string(), value: Some(value.to_string()), secret: false } } fn unset(name: &str) -> VariableWrite { - VariableWrite { - scope: WriteScope::Environment, - name: name.to_string(), - ..VariableWrite::default() - } + VariableWrite { scope: WriteScope::Environment, name: name.to_string(), ..VariableWrite::default() } } fn set_secret(name: &str, value: &str) -> VariableWrite { - VariableWrite { - secret: true, - ..set(WriteScope::Environment, name, value) - } + VariableWrite { secret: true, ..set(WriteScope::Environment, name, value) } } fn rows(table: &[Variable]) -> Vec<(&str, &str, VariableKind)> { @@ -502,28 +396,19 @@ mod tests { #[test] fn a_value_set_changes_its_row_and_a_secret_stays_one() { let table = [secret(" token ", "old"), variable("page", "1")]; - let writes = [ - set(WriteScope::Environment, "token", "new"), - set_secret("page", "2"), - ]; + let writes = [set(WriteScope::Environment, "token", "new"), set_secret("page", "2")]; let after = written(&table, &writes, None); assert_eq!( rows(&after), - [ - (" token ", "new", VariableKind::Secret), - ("page", "2", VariableKind::Secret) - ] + [(" token ", "new", VariableKind::Secret), ("page", "2", VariableKind::Secret)] ); } #[test] fn a_value_set_under_a_new_name_is_a_row_at_the_end() { - let writes = [ - set(WriteScope::Environment, " page ", "2"), - set_secret("key", "k"), - ]; + let writes = [set(WriteScope::Environment, " page ", "2"), set_secret("key", "k")]; let after = written(&[variable("first", "1")], &writes, None); @@ -540,53 +425,24 @@ mod tests { #[test] fn a_value_unset_takes_every_row_of_its_name_and_the_writes_go_in_order() { - let table = [ - variable("gone", "1"), - variable("kept", "2"), - variable(" gone ", "3"), - ]; + let table = [variable("gone", "1"), variable("kept", "2"), variable(" gone ", "3")]; - let after = written( - &table, - &[unset("gone"), set(WriteScope::Environment, "gone", "4")], - None, - ); + let after = written(&table, &[unset("gone"), set(WriteScope::Environment, "gone", "4")], None); - assert_eq!( - rows(&after), - [ - ("kept", "2", VariableKind::Text), - ("gone", "4", VariableKind::Text) - ] - ); + assert_eq!(rows(&after), [("kept", "2", VariableKind::Text), ("gone", "4", VariableKind::Text)]); } #[test] fn a_row_set_says_which_request_filled_it_and_another_keeps_who_did() { - let login = FilledBy { - request_id: Some("r1".to_string()), - name: "Login".to_string(), - }; - let earlier = FilledBy { - request_id: None, - name: "Earlier".to_string(), - }; - let held = |name: &str| Variable { - filled_by: Some(earlier.clone()), - ..variable(name, "1") - }; - let writes = [ - set(WriteScope::Environment, "set", "2"), - set(WriteScope::Environment, "new", "3"), - ]; + let login = FilledBy { request_id: Some("r1".to_string()), name: "Login".to_string() }; + let earlier = FilledBy { request_id: None, name: "Earlier".to_string() }; + let held = |name: &str| Variable { filled_by: Some(earlier.clone()), ..variable(name, "1") }; + let writes = [set(WriteScope::Environment, "set", "2"), set(WriteScope::Environment, "new", "3")]; let named = written(&[held("set"), held("left")], &writes, Some(&login)); let unnamed = written(&[held("set")], &writes[..1], None); - let by: Vec<_> = named - .iter() - .map(|row| row.filled_by.as_ref().unwrap().name.as_str()) - .collect(); + let by: Vec<_> = named.iter().map(|row| row.filled_by.as_ref().unwrap().name.as_str()).collect(); assert_eq!(by, ["Login", "Earlier", "Login"]); assert_eq!(unnamed[0].filled_by, Some(earlier)); } @@ -609,14 +465,8 @@ mod tests { ); let resolver = variables::Resolver::new(&layers); - assert_eq!( - resolver.fill("{{token}}/{{tenant}}/{{page}}"), - "t0k3n/acme/2" - ); - assert_eq!( - resolver.secrets(), - [("token".to_string(), "t0k3n".to_string())] - ); + assert_eq!(resolver.fill("{{token}}/{{tenant}}/{{page}}"), "t0k3n/acme/2"); + assert_eq!(resolver.secrets(), [("token".to_string(), "t0k3n".to_string())]); } /// With « Aucun », there is no environment to write to: the rest is still applied. @@ -624,28 +474,17 @@ mod tests { fn a_write_to_a_level_the_send_has_not_changes_nothing_else() { let mut layers = [level(VariableScope::Globals, vec![variable("kept", "1")])]; - apply( - &mut layers, - &[ - set(WriteScope::Collection, "nowhere", "1"), - set(WriteScope::Data, "row", "1"), - ], - ); + apply(&mut layers, &[set(WriteScope::Collection, "nowhere", "1"), set(WriteScope::Data, "row", "1")]); - assert_eq!( - rows(&layers[0].variables), - [("kept", "1", VariableKind::Text)] - ); + assert_eq!(rows(&layers[0].variables), [("kept", "1", VariableKind::Text)]); } #[test] fn local_variables_are_nearer_than_the_request_s_own() { let locals = locals_layer(&[("path".to_string(), "orders".to_string())].into()); - let resolver = variables::Resolver::new(&[ - locals, - level(VariableScope::Request, vec![variable("path", "own")]), - ]); + let resolver = + variables::Resolver::new(&[locals, level(VariableScope::Request, vec![variable("path", "own")])]); assert_eq!(resolver.fill("/{{path}}"), "/orders"); } @@ -670,11 +509,7 @@ mod tests { ..TestResult::default() }; - let shown = shown_tests( - vec![test], - &[script], - &[("token".to_string(), "t0k3n".to_string())], - ); + let shown = shown_tests(vec![test], &[script], &[("token".to_string(), "t0k3n".to_string())]); let test = &shown[0]; assert_eq!(test.name, "holds {{token}}"); @@ -682,9 +517,6 @@ mod tests { assert_eq!(test.expected.as_deref(), Some("expected {{token}}")); assert_eq!(test.actual.as_deref(), Some("actual {{token}}")); assert_eq!(test.code.as_deref(), Some("expect('{{token}}').toBe(a);")); - assert_eq!( - (test.kind, test.holder.as_deref()), - (Some(ScriptKind::Tests), Some("Pay")) - ); + assert_eq!((test.kind, test.holder.as_deref()), (Some(ScriptKind::Tests), Some("Pay"))); } } diff --git a/crates/engine/src/http/scripts/child.rs b/crates/engine/src/http/scripts/child.rs index 6029e40cb..7764791f1 100644 --- a/crates/engine/src/http/scripts/child.rs +++ b/crates/engine/src/http/scripts/child.rs @@ -21,11 +21,7 @@ const STACK: usize = 16 * 1024 * 1024; /// What the application writes to the host. #[derive(Debug, Serialize, Deserialize)] -#[serde( - tag = "type", - rename_all = "camelCase", - rename_all_fields = "camelCase" -)] +#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")] pub enum ToHost { Run { job: Box, millis: u64 }, Reply { id: u64, answer: String }, @@ -33,29 +29,14 @@ pub enum ToHost { /// What the host writes back. #[derive(Debug, Serialize, Deserialize)] -#[serde( - tag = "type", - rename_all = "camelCase", - rename_all_fields = "camelCase" -)] +#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")] pub enum FromHost { - Call { - id: u64, - kind: String, - payload: String, - }, - Log { - entry: LogEntry, - }, - Done { - outcome: Box, - }, + Call { id: u64, kind: String, payload: String }, + Log { entry: LogEntry }, + Done { outcome: Box }, } -pub(crate) fn write_line( - output: &mut W, - message: &T, -) -> std::io::Result<()> { +pub(crate) fn write_line(output: &mut W, message: &T) -> std::io::Result<()> { serde_json::to_writer(&mut *output, message)?; output.write_all(b"\n")?; output.flush() @@ -92,20 +73,13 @@ impl Host for Stdio { let mut channel = self.0.borrow_mut(); channel.last += 1; let id = channel.last; - let asked = FromHost::Call { - id, - kind: kind.to_string(), - payload: payload.to_string(), - }; + let asked = FromHost::Call { id, kind: kind.to_string(), payload: payload.to_string() }; if write_line(&mut channel.output, &asked).is_err() { return refusal("The application stopped answering"); } loop { match read_line(&mut channel.input) { - Some(ToHost::Reply { - id: answered, - answer, - }) if answered == id => return answer, + Some(ToHost::Reply { id: answered, answer }) if answered == id => return answer, Some(_) => {} None => return refusal("The application stopped answering"), } @@ -119,11 +93,7 @@ impl Host for Stdio { /// Serves until the application closes the input: `0`, or `1` when it could not answer. pub fn serve_on(input: R, output: W) -> i32 { - let channel = Rc::new(RefCell::new(Channel { - input, - output, - last: 0, - })); + let channel = Rc::new(RefCell::new(Channel { input, output, last: 0 })); let engine = Engine::new(Box::new(Stdio(Rc::clone(&channel)))); loop { let message = read_line(&mut channel.borrow_mut().input); @@ -140,9 +110,7 @@ pub fn serve_on(input: R, output: W) - ..ScriptFailure::default() }), }; - let done = FromHost::Done { - outcome: Box::new(outcome), - }; + let done = FromHost::Done { outcome: Box::new(outcome) }; if write_line(&mut channel.borrow_mut().output, &done).is_err() { return 1; } @@ -204,11 +172,7 @@ mod tests { }], ..Job::default() }; - serde_json::to_string(&ToHost::Run { - job: Box::new(job), - millis: 2000, - }) - .unwrap() + serde_json::to_string(&ToHost::Run { job: Box::new(job), millis: 2000 }).unwrap() } fn reply(id: u64) -> String { @@ -219,10 +183,7 @@ mod tests { /// What the host wrote for these lines, and the code it ended with. fn served(lines: &[String]) -> (Vec, i32) { let output = Shared::default(); - let code = serve_on( - Cursor::new(format!("{}\n", lines.join("\n"))), - output.clone(), - ); + let code = serve_on(Cursor::new(format!("{}\n", lines.join("\n"))), output.clone()); let bytes = output.0.lock().unwrap().clone(); let messages = String::from_utf8(bytes) .unwrap() @@ -239,34 +200,23 @@ mod tests { } } - const JAR: &str = - "pm.cookies.jar().getAll('https://x.y', (e, all) => env.set('n', all.length));"; + const JAR: &str = "pm.cookies.jar().getAll('https://x.y', (e, all) => env.set('n', all.length));"; #[test] fn a_job_is_answered_with_its_logs_its_calls_and_its_outcome_then_the_host_ends() { - let (messages, code) = - served(&[run_message(&format!("console.log('hi'); {JAR}")), reply(1)]); + let (messages, code) = served(&[run_message(&format!("console.log('hi'); {JAR}")), reply(1)]); assert_eq!((messages.len(), code), (3, 0)); assert!(matches!(&messages[0], FromHost::Log { entry } if entry.text == "hi")); assert!(matches!(&messages[1], FromHost::Call { id: 1, kind, .. } if kind == "jarAll")); let outcome = outcome(&messages[2]); - assert_eq!( - (&outcome.failure, outcome.writes[0].value.as_deref()), - (&None, Some("0")) - ); + assert_eq!((&outcome.failure, outcome.writes[0].value.as_deref()), (&None, Some("0"))); } #[test] fn a_line_that_does_not_read_and_an_answer_to_another_call_are_passed_over() { - let lines = [ - "not json".to_string(), - reply(9), - run_message(JAR), - "{}".to_string(), - reply(7), - reply(1), - ]; + let lines = + ["not json".to_string(), reply(9), run_message(JAR), "{}".to_string(), reply(7), reply(1)]; let (messages, code) = served(&lines); @@ -283,10 +233,7 @@ mod tests { let (messages, _) = served(&[first, second]); assert_eq!(messages.len(), 2); - assert_eq!( - outcome(&messages[1]).writes[0].value.as_deref(), - Some("yes") - ); + assert_eq!(outcome(&messages[1]).writes[0].value.as_deref(), Some("yes")); } #[test] @@ -294,11 +241,7 @@ mod tests { let (messages, _) = served(&[run_message("await pm.sendRequest('https://x.y');")]); let failure = outcome(messages.last().unwrap()).failure.clone().unwrap(); - assert!( - failure.message.contains("stopped answering"), - "{}", - failure.message - ); + assert!(failure.message.contains("stopped answering"), "{}", failure.message); } #[test] diff --git a/crates/engine/src/http/scripts/engine.rs b/crates/engine/src/http/scripts/engine.rs index 2a54f2bbb..9be8e6197 100644 --- a/crates/engine/src/http/scripts/engine.rs +++ b/crates/engine/src/http/scripts/engine.rs @@ -88,8 +88,7 @@ fn install<'js>(ctx: &Ctx<'js>, host: &Rc>>) -> rquickjs:: return Ok(None); }; let wrapped = format!("(function (module, exports, require) {{{source}\n}})"); - ctx.eval_with_options(wrapped, options(&format!("library:{name}"))) - .map(Some) + ctx.eval_with_options(wrapped, options(&format!("library:{name}"))).map(Some) }, )?, )?; @@ -116,11 +115,7 @@ fn place_in(stack: &str) -> Option<(usize, u32)> { /// What the engine threw, as a failure: the message, and the script and line it came from. fn caught(ctx: &Ctx<'_>, error: &rquickjs::Error, job: &Job, kind: FailureKind) -> ScriptFailure { - let mut failure = ScriptFailure { - kind, - message: error.to_string(), - ..ScriptFailure::default() - }; + let mut failure = ScriptFailure { kind, message: error.to_string(), ..ScriptFailure::default() }; if !matches!(error, rquickjs::Error::Exception) { return failure; } @@ -193,8 +188,7 @@ struct Loop<'js> { } fn drive(ctx: &Ctx<'_>, job: &Job, deadline: Instant, time: Duration) -> Outcome { - let failed = - |error: &rquickjs::Error| Outcome::failed(caught(ctx, error, job, FailureKind::Error)); + let failed = |error: &rquickjs::Error| Outcome::failed(caught(ctx, error, job, FailureKind::Error)); let functions = match compile(ctx, job) { Ok(functions) => functions, Err(failure) => return Outcome::failed(failure), @@ -221,13 +215,12 @@ fn drive(ctx: &Ctx<'_>, job: &Job, deadline: Instant, time: Duration) -> Outcome PromiseState::Resolved => { return match promise.result::() { Some(Ok(answer)) => { - let mut outcome: Outcome = - serde_json::from_str(&answer).unwrap_or_else(|error| { - Outcome::failed(ScriptFailure { - message: error.to_string(), - ..ScriptFailure::default() - }) - }); + let mut outcome: Outcome = serde_json::from_str(&answer).unwrap_or_else(|error| { + Outcome::failed(ScriptFailure { + message: error.to_string(), + ..ScriptFailure::default() + }) + }); if let Some(failure) = outcome.failure.as_mut() { classify(failure); } @@ -378,19 +371,11 @@ mod tests { .iter() .map(|(key, value)| ((*key).to_string(), (*value).to_string())) .collect(); - ScriptLayer { - scope, - from: String::new(), - values, - } + ScriptLayer { scope, from: String::new(), values } } fn row(key: &str, value: &str) -> ScriptRow { - ScriptRow { - key: key.to_string(), - value: value.to_string(), - ..ScriptRow::default() - } + ScriptRow { key: key.to_string(), value: value.to_string(), ..ScriptRow::default() } } /// A phase before the send: a `POST` of `{{baseUrl}}/pay?page=1`, on Staging. @@ -422,11 +407,7 @@ mod tests { } fn cookie(name: &str, value: &str) -> ScriptCookie { - ScriptCookie { - name: name.to_string(), - value: value.to_string(), - ..ScriptCookie::default() - } + ScriptCookie { name: name.to_string(), value: value.to_string(), ..ScriptCookie::default() } } /// A phase after the answer: a `402` whose body is `{"currency":"usd","items":[{"id":7}]}`. @@ -437,11 +418,7 @@ mod tests { response: Some(ScriptResponse { code: 402, reason: "Payment Required".to_string(), - headers: vec![ - row("Content-Type", "application/json"), - row("Vary", "a"), - row("vary", "b"), - ], + headers: vec![row("Content-Type", "application/json"), row("Vary", "a"), row("vary", "b")], body: r#"{"currency":"usd","items":[{"id":7}]}"#.to_string(), millis: 203, size: 37, @@ -466,9 +443,7 @@ mod tests { hosted(move || { let lines: Vec = cases .iter() - .map(|(expression, _)| { - format!("console.log(String(JSON.stringify({expression})));") - }) + .map(|(expression, _)| format!("console.log(String(JSON.stringify({expression})));")) .collect(); let (engine, seen) = engine(); let outcome = engine.run( @@ -528,16 +503,9 @@ mod tests { (request.method.as_str(), request.url.as_str()), ("PUT", "{{baseUrl}}/pay?page=1&retry=1") ); - let headers = [ - row("Accept", "application/json"), - row("X-Signature", "abc"), - row("X-Trace", "1"), - ]; + let headers = [row("Accept", "application/json"), row("X-Signature", "abc"), row("X-Trace", "1")]; assert_eq!(request.headers, headers); - assert_eq!( - (request.body.mode.as_str(), request.body.raw.as_str()), - ("raw", "{\"amount\":2}") - ); + assert_eq!((request.body.mode.as_str(), request.body.raw.as_str()), ("raw", "{\"amount\":2}")); }); } @@ -568,20 +536,11 @@ mod tests { fn a_form_s_file_part_stays_a_file_through_a_script() { hosted(|| { let mut job = before("pm.request.body.formdata.add({ key: 'note', value: 'x' });"); - let scan = ScriptRow { - part: Some("file".to_string()), - ..row("scan", "/tmp/scan.png") - }; - job.request.body = ScriptBody { - mode: "formdata".to_string(), - formdata: vec![scan], - ..ScriptBody::default() - }; + let scan = ScriptRow { part: Some("file".to_string()), ..row("scan", "/tmp/scan.png") }; + job.request.body = + ScriptBody { mode: "formdata".to_string(), formdata: vec![scan], ..ScriptBody::default() }; let parts = run(&job).request.unwrap().body.formdata; - let parts: Vec<_> = parts - .iter() - .map(|part| (part.key.as_str(), part.part.as_deref())) - .collect(); + let parts: Vec<_> = parts.iter().map(|part| (part.key.as_str(), part.part.as_deref())).collect(); assert_eq!(parts, [("scan", Some("file")), ("note", Some("text"))]); }); } @@ -596,20 +555,11 @@ mod tests { hold( before, &[ - ( - "[req.method, req.url, req.body]", - r#"["POST","{{baseUrl}}/pay?page=1",""]"#, - ), + ("[req.method, req.url, req.body]", r#"["POST","{{baseUrl}}/pay?page=1",""]"#), ("req.headers.get('accept')", r#""application/json""#), ("request.headers", r#"{"Accept":"application/json"}"#), - ( - "[request.method, request.url]", - r#"["POST","{{baseUrl}}/pay?page=1"]"#, - ), - ( - "pm.request.getHeaders({ ignoreCase: true })", - r#"{"accept":"application/json"}"#, - ), + ("[request.method, request.url]", r#"["POST","{{baseUrl}}/pay?page=1"]"#), + ("pm.request.getHeaders({ ignoreCase: true })", r#"{"accept":"application/json"}"#), ( "(pm.request.addHeader({ key: 'A', value: 'b', disabled: true }), pm.request.getHeaders({ enabled: true }))", r#"{"Accept":"application/json"}"#, @@ -728,10 +678,7 @@ mod tests { "(pm.request.headers.remove('z'), pm.request.headers.remove({ key: 'y' }), pm.request.headers.remove((row) => row.value === '3'), pm.request.headers.delete('A'), pm.request.headers.repopulate([{ key: 'last' }]), pm.request.headers)", r#"[{"key":"last","value":"","disabled":false}]"#, ), - ( - "(pm.request.headers.set('last'), pm.request.headers.get('last'))", - r#""""#, - ), + ("(pm.request.headers.set('last'), pm.request.headers.get('last'))", r#""""#), ], ); } @@ -743,14 +690,9 @@ mod tests { let asking = |header: &str| { format!("await pm.sendRequest({{ url: 'https://a.test', header: {header} }});") }; - let source = [ - "[{ key: 'A', value: '1' }]", - "{ A: 1 }", - "'A: 1\\r\\nnot a header'", - "null", - ] - .map(asking) - .join("\n"); + let source = ["[{ key: 'A', value: '1' }]", "{ A: 1 }", "'A: 1\\r\\nnot a header'", "null"] + .map(asking) + .join("\n"); assert_eq!(engine.run(&before(&source), SECONDS).failure, None); let sent: Vec<_> = seen .borrow() @@ -770,15 +712,9 @@ mod tests { hold( after, &[ - ( - "[res.status, res.statusText, res.time, res.size]", - r#"[402,"Payment Required",203,37]"#, - ), + ("[res.status, res.statusText, res.time, res.size]", r#"[402,"Payment Required",203,37]"#), // Two headers of one name are one, as a browser joins them. - ( - "res.headers", - r#"{"content-type":"application/json","vary":"a, b"}"#, - ), + ("res.headers", r#"{"content-type":"application/json","vary":"a, b"}"#), ( "[res.body === res.text(), res.json().currency, res.cookies]", r#"[true,"usd",{"sid":"42"}]"#, @@ -801,10 +737,7 @@ mod tests { "[pm.response.json().items[0].id, pm.response.stream.length, pm.response.headers.get('VARY')]", r#"[7,37,"a"]"#, ), - ( - "Object.keys(pm.response.toJSON())", - r#"["code","status","headers","body"]"#, - ), + ("Object.keys(pm.response.toJSON())", r#"["code","status","headers","body"]"#), ], ); } @@ -836,10 +769,7 @@ mod tests { hold( before, &[ - ( - "[typeof res, pm.response, typeof responseBody]", - r#"["undefined",null,"undefined"]"#, - ), + ("[typeof res, pm.response, typeof responseBody]", r#"["undefined",null,"undefined"]"#), ( "[postman.getResponseHeader('a') === undefined, postman.getResponseCookie('a') === undefined]", "[true,true]", @@ -855,9 +785,7 @@ mod tests { job.response.as_mut().unwrap().body = "".to_string(); let failure = run(&job).failure.unwrap(); assert!( - failure - .message - .starts_with("SyntaxError: The response is not JSON: "), + failure.message.starts_with("SyntaxError: The response is not JSON: "), "{}", failure.message ); @@ -942,14 +870,8 @@ mod tests { "(pm.variables.set('tenant', 'local'), [env.get('tenant'), pm.variables.toObject().tenant, env.replaceIn('{{tenant}}')])", r#"["local","local","local"]"#, ), - ( - "(pm.variables.unset('tenant'), env.get('tenant'))", - r#""near""#, - ), - ( - "(pm.variables.set('a', 1), pm.variables.clear(), env.has('a'))", - "false", - ), + ("(pm.variables.unset('tenant'), env.get('tenant'))", r#""near""#), + ("(pm.variables.set('a', 1), pm.variables.clear(), env.has('a'))", "false"), ], ); } @@ -962,38 +884,15 @@ mod tests { "for (const value of ['a', 42, true, null, undefined, { a: 1 }, [1, 2]]) pm.globals.set('v', value); const loop = {}; loop.self = loop; pm.globals.set('v', loop);", )); - let values: Vec<_> = outcome - .writes - .iter() - .map(|write| write.value.as_deref().unwrap()) - .collect(); - assert_eq!( - values, - [ - "a", - "42", - "true", - "", - "", - "{\"a\":1}", - "[1,2]", - "[object Object]" - ] - ); + let values: Vec<_> = outcome.writes.iter().map(|write| write.value.as_deref().unwrap()).collect(); + assert_eq!(values, ["a", "42", "true", "", "", "{\"a\":1}", "[1,2]", "[object Object]"]); }); } fn writes(outcome: &Outcome) -> Vec<(WriteScope, &str, Option<&str>, bool)> { let writes = outcome.writes.iter(); writes - .map(|write| { - ( - write.scope, - write.name.as_str(), - write.value.as_deref(), - write.secret, - ) - }) + .map(|write| (write.scope, write.name.as_str(), write.value.as_deref(), write.secret)) .collect() } @@ -1027,12 +926,7 @@ mod tests { let mut job = before("env.set('a', 1); pm.environment.set('b', 2);"); job.environment = None; let outcome = run(&job); - assert!( - outcome - .writes - .iter() - .all(|write| write.scope == WriteScope::Globals) - ); + assert!(outcome.writes.iter().all(|write| write.scope == WriteScope::Globals)); assert_eq!(outcome.writes.len(), 2); }); } @@ -1086,16 +980,10 @@ mod tests { hosted(|| { let (engine, _) = engine(); let outcome = engine.run(&before("pm.variables.set('started', 'yes');"), SECONDS); - assert_eq!( - outcome.locals, - [("started".to_string(), "yes".to_string())].into() - ); + assert_eq!(outcome.locals, [("started".to_string(), "yes".to_string())].into()); assert!(outcome.writes.is_empty()); - let outcome = engine.run( - &after("env.set('kept', pm.variables.get('started'));"), - SECONDS, - ); + let outcome = engine.run(&after("env.set('kept', pm.variables.get('started'));"), SECONDS); assert_eq!(outcome.writes[0].value.as_deref(), Some("yes")); }); } @@ -1135,23 +1023,15 @@ mod tests { (failed.expected.as_deref(), failed.actual.as_deref()), (Some("\"eur\""), Some("\"usd\"")) ); - assert_eq!( - (failed.script.as_deref(), failed.line), - (Some("request:tests"), Some(3)) - ); + assert_eq!((failed.script.as_deref(), failed.line), (Some("request:tests"), Some(3))); assert!(failed.message.as_deref().unwrap().contains("eur")); } #[test] fn a_test_skipped_neither_passes_nor_fails() { - let tests = - tested("test.skip('later'); pm.test.skip('never', () => { throw new Error('ran'); });"); + let tests = tested("test.skip('later'); pm.test.skip('never', () => { throw new Error('ran'); });"); assert_eq!(tests.len(), 2); - assert!( - tests - .iter() - .all(|test| test.skipped && !test.passed && test.message.is_none()) - ); + assert!(tests.iter().all(|test| test.skipped && !test.passed && test.message.is_none())); } #[test] @@ -1163,10 +1043,7 @@ mod tests { test('no body');", ); let messages: Vec<_> = tests.iter().map(|test| test.message.as_deref()).collect(); - assert_eq!( - messages, - [Some("no"), Some("plain"), Some("undefined"), None] - ); + assert_eq!(messages, [Some("no"), Some("plain"), Some("undefined"), None]); assert!(tests[0].expected.is_none() && tests[0].actual.is_none()); assert!(tests[3].passed); } @@ -1191,10 +1068,7 @@ mod tests { .iter() .map(|test| (test.name.as_str(), test.passed, test.message.as_deref())) .collect(); - assert_eq!( - read, - [("holds", true, None), ("fails", false, Some("false"))] - ); + assert_eq!(read, [("holds", true, None), ("fails", false, Some("false"))]); } /// As the prelude writes a value: a text quoted, the rest as JSON, a long one cut. @@ -1207,11 +1081,7 @@ mod tests { test('loop', () => { const e = new Error('m'); e.actual = loop; throw e; }); test('long', () => { const e = new Error('m'); e.actual = [...'x'.repeat(3000)]; throw e; });", ); - let shown: Vec<_> = tests - .iter() - .take(12) - .map(|test| test.actual.as_deref().unwrap()) - .collect(); + let shown: Vec<_> = tests.iter().take(12).map(|test| test.actual.as_deref().unwrap()).collect(); assert_eq!( shown, [ @@ -1228,18 +1098,10 @@ mod tests { "\"xxxxxxxxxx\"", "[object Object]" ] - .map(|shown| if shown == "[Function value]" { - "[Function]" - } else { - shown - }) + .map(|shown| if shown == "[Function value]" { "[Function]" } else { shown }) ); let long = tests[12].actual.as_deref().unwrap(); - assert!( - long.ends_with('…') && long.chars().count() == 2001, - "{}", - long.len() - ); + assert!(long.ends_with('…') && long.chars().count() == 2001, "{}", long.len()); } #[test] @@ -1248,10 +1110,7 @@ mod tests { ("expect(1).toBe(1)", true), ("expect(NaN).toBe(NaN)", true), ("expect({}).toBe({})", false), - ( - "expect({ a: { b: [1, 2] } }).toEqual({ a: { b: [1, 2] } })", - true, - ), + ("expect({ a: { b: [1, 2] } }).toEqual({ a: { b: [1, 2] } })", true), ("expect({ a: 1 }).toEqual({ a: 2 })", false), ("expect([1]).toStrictEqual([1])", true), ("expect([1]).toStrictEqual([2])", false), @@ -1263,10 +1122,7 @@ mod tests { ("expect([{ a: 1 }]).toContainEqual({ a: 2 })", false), ("expect('DevNotes').toMatch(/notes/i)", true), ("expect('DevNotes').toMatch('notes')", false), - ( - "expect({ a: 1, b: { c: 2, d: 3 } }).toMatchObject({ b: { c: 2 } })", - true, - ), + ("expect({ a: 1, b: { c: 2, d: 3 } }).toMatchObject({ b: { c: 2 } })", true), ("expect({ a: [1, 2] }).toMatchObject({ a: [1] })", false), ("expect({ a: 1 }).toMatchObject({ b: undefined })", false), ("expect('a').toMatchObject({ a: 1 })", false), @@ -1279,20 +1135,11 @@ mod tests { ("expect(0.1 + 0.2).toBeCloseTo(0.3)", true), ("expect(0.31).toBeCloseTo(0.3)", false), ("expect(0.31).toBeCloseTo(0.3, 1)", true), - ( - "expect(res.headers).toHaveProperty('content-type', 'application/json')", - true, - ), + ("expect(res.headers).toHaveProperty('content-type', 'application/json')", true), ("expect(res.json()).toHaveProperty('items[0].id', 7)", true), - ( - "expect(res.json()).toHaveProperty(['items', 0, 'id'])", - true, - ), + ("expect(res.json()).toHaveProperty(['items', 0, 'id'])", true), ("expect(res.json()).toHaveProperty('items[1].id')", false), - ( - "expect(res.json()).toHaveProperty('currency', 'eur')", - false, - ), + ("expect(res.json()).toHaveProperty('currency', 'eur')", false), ("expect(null).toHaveProperty('a')", false), ("expect([1, 2, 3]).toHaveLength(3)", true), ("expect('abc').toHaveLength(2)", false), @@ -1309,26 +1156,11 @@ mod tests { ("expect('NaN').toBeNaN()", false), ("expect(new TypeError('x')).toBeInstanceOf(Error)", true), ("expect({}).toBeInstanceOf(Error)", false), - ( - "expect(() => { throw new TypeError('no'); }).toThrow()", - true, - ), - ( - "expect(() => { throw new TypeError('no'); }).toThrow(TypeError)", - true, - ), - ( - "expect(() => { throw new TypeError('no'); }).toThrow(RangeError)", - false, - ), - ( - "expect(() => { throw new TypeError('no way'); }).toThrow('way')", - true, - ), - ( - "expect(() => { throw new TypeError('no way'); }).toThrow(/^way/)", - false, - ), + ("expect(() => { throw new TypeError('no'); }).toThrow()", true), + ("expect(() => { throw new TypeError('no'); }).toThrow(TypeError)", true), + ("expect(() => { throw new TypeError('no'); }).toThrow(RangeError)", false), + ("expect(() => { throw new TypeError('no way'); }).toThrow('way')", true), + ("expect(() => { throw new TypeError('no way'); }).toThrow(/^way/)", false), ("expect(() => { throw 'plain'; }).toThrow('plain')", true), ("expect(() => {}).toThrow()", false), ("expect(() => {}).not.toThrow()", true), @@ -1359,33 +1191,21 @@ mod tests { ("pm.response.to.be.notFound", false), ("pm.response.to.not.be.rateLimited", true), ("pm.response.to.have.header('content-type')", true), - ( - "pm.response.to.have.header('Content-Type', 'application/json')", - true, - ), - ( - "pm.response.to.have.header('Content-Type', 'text/html')", - false, - ), + ("pm.response.to.have.header('Content-Type', 'application/json')", true), + ("pm.response.to.have.header('Content-Type', 'text/html')", false), ("pm.response.to.have.header('X-Gone')", false), ("pm.response.to.have.body()", true), ("pm.response.to.have.body(responseBody)", true), ("pm.response.to.have.body('other')", false), ("pm.response.to.have.body(/usd/)", true), - ( - "pm.response.to.have.body({ currency: 'usd', items: [{ id: 7 }] })", - true, - ), + ("pm.response.to.have.body({ currency: 'usd', items: [{ id: 7 }] })", true), ("pm.response.to.have.body({ currency: 'eur' })", false), ("pm.response.to.have.jsonBody()", true), ("pm.response.to.have.jsonBody('items[0].id')", true), ("pm.response.to.have.jsonBody('items[0].id', 7)", true), ("pm.response.to.have.jsonBody('items[0].id', 8)", false), ("pm.response.to.have.jsonBody('gone')", false), - ( - "pm.response.to.have.jsonBody({ currency: 'usd', items: [{ id: 7 }] })", - true, - ), + ("pm.response.to.have.jsonBody({ currency: 'usd', items: [{ id: 7 }] })", true), ("pm.response.to.be.json", true), ("pm.response.to.be.withBody", true), ("pm.expect(pm.response).to.have.responseTime(203)", true), @@ -1419,26 +1239,17 @@ mod tests { #[test] fn an_error_names_its_script_and_line_and_stops_the_phase() { hosted(|| { - let mut job = - before("env.set('first', 1);\nconst b = 2;\ntokn.read();\nenv.set('never', 1);"); - job.scripts - .push(script("collection:before", "env.set('later', 1);")); + let mut job = before("env.set('first', 1);\nconst b = 2;\ntokn.read();\nenv.set('never', 1);"); + job.scripts.push(script("collection:before", "env.set('later', 1);")); let outcome = run(&job); let failure = outcome.failure.clone().unwrap(); assert_eq!( (failure.kind, failure.script.as_deref(), failure.line), (FailureKind::Error, Some("request:before"), Some(3)) ); - assert!( - failure.message.starts_with("ReferenceError: "), - "{}", - failure.message - ); + assert!(failure.message.starts_with("ReferenceError: "), "{}", failure.message); // What it did before it stopped is kept. - assert_eq!( - writes(&outcome), - [(WriteScope::Environment, "first", Some("1"), false)] - ); + assert_eq!(writes(&outcome), [(WriteScope::Environment, "first", Some("1"), false)]); }); } @@ -1446,13 +1257,9 @@ mod tests { fn an_error_of_a_later_script_names_that_one() { hosted(|| { let mut job = before("const a = 1;"); - job.scripts - .push(script("collection:before", "\nthrow new Error('x');")); + job.scripts.push(script("collection:before", "\nthrow new Error('x');")); let failure = run(&job).failure.unwrap(); - assert_eq!( - (failure.script.as_deref(), failure.line), - (Some("collection:before"), Some(2)) - ); + assert_eq!((failure.script.as_deref(), failure.line), (Some("collection:before"), Some(2))); }); } @@ -1463,14 +1270,8 @@ mod tests { ("throw 'plain';", "plain"), ("throw null;", "null"), ("throw { message: 'object' };", "Error: object"), - ( - "await Promise.reject(new TypeError('late'));", - "TypeError: late", - ), - ( - "test('t', () => {}); throw new RangeError('after');", - "RangeError: after", - ), + ("await Promise.reject(new TypeError('late'));", "TypeError: late"), + ("test('t', () => {}); throw new RangeError('after');", "RangeError: after"), ] { let failure = failure(source); assert_eq!( @@ -1487,8 +1288,7 @@ mod tests { fn a_script_that_does_not_read_is_a_syntax_failure_on_its_line_and_nothing_runs() { hosted(|| { let mut job = before("env.set('ran', 1);"); - job.scripts - .push(script("folder:before", "const ok = 1;\nif (ok {\n}")); + job.scripts.push(script("folder:before", "const ok = 1;\nif (ok {\n}")); let outcome = run(&job); let failure = outcome.failure.unwrap(); assert_eq!( @@ -1531,8 +1331,7 @@ mod tests { #[test] fn a_script_that_takes_all_memory_ends_as_a_memory_failure() { hosted(|| { - let failure = - failure("const kept = []; while (true) kept.push(new Array(1e6).fill(1));"); + let failure = failure("const kept = []; while (true) kept.push(new Array(1e6).fill(1));"); assert_eq!(failure.kind, FailureKind::Memory); }); } @@ -1542,11 +1341,7 @@ mod tests { hosted(|| { let failure = failure("await new Promise(() => {});"); assert_eq!(failure.kind, FailureKind::Timeout); - assert!( - failure.message.contains("nothing settles"), - "{}", - failure.message - ); + assert!(failure.message.contains("nothing settles"), "{}", failure.message); }); } @@ -1555,10 +1350,7 @@ mod tests { fn a_stack_names_the_script_and_the_line() { for (stack, place) in [ (" at f (script-2:12:5)\n", Some((2, 12))), - ( - " at prelude:40\n at (script-0:3)\n", - Some((0, 3)), - ), + (" at prelude:40\n at (script-0:3)\n", Some((0, 3))), (" at script-x:1\n at script-1:7\n", Some((1, 7))), (" at script-4\n", None), (" at prelude:40\n", None), @@ -1587,20 +1379,14 @@ mod tests { await new Promise((resolve) => setTimeout(resolve, 1));", )); assert_eq!(outcome.failure, None); - assert_eq!( - outcome.writes[0].value.as_deref(), - Some("tick0,now,tick,soon,late") - ); + assert_eq!(outcome.writes[0].value.as_deref(), Some("tick0,now,tick,soon,late")); }); } #[test] fn a_timer_that_throws_or_is_given_no_function_stops_the_script() { hosted(|| { - assert_eq!( - failure("setTimeout(() => { throw new Error('late'); }, 1);").message, - "Error: late" - ); + assert_eq!(failure("setTimeout(() => { throw new Error('late'); }, 1);").message, "Error: late"); assert_eq!( failure("setTimeout('code', 1);").message, "TypeError: The callback must be a function" @@ -1629,18 +1415,12 @@ mod tests { hold( before, &[ - ( - "[require('lodash').chunk([1, 2, 3], 2).length, _.chunk([1, 2, 3], 2).length]", - "[2,2]", - ), + ("[require('lodash').chunk([1, 2, 3], 2).length, _.chunk([1, 2, 3], 2).length]", "[2,2]"), ( "[require('moment')('2026-10-19').format('DD/MM/YYYY'), typeof moment]", r#"["19/10/2026","function"]"#, ), - ( - "require('chai').expect(1).to.equal(1) !== undefined", - "true", - ), + ("require('chai').expect(1).to.equal(1) !== undefined", "true"), ( "CryptoJS.SHA256('abc').toString() === require('crypto-js').SHA256('abc').toString()", "true", @@ -1650,10 +1430,7 @@ mod tests { r#""ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad""#, ), ("/^[0-9a-f-]{36}$/.test(require('uuid').v4())", "true"), - ( - "new (require('ajv'))().validate({ type: 'object', required: ['id'] }, { id: 1 })", - "true", - ), + ("new (require('ajv'))().validate({ type: 'object', required: ['id'] }, { id: 1 })", "true"), ( "[tv4.validate({ id: 1 }, { type: 'object' }), tv4.validate(1, { type: 'object' })]", "[true,false]", @@ -1666,14 +1443,8 @@ mod tests { "[require('cheerio').load('

    Bonjour

    ')('.x').text(), typeof cheerio.load]", r#"["Bonjour","function"]"#, ), - ( - "require('csv-parse/lib/sync')('a,b\\n1,2', { columns: true })", - r#"[{"a":"1","b":"2"}]"#, - ), - ( - "require('csv-parse/sync').parse('a,b\\n1,2')", - r#"[["a","b"],["1","2"]]"#, - ), + ("require('csv-parse/lib/sync')('a,b\\n1,2', { columns: true })", r#"[{"a":"1","b":"2"}]"#), + ("require('csv-parse/sync').parse('a,b\\n1,2')", r#"[["a","b"],["1","2"]]"#), ( "[Buffer.from('DevNotes').toString('base64'), require('node:buffer').Buffer === Buffer]", r#"["RGV2Tm90ZXM=",true]"#, @@ -1686,35 +1457,17 @@ mod tests { "[require('path').join('/a', 'b', '../c'), require('path-browserify') === require('path/')]", r#"["/a/c",true]"#, ), - ( - "require('querystring').stringify({ a: 1, b: 'x y' })", - r#""a=1&b=x%20y""#, - ), - ( - "require('url').parse('https://example.com:8080/p?q=1').port", - r#""8080""#, - ), + ("require('querystring').stringify({ a: 1, b: 'x y' })", r#""a=1&b=x%20y""#), + ("require('url').parse('https://example.com:8080/p?q=1').port", r#""8080""#), ("require('util').format('%s=%d', 'a', 1)", r#""a=1""#), - ( - "require('assert').deepStrictEqual({ a: [1] }, { a: [1] })", - "undefined", - ), - ( - "require('punycode').toASCII('mañana.com')", - r#""xn--maana-pta.com""#, - ), - ( - "new (require('string_decoder').StringDecoder)('utf8').write(Buffer.from('é'))", - r#""é""#, - ), + ("require('assert').deepStrictEqual({ a: [1] }, { a: [1] })", "undefined"), + ("require('punycode').toASCII('mañana.com')", r#""xn--maana-pta.com""#), + ("new (require('string_decoder').StringDecoder)('utf8').write(Buffer.from('é'))", r#""é""#), ( "[typeof require('stream').Readable, typeof require('timers').setTimeout]", r#"["function","function"]"#, ), - ( - "[require('atob')('YQ=='), require('btoa')('a')]", - r#"["a","YQ=="]"#, - ), + ("[require('atob')('YQ=='), require('btoa')('a')]", r#"["a","YQ=="]"#), ], ); } @@ -1734,9 +1487,7 @@ mod tests { format!("require('{library}') === {global}"), format!("{global} === require('{library}')"), ] { - let outcome = run(&before(&format!( - "if (!({same})) throw new Error('not the same');" - ))); + let outcome = run(&before(&format!("if (!({same})) throw new Error('not the same');"))); assert_eq!(outcome.failure, None, "{same}"); } } @@ -1810,13 +1561,7 @@ mod tests { ); assert_eq!(outcome.failure, None); assert_eq!(outcome.writes[0].value.as_deref(), Some("undefined")); - assert!( - outcome.writes[1] - .value - .as_deref() - .unwrap() - .contains("not available here") - ); + assert!(outcome.writes[1].value.as_deref().unwrap().contains("not available here")); assert!(seen.borrow().logs[0].text.contains("not supported")); }); } @@ -1835,12 +1580,7 @@ mod tests { ), SECONDS, ); - let said: Vec<_> = seen - .borrow() - .logs - .iter() - .map(|log| (log.level, log.text.clone())) - .collect(); + let said: Vec<_> = seen.borrow().logs.iter().map(|log| (log.level, log.text.clone())).collect(); let expected = [ (LogLevel::Log, "signé {\"a\":1} 2"), (LogLevel::Error, "TypeError: x"), @@ -1852,10 +1592,7 @@ mod tests { (LogLevel::Log, "{\"a\":1}"), (LogLevel::Error, "Assertion failed not held"), ]; - assert_eq!( - said, - expected.map(|(level, text)| (level, text.to_string())) - ); + assert_eq!(said, expected.map(|(level, text)| (level, text.to_string()))); assert!( seen.borrow() .logs @@ -1887,11 +1624,7 @@ mod tests { SECONDS, ); assert_eq!(outcome.failure, None); - let values: Vec<_> = outcome - .writes - .iter() - .map(|write| write.value.as_deref()) - .collect(); + let values: Vec<_> = outcome.writes.iter().map(|write| write.value.as_deref()).collect(); assert_eq!(values, [Some("https://example.com/a"), Some("200")]); let calls = &seen.borrow().calls; assert_eq!( @@ -1911,15 +1644,8 @@ mod tests { pm.sendRequest(asked, (error, response) => env.set('callback', error.code + ' ' + response)); try { await pm.sendRequest(asked); } catch (error) { env.set('promise', error.message); }", )); - let values: Vec<_> = outcome - .writes - .iter() - .map(|write| write.value.as_deref()) - .collect(); - assert_eq!( - values, - [Some("httpScriptProtected undefined"), Some("refused")] - ); + let values: Vec<_> = outcome.writes.iter().map(|write| write.value.as_deref()).collect(); + assert_eq!(values, [Some("httpScriptProtected undefined"), Some("refused")]); }); } @@ -1941,17 +1667,8 @@ mod tests { ); let calls = &seen.borrow().calls; let kinds: Vec<_> = calls.iter().map(|(kind, _)| kind.as_str()).collect(); - assert_eq!( - kinds, - [ - "jarGet", "jarAll", "jarSet", "jarSet", "jarUnset", "jarClear" - ] - ); - assert!( - calls - .iter() - .all(|(_, payload)| payload["url"] == "https://a.test") - ); + assert_eq!(kinds, ["jarGet", "jarAll", "jarSet", "jarSet", "jarUnset", "jarClear"]); + assert!(calls.iter().all(|(_, payload)| payload["url"] == "https://a.test")); assert_eq!(calls[2].1["cookie"], json!({ "name": "two", "value": "2" })); assert_eq!( calls[3].1["cookie"], @@ -1967,11 +1684,7 @@ mod tests { assert!(run(&before("pm.execution.skipRequest();")).skip); assert!(!run(&before("")).skip); let failure = run(&after("pm.execution.skipRequest();")).failure.unwrap(); - assert!( - failure.message.contains("only before the request is sent"), - "{}", - failure.message - ); + assert!(failure.message.contains("only before the request is sent"), "{}", failure.message); }); } @@ -1983,10 +1696,7 @@ mod tests { (next.set, next.name) }; assert_eq!(next(""), (false, None)); - assert_eq!( - next("pm.execution.setNextRequest('Reçu');"), - (true, Some("Reçu".to_string())) - ); + assert_eq!(next("pm.execution.setNextRequest('Reçu');"), (true, Some("Reçu".to_string()))); assert_eq!(next("pm.execution.setNextRequest(null);"), (true, None)); }); } @@ -1999,10 +1709,7 @@ mod tests { engine.run(&before("env.set('a', 1); test('t', () => {}); pm.execution.skipRequest(); pm.execution.setNextRequest('x');"), SECONDS); let outcome = engine.run(&before(""), SECONDS); assert!( - outcome.writes.is_empty() - && outcome.tests.is_empty() - && !outcome.skip - && !outcome.next.set + outcome.writes.is_empty() && outcome.tests.is_empty() && !outcome.skip && !outcome.next.set ); }); } diff --git a/crates/engine/src/http/scripts/libraries.rs b/crates/engine/src/http/scripts/libraries.rs index 3ee862c1d..9db2a9fac 100644 --- a/crates/engine/src/http/scripts/libraries.rs +++ b/crates/engine/src/http/scripts/libraries.rs @@ -37,10 +37,7 @@ bundled! { /// The module's source, `None` for a name nothing provides. pub(crate) fn source(name: &str) -> Option<&'static str> { - LIBRARIES - .iter() - .find(|(known, _)| *known == name) - .map(|(_, source)| *source) + LIBRARIES.iter().find(|(known, _)| *known == name).map(|(_, source)| *source) } #[cfg(test)] @@ -63,11 +60,7 @@ mod tests { .unwrap(); assert_eq!(manifest.len(), LIBRARIES.len()); for module in manifest { - assert!( - source(&module.name).is_some(), - "{} is not compiled in", - module.name - ); + assert!(source(&module.name).is_some(), "{} is not compiled in", module.name); } } } diff --git a/crates/engine/src/http/scripts/model.rs b/crates/engine/src/http/scripts/model.rs index d3f415ffa..5632991bf 100644 --- a/crates/engine/src/http/scripts/model.rs +++ b/crates/engine/src/http/scripts/model.rs @@ -6,9 +6,7 @@ use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; use crate::closed_enum::closed_enum; -use crate::http::model::{ - FormPart, HttpMethod, KeyValue, RequestBody, RequestDocument, RequestKind, -}; +use crate::http::model::{FormPart, HttpMethod, KeyValue, RequestBody, RequestDocument, RequestKind}; use crate::http::response::Cookie; closed_enum! { @@ -110,18 +108,11 @@ pub enum RequestFault { } fn row(key: &str, value: &str, enabled: bool) -> ScriptRow { - ScriptRow { - key: key.to_string(), - value: value.to_string(), - disabled: !enabled, - part: None, - } + ScriptRow { key: key.to_string(), value: value.to_string(), disabled: !enabled, part: None } } fn rows_of(rows: &[KeyValue]) -> Vec { - rows.iter() - .map(|kv| row(&kv.key, &kv.value, kv.enabled)) - .collect() + rows.iter().map(|kv| row(&kv.key, &kv.value, kv.enabled)).collect() } /// The script's rows back as the request's, each keeping the description of the row of its name. @@ -142,11 +133,7 @@ fn key_values(rows: &[ScriptRow], before: &[KeyValue]) -> Vec { impl ScriptBody { fn of(kind: RequestKind, document: &RequestDocument) -> Self { - let mut body = Self { - mode: "none".to_string(), - language: "text".to_string(), - ..Self::default() - }; + let mut body = Self { mode: "none".to_string(), language: "text".to_string(), ..Self::default() }; if kind == RequestKind::Graphql { body.mode = "graphql".to_string(); body.graphql = ScriptGraphql { @@ -192,20 +179,16 @@ impl ScriptBody { fn onto(&self, before: &RequestBody) -> RequestBody { match self.mode.as_str() { "none" => RequestBody::None, - "raw" if self.language.eq_ignore_ascii_case("json") => RequestBody::Json { - text: self.raw.clone(), - }, - "raw" => RequestBody::Text { - text: self.raw.clone(), - }, + "raw" if self.language.eq_ignore_ascii_case("json") => { + RequestBody::Json { text: self.raw.clone() } + } + "raw" => RequestBody::Text { text: self.raw.clone() }, "urlencoded" => { let fields = match before { RequestBody::Form { fields } => fields.as_slice(), _ => &[], }; - RequestBody::Form { - fields: key_values(&self.urlencoded, fields), - } + RequestBody::Form { fields: key_values(&self.urlencoded, fields) } } "formdata" => RequestBody::Multipart { parts: self @@ -220,9 +203,7 @@ impl ScriptBody { }) .collect(), }, - "file" => RequestBody::Binary { - path: self.file.src.clone(), - }, + "file" => RequestBody::Binary { path: self.file.src.clone() }, _ => before.clone(), } } @@ -257,10 +238,7 @@ impl ScriptRequest { if kind == RequestKind::Graphql { if self.body.mode == "graphql" { document.graphql.query.clone_from(&self.body.graphql.query); - document - .graphql - .variables - .clone_from(&self.body.graphql.variables); + document.graphql.variables.clone_from(&self.body.graphql.variables); } } else { document.body = self.body.onto(&document.body); @@ -271,10 +249,7 @@ impl ScriptRequest { /// A request a script sends by itself, its body by Postman's modes. #[must_use] pub fn document(&self) -> RequestDocument { - let mut document = RequestDocument { - url: self.url.clone(), - ..RequestDocument::default() - }; + let mut document = RequestDocument { url: self.url.clone(), ..RequestDocument::default() }; document.headers = key_values(&self.headers, &[]); document.body = self.body.onto(&RequestBody::None); document @@ -424,11 +399,7 @@ impl TestResult { }; let code = self.line.and_then(|line| { let index = usize::try_from(line).ok()?.checked_sub(1)?; - script - .source - .lines() - .nth(index) - .map(|code| code.trim().to_string()) + script.source.lines().nth(index).map(|code| code.trim().to_string()) }); Self { kind: Some(script.kind), @@ -491,10 +462,7 @@ pub struct Outcome { impl Outcome { #[must_use] pub fn failed(failure: ScriptFailure) -> Self { - Self { - failure: Some(failure), - ..Self::default() - } + Self { failure: Some(failure), ..Self::default() } } } @@ -588,10 +556,7 @@ pub enum ScriptError { #[error("A script set the method {0}, which no request is sent with")] Method(String), #[error("The scripts made the request a {method} on {environment}, which is protected")] - Protected { - method: HttpMethod, - environment: String, - }, + Protected { method: HttpMethod, environment: String }, } #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -645,10 +610,7 @@ mod tests { ("test('a', () => {});", 1), ("pm.test('a', f);\ntest ('b', f);", 2), ("test.skip('c');", 0), - ( - "const latest = 1; env.test('x'); attest(1); _test(1); my9test(1);", - 0, - ), + ("const latest = 1; env.test('x'); attest(1); _test(1); my9test(1);", 0), ("test", 0), ] { assert_eq!(tests_declared(source), count, "{source}"); @@ -691,14 +653,8 @@ mod tests { fn a_stop_read_from_an_error_that_says_little_says_as_little() { let stop = ScriptStop::of_params(¶ms(&[("failure", "unheard of"), ("line", "many")])); - assert_eq!( - (stop.kind, stop.level, stop.line), - (FailureKind::Error, None, None) - ); - assert_eq!( - (stop.name, stop.owner, stop.message.as_str()), - (None, None, "") - ); + assert_eq!((stop.kind, stop.level, stop.line), (FailureKind::Error, None, None)); + assert_eq!((stop.name, stop.owner, stop.message.as_str()), (None, None, "")); } fn script(id: &str, name: &str) -> Script { @@ -723,33 +679,19 @@ mod tests { #[test] fn a_stop_names_the_script_its_failure_names() { - let stop = ScriptStop::of( - &failure(Some("s2")), - &[script("s1", "First"), script("s2", "Second")], - ); + let stop = ScriptStop::of(&failure(Some("s2")), &[script("s1", "First"), script("s2", "Second")]); - assert_eq!( - (stop.kind, stop.line, stop.message.as_str()), - (FailureKind::Memory, Some(2), "boom") - ); - assert_eq!( - (stop.level, stop.script), - (Some(ScriptLevel::Folder), Some(ScriptKind::Tests)) - ); - assert_eq!( - (stop.name.as_deref(), stop.owner.as_deref()), - (Some("Second"), Some("f1")) - ); + assert_eq!((stop.kind, stop.line, stop.message.as_str()), (FailureKind::Memory, Some(2), "boom")); + assert_eq!((stop.level, stop.script), (Some(ScriptLevel::Folder), Some(ScriptKind::Tests))); + assert_eq!((stop.name.as_deref(), stop.owner.as_deref()), (Some("Second"), Some("f1"))); } /// A timeout names no script: with one alone to blame it is that one, with several none. #[test] fn a_stop_of_no_named_script_is_the_only_one_there_is() { let one = ScriptStop::of(&failure(None), &[script("s1", "First")]); - let several = ScriptStop::of( - &failure(Some("gone")), - &[script("s1", "First"), script("s2", "Second")], - ); + let several = + ScriptStop::of(&failure(Some("gone")), &[script("s1", "First"), script("s2", "Second")]); assert_eq!(one.name.as_deref(), Some("First")); assert_eq!((several.name, several.level), (None, None)); @@ -757,22 +699,12 @@ mod tests { #[test] fn a_test_is_placed_in_the_script_that_wrote_it_with_its_line_of_code() { - let test = TestResult { - script: Some("s1".to_string()), - line: Some(2), - ..TestResult::default() - }; + let test = TestResult { script: Some("s1".to_string()), line: Some(2), ..TestResult::default() }; let placed = test.placed(&[script("s0", "Other"), script("s1", "Auth")]); - assert_eq!( - (placed.kind, placed.level), - (Some(ScriptKind::Tests), Some(ScriptLevel::Folder)) - ); - assert_eq!( - (placed.holder.as_deref(), placed.owner.as_deref()), - (Some("Auth"), Some("f1")) - ); + assert_eq!((placed.kind, placed.level), (Some(ScriptKind::Tests), Some(ScriptLevel::Folder))); + assert_eq!((placed.holder.as_deref(), placed.owner.as_deref()), (Some("Auth"), Some("f1"))); assert_eq!(placed.code.as_deref(), Some("expect(a).toBe(2);")); } @@ -787,17 +719,10 @@ mod tests { for line in [None, Some(0), Some(9)] { let placed = on("s1", line).placed(&scripts); - assert_eq!( - (placed.holder.as_deref(), placed.code), - (Some("Auth"), None), - "{line:?}" - ); + assert_eq!((placed.holder.as_deref(), placed.code), (Some("Auth"), None), "{line:?}"); } assert_eq!(on("gone", Some(2)).placed(&scripts), on("gone", Some(2))); - assert_eq!( - TestResult::default().placed(&scripts), - TestResult::default() - ); + assert_eq!(TestResult::default().placed(&scripts), TestResult::default()); } fn header(key: &str, value: &str) -> KeyValue { @@ -815,10 +740,8 @@ mod tests { #[test] fn what_a_script_changed_is_what_the_request_sends() { - let mut document = RequestDocument { - url: "{{baseUrl}}/pay".to_string(), - ..RequestDocument::default() - }; + let mut document = + RequestDocument { url: "{{baseUrl}}/pay".to_string(), ..RequestDocument::default() }; let mut request = handed(&document); request.method = " put ".to_string(); request.url.push_str("?retry=1"); @@ -827,10 +750,7 @@ mod tests { let method = request.onto(RequestKind::Http, &mut document).unwrap(); - assert_eq!( - (method, document.url.as_str()), - (HttpMethod::Put, "{{baseUrl}}/pay?retry=1") - ); + assert_eq!((method, document.url.as_str()), (HttpMethod::Put, "{{baseUrl}}/pay?retry=1")); let sent: Vec<_> = document .headers .iter() @@ -844,9 +764,7 @@ mod tests { fn a_row_a_script_hands_back_keeps_its_description() { let mut document = RequestDocument { headers: vec![header("Accept", "application/json")], - body: RequestBody::Form { - fields: vec![header("q", "1")], - }, + body: RequestBody::Form { fields: vec![header("q", "1")] }, ..RequestDocument::default() }; let mut request = handed(&document); @@ -856,25 +774,18 @@ mod tests { request.onto(RequestKind::Http, &mut document).unwrap(); assert_eq!( - ( - document.headers[0].value.as_str(), - document.headers[0].description.as_str() - ), + (document.headers[0].value.as_str(), document.headers[0].description.as_str()), ("text/csv", "about Accept") ); - let RequestBody::Form { fields } = &document.body else { - panic!("no form") - }; + let RequestBody::Form { fields } = &document.body else { panic!("no form") }; let described: Vec<_> = fields.iter().map(|row| row.description.as_str()).collect(); assert_eq!(described, ["about q", ""]); } #[test] fn a_method_rust_does_not_send_is_refused_by_its_name_and_changes_nothing() { - let mut document = RequestDocument { - url: "https://shop.test".to_string(), - ..RequestDocument::default() - }; + let mut document = + RequestDocument { url: "https://shop.test".to_string(), ..RequestDocument::default() }; let mut request = handed(&document); request.method = "PURGE".to_string(); request.url = "https://other.test".to_string(); @@ -897,45 +808,19 @@ mod tests { }; for (body, mode, language) in [ (RequestBody::None, "none", "text"), - ( - RequestBody::Text { - text: text("hello"), - }, - "raw", - "text", - ), + (RequestBody::Text { text: text("hello") }, "raw", "text"), (RequestBody::Json { text: text("{}") }, "raw", "json"), + (RequestBody::Form { fields: vec![header("q", "1")] }, "urlencoded", "text"), ( - RequestBody::Form { - fields: vec![header("q", "1")], - }, - "urlencoded", - "text", - ), - ( - RequestBody::Multipart { - parts: vec![part("file", true), part("text", false)], - }, + RequestBody::Multipart { parts: vec![part("file", true), part("text", false)] }, "formdata", "text", ), - ( - RequestBody::Binary { - path: text("/tmp/a.bin"), - }, - "file", - "text", - ), + (RequestBody::Binary { path: text("/tmp/a.bin") }, "file", "text"), ] { - let mut document = RequestDocument { - body: body.clone(), - ..RequestDocument::default() - }; + let mut document = RequestDocument { body: body.clone(), ..RequestDocument::default() }; let request = handed(&document); - assert_eq!( - (request.body.mode.as_str(), request.body.language.as_str()), - (mode, language) - ); + assert_eq!((request.body.mode.as_str(), request.body.language.as_str()), (mode, language)); request.onto(RequestKind::Http, &mut document).unwrap(); @@ -946,9 +831,7 @@ mod tests { #[test] fn a_body_of_a_mode_rust_has_no_kind_for_stays_the_one_it_was() { let mut document = RequestDocument { - body: RequestBody::Text { - text: "kept".to_string(), - }, + body: RequestBody::Text { text: "kept".to_string() }, ..RequestDocument::default() }; let mut request = handed(&document); @@ -956,12 +839,7 @@ mod tests { request.onto(RequestKind::Http, &mut document).unwrap(); - assert_eq!( - document.body, - RequestBody::Text { - text: "kept".to_string() - } - ); + assert_eq!(document.body, RequestBody::Text { text: "kept".to_string() }); } fn graphql() -> RequestDocument { @@ -981,20 +859,14 @@ mod tests { let mut request = ScriptRequest::of(RequestKind::Graphql, HttpMethod::Post, &document); assert_eq!(request.body.mode, "graphql"); let handed = &request.body.graphql; - assert_eq!( - (handed.query.as_str(), handed.variables.as_str()), - ("{ me { id } }", "{}") - ); + assert_eq!((handed.query.as_str(), handed.variables.as_str()), ("{ me { id } }", "{}")); request.body.graphql.query = "{ me { name } }".to_string(); request.body.graphql.variables = "{\"a\":1}".to_string(); request.onto(RequestKind::Graphql, &mut document).unwrap(); assert_eq!( - ( - document.graphql.query.as_str(), - document.graphql.variables.as_str() - ), + (document.graphql.query.as_str(), document.graphql.variables.as_str()), ("{ me { name } }", "{\"a\":1}") ); } @@ -1029,19 +901,8 @@ mod tests { let document = request.document(); assert_eq!(document.url, "https://auth.test/login"); - assert_eq!( - ( - document.headers[0].key.as_str(), - document.headers[0].value.as_str() - ), - ("X-Trace", "1") - ); - assert_eq!( - document.body, - RequestBody::Json { - text: "{}".to_string() - } - ); + assert_eq!((document.headers[0].key.as_str(), document.headers[0].value.as_str()), ("X-Trace", "1")); + assert_eq!(document.body, RequestBody::Json { text: "{}".to_string() }); } #[test] @@ -1063,9 +924,6 @@ mod tests { (read.name, read.value, read.domain, read.path), (cookie.name, cookie.value, cookie.domain, cookie.path) ); - assert_eq!( - (read.expires, read.http_only, read.secure), - (cookie.expires, true, true) - ); + assert_eq!((read.expires, read.http_only, read.secure), (cookie.expires, true, true)); } } diff --git a/crates/engine/src/http/scripts/network.rs b/crates/engine/src/http/scripts/network.rs index 4236cd897..93293c57c 100644 --- a/crates/engine/src/http/scripts/network.rs +++ b/crates/engine/src/http/scripts/network.rs @@ -81,20 +81,12 @@ impl Network { } let Asked { request, script } = serde_json::from_str(payload).map_err(|error| Refusal::new(error.to_string(), None))?; - let method = request - .method - .trim() - .to_ascii_uppercase() - .parse::() - .map_err(|()| { - Refusal::new( - format!( - "The method {} is not one a request is sent with", - request.method - ), - Some("httpScriptMethod"), - ) - })?; + let method = request.method.trim().to_ascii_uppercase().parse::().map_err(|()| { + Refusal::new( + format!("The method {} is not one a request is sent with", request.method), + Some("httpScriptMethod"), + ) + })?; if !self.may_change && !method.changes_nothing() { return Err(Refusal::new( format!( @@ -116,13 +108,8 @@ impl Network { Some(FILE), )); } - let mut outgoing = send::compose( - RequestKind::Http, - method, - &document, - &settings::inherit(&[]), - ) - .map_err(|error| Refusal::new(error.to_string(), Some("httpScriptSend")))?; + let mut outgoing = send::compose(RequestKind::Http, method, &document, &settings::inherit(&[])) + .map_err(|error| Refusal::new(error.to_string(), Some("httpScriptSend")))?; outgoing.transport = self.transport; outgoing.jar = self.jar.clone().filter(|_| self.transport.use_cookies); let exchange = send::exchange(&outgoing); @@ -132,17 +119,10 @@ impl Network { cookies::apply(jar, &changes); } self.changes.extend(changes); - self.sent.push(ScriptSend { - script, - exchange, - started, - ended: Utc::now(), - answer: answer.clone(), - }); - let response = - answer.map_err(|error| Refusal::new(error.to_string(), Some("httpScriptSend")))?; - serde_json::to_value(response_of(&response)) - .map_err(|error| Refusal::new(error.to_string(), None)) + self.sent + .push(ScriptSend { script, exchange, started, ended: Utc::now(), answer: answer.clone() }); + let response = answer.map_err(|error| Refusal::new(error.to_string(), Some("httpScriptSend")))?; + serde_json::to_value(response_of(&response)).map_err(|error| Refusal::new(error.to_string(), None)) } fn jar(&mut self, kind: &str, payload: &str) -> Result { @@ -156,8 +136,8 @@ impl Network { } let asked: Asked = serde_json::from_str(payload).map_err(|error| Refusal::new(error.to_string(), None))?; - let url = Url::parse(&asked.url) - .map_err(|_| Refusal::new(format!("{} is not a URL", asked.url), None))?; + let url = + Url::parse(&asked.url).map_err(|_| Refusal::new(format!("{} is not a URL", asked.url), None))?; let Some(jar) = self.jar.as_mut() else { return Err(Refusal::new( "This request sends no cookie: its jar is switched off", @@ -174,21 +154,15 @@ impl Network { }; let changes: Vec = match kind { "jarGet" => { - let value = found(Some(&asked.name)) - .first() - .map(|cookie| cookie.value.clone()); + let value = found(Some(&asked.name)).first().map(|cookie| cookie.value.clone()); return Ok(serde_json::json!(value)); } "jarAll" => { let all: Vec = found(None).iter().map(cookie_of).collect(); - return serde_json::to_value(all) - .map_err(|error| Refusal::new(error.to_string(), None)); + return serde_json::to_value(all).map_err(|error| Refusal::new(error.to_string(), None)); } "jarSet" => cookies::received(&[set_cookie(&asked.cookie)], &url, now), - "jarUnset" => found(Some(&asked.name)) - .into_iter() - .map(Change::Remove) - .collect(), + "jarUnset" => found(Some(&asked.name)).into_iter().map(Change::Remove).collect(), "jarClear" => found(None).into_iter().map(Change::Remove).collect(), _ => return Err(Refusal::new(format!("Nothing answers {kind}"), None)), }; @@ -201,11 +175,9 @@ impl Network { /// A cookie a script sets, as the line a server would have written for it. fn set_cookie(cookie: &ScriptCookie) -> KeyValue { let mut line = format!("{}={}", cookie.name, cookie.value); - for (attribute, value) in [ - ("Path", &cookie.path), - ("Domain", &cookie.domain), - ("Expires", &cookie.expires), - ] { + for (attribute, value) in + [("Path", &cookie.path), ("Domain", &cookie.domain), ("Expires", &cookie.expires)] + { if let Some(value) = value { let _ = write!(line, "; {attribute}={value}"); } @@ -216,11 +188,7 @@ fn set_cookie(cookie: &ScriptCookie) -> KeyValue { if cookie.http_only { line.push_str("; HttpOnly"); } - KeyValue { - key: "Set-Cookie".to_string(), - value: line, - ..KeyValue::default() - } + KeyValue { key: "Set-Cookie".to_string(), value: line, ..KeyValue::default() } } fn cookie_of(cookie: &JarCookie) -> ScriptCookie { @@ -241,10 +209,7 @@ pub fn cookies_for(jar: Option<&[JarCookie]>, url: &str) -> Vec { let (Some(jar), Ok(url)) = (jar, Url::parse(url)) else { return Vec::new(); }; - cookies::matching(jar, &url, Utc::now()) - .into_iter() - .map(cookie_of) - .collect() + cookies::matching(jar, &url, Utc::now()).into_iter().map(cookie_of).collect() } /// An answer as a script reads it. @@ -279,9 +244,6 @@ impl Services for Network { } fn log(&mut self, entry: LogEntry) { - self.logs.push(LogEntry { - at: Some(Utc::now()), - ..entry - }); + self.logs.push(LogEntry { at: Some(Utc::now()), ..entry }); } } diff --git a/crates/engine/src/http/scripts/process.rs b/crates/engine/src/http/scripts/process.rs index a9451df91..ddc9f2348 100644 --- a/crates/engine/src/http/scripts/process.rs +++ b/crates/engine/src/http/scripts/process.rs @@ -41,10 +41,7 @@ pub struct Refusal { impl Refusal { #[must_use] pub fn new(message: impl Into, code: Option<&str>) -> Self { - Self { - message: message.into(), - code: code.map(str::to_string), - } + Self { message: message.into(), code: code.map(str::to_string) } } } @@ -122,20 +119,12 @@ impl ScriptProcess { let missing = || std::io::Error::other("the script host has no standard streams"); let input = child.stdin.take().ok_or_else(missing)?; let output = BufReader::new(child.stdout.take().ok_or_else(missing)?); - Ok(Self { - child: Arc::new(Mutex::new(child)), - input: Some(input), - output, - killed: Arc::default(), - }) + Ok(Self { child: Arc::new(Mutex::new(child)), input: Some(input), output, killed: Arc::default() }) } #[must_use] pub fn killer(&self) -> Killer { - Killer { - child: Arc::clone(&self.child), - killed: Arc::clone(&self.killed), - } + Killer { child: Arc::clone(&self.child), killed: Arc::clone(&self.killed) } } /// One phase, within `time`, its calls answered by `services`. @@ -169,15 +158,8 @@ impl ScriptProcess { serde_json::json!({ "error": refusal.message, "code": refusal.code }) } }; - let reply = child::ToHost::Reply { - id, - answer: answer.to_string(), - }; - if self - .input - .as_mut() - .is_none_or(|input| write_line(input, &reply).is_err()) - { + let reply = child::ToHost::Reply { id, answer: answer.to_string() }; + if self.input.as_mut().is_none_or(|input| write_line(input, &reply).is_err()) { break host_failure("The script host cannot be reached"); } } diff --git a/crates/engine/src/http/scripts/session.rs b/crates/engine/src/http/scripts/session.rs index c8a97e886..d356066a7 100644 --- a/crates/engine/src/http/scripts/session.rs +++ b/crates/engine/src/http/scripts/session.rs @@ -15,11 +15,7 @@ pub struct Session { impl Session { #[must_use] pub fn new(host: ScriptProcess, network: Network) -> Self { - Self { - host, - network, - logs: Vec::new(), - } + Self { host, network, logs: Vec::new() } } #[must_use] diff --git a/crates/engine/src/http/search.rs b/crates/engine/src/http/search.rs index 0fc1c8d39..3f494948c 100644 --- a/crates/engine/src/http/search.rs +++ b/crates/engine/src/http/search.rs @@ -56,24 +56,12 @@ pub fn rank(candidates: Vec, search: &str) -> Vec { let mut scored: Vec<(u8, DateTime, RequestHit)> = candidates .into_iter() .filter_map(|candidate| { - let score = if needle.is_empty() { - Some(0) - } else { - score(&candidate.hit, &needle) - }; + let score = if needle.is_empty() { Some(0) } else { score(&candidate.hit, &needle) }; score.map(|score| (score, candidate.updated_at, candidate.hit)) }) .collect(); - scored.sort_by(|a, b| { - a.0.cmp(&b.0) - .then(b.1.cmp(&a.1)) - .then_with(|| a.2.name.cmp(&b.2.name)) - }); - scored - .into_iter() - .take(MAX_HITS) - .map(|(_, _, hit)| hit) - .collect() + scored.sort_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1)).then_with(|| a.2.name.cmp(&b.2.name))); + scored.into_iter().take(MAX_HITS).map(|(_, _, hit)| hit).collect() } #[cfg(test)] @@ -81,8 +69,7 @@ mod tests { use super::*; fn at(hours: i64) -> DateTime { - crate::db::iso8601::parse("2026-07-25T09:00:00.000Z").unwrap() - + chrono::TimeDelta::hours(hours) + crate::db::iso8601::parse("2026-07-25T09:00:00.000Z").unwrap() + chrono::TimeDelta::hours(hours) } fn candidate(name: &str, url: &str, place: &[&str], edited: i64) -> Candidate { @@ -118,16 +105,7 @@ mod tests { let hits = rank(candidates, " ÓRDER "); - assert_eq!( - names(&hits), - [ - "Ordered items", - "Shop orders", - "Reorder", - "List all", - "Health" - ] - ); + assert_eq!(names(&hits), ["Ordered items", "Shop orders", "Reorder", "List all", "Health"]); } /// A tie goes to the one edited last, then to its name. diff --git a/crates/engine/src/http/send.rs b/crates/engine/src/http/send.rs index 2bc864d0f..88ac9161f 100644 --- a/crates/engine/src/http/send.rs +++ b/crates/engine/src/http/send.rs @@ -17,8 +17,8 @@ use url::Url; use super::cookies::{self, Change, JarCookie}; use super::graphql::{self, GraphqlDocument, GraphqlResult}; use super::model::{ - HeaderFault, HttpMethod, KeyPlace, KeyValue, RequestAuth, RequestBody, RequestDocument, - RequestKind, header_fault, + HeaderFault, HttpMethod, KeyPlace, KeyValue, RequestAuth, RequestBody, RequestDocument, RequestKind, + header_fault, }; use super::response::{self, Cookie}; use super::scripts::model::ScriptsAnswer; @@ -126,11 +126,7 @@ pub struct Exchange { } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde( - tag = "kind", - rename_all = "camelCase", - rename_all_fields = "camelCase" -)] +#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")] pub enum SentBody { None, /// Up to `SHOWN_LIMIT`. @@ -188,11 +184,7 @@ pub enum SendError { SocketScheme { twin: Option }, /// A header that cannot be built: named, with who wrote it, rather than blamed on the URL. #[error("The header {name} cannot be sent: its {fault:?} is not valid")] - Header { - name: String, - fault: HeaderFault, - set_by: SetBy, - }, + Header { name: String, fault: HeaderFault, set_by: SetBy }, } /// Who put a header on a request that no row of its own wrote. @@ -254,17 +246,11 @@ pub struct Outgoing { impl Outgoing { pub fn timeout(&self) -> Limit { - Limit { - value: self.transport.timeout_ms, - set_by: self.limits.timeout.clone(), - } + Limit { value: self.transport.timeout_ms, set_by: self.limits.timeout.clone() } } pub fn redirects(&self) -> Limit { - Limit { - value: self.transport.max_redirects, - set_by: self.limits.redirects.clone(), - } + Limit { value: self.transport.max_redirects, set_by: self.limits.redirects.clone() } } } @@ -283,8 +269,7 @@ pub enum Part { } fn sent(rows: &[KeyValue]) -> impl Iterator { - rows.iter() - .filter(|row| row.enabled && !row.key.trim().is_empty()) + rows.iter().filter(|row| row.enabled && !row.key.trim().is_empty()) } /// Its size is checked before it is read, and the read stops past it: the file may grow. @@ -296,9 +281,7 @@ fn read(path: &str) -> Result, SendError> { return Err(SendError::FileTooLarge(path.to_string())); } let mut bytes = Vec::new(); - file.take(limit + 1) - .read_to_end(&mut bytes) - .map_err(unreadable)?; + file.take(limit + 1).read_to_end(&mut bytes).map_err(unreadable)?; if bytes.len() as u64 > limit { return Err(SendError::FileTooLarge(path.to_string())); } @@ -306,11 +289,7 @@ fn read(path: &str) -> Result, SendError> { } /// The first `{{variable}}` left in what will be sent, in reading order: one no level sets. -fn first_variable( - kind: RequestKind, - document: &RequestDocument, - inherited: &Inherited, -) -> Option { +fn first_variable(kind: RequestKind, document: &RequestDocument, inherited: &Inherited) -> Option { variables::texts(kind, document, inherited) .into_iter() .find_map(|text| variables::names_in(text).into_iter().next()) @@ -319,19 +298,12 @@ fn first_variable( /// `api.example.com/users` is sent as `http://api.example.com/users`, as a browser would. fn parse_url(typed: &str) -> Result { let typed = typed.trim(); - let url = if typed.contains("://") { - Url::parse(typed) - } else { - Url::parse(&format!("http://{typed}")) - }; + let url = if typed.contains("://") { Url::parse(typed) } else { Url::parse(&format!("http://{typed}")) }; let url = url.map_err(|error| SendError::InvalidUrl(error.to_string()))?; // ⚠️ Why, never the URL itself: a detail is shown and logged, and a URL carries a key in // its query or a password before its host. if !matches!(url.scheme(), "http" | "https") { - return Err(SendError::InvalidUrl(format!( - "the scheme {}", - url.scheme() - ))); + return Err(SendError::InvalidUrl(format!("the scheme {}", url.scheme()))); } if url.host_str().is_none_or(str::is_empty) { return Err(SendError::InvalidUrl("no host".to_string())); @@ -350,61 +322,35 @@ fn content_type(kind: RequestKind, document: &RequestDocument) -> Option<&'stati /// Every header of a request and who wrote it: the inherited ones, its own over them by name, /// then, each only where no row sets it, the auth's, the body's type and the application's own. -fn written( - document: &RequestDocument, - inherited: &Inherited, - content_type: Option<&str>, -) -> Vec { +fn written(document: &RequestDocument, inherited: &Inherited, content_type: Option<&str>) -> Vec { let mut headers: Vec = Vec::new(); let mut set = |name: &str, value: &str, by: Wrote| { headers.retain(|known| !known.name.eq_ignore_ascii_case(name)); - headers.push(Written { - name: name.to_string(), - value: value.to_string(), - by, - }); + headers.push(Written { name: name.to_string(), value: value.to_string(), by }); }; for known in &inherited.headers { - set( - known.header.key.trim(), - &known.header.value, - Wrote::Above(known.from.clone()), - ); + set(known.header.key.trim(), &known.header.value, Wrote::Above(known.from.clone())); } for row in sent(&document.headers) { set(row.key.trim(), &row.value, Wrote::Request); } let mut unless_set = |name: &str, value: String, by: Wrote| { - if !headers - .iter() - .any(|known| known.name.eq_ignore_ascii_case(name)) - { - headers.push(Written { - name: name.to_string(), - value, - by, - }); + if !headers.iter().any(|known| known.name.eq_ignore_ascii_case(name)) { + headers.push(Written { name: name.to_string(), value, by }); } }; match auth_of(document, inherited) { RequestAuth::Basic { username, password } => { - let pair = - base64::engine::general_purpose::STANDARD.encode(format!("{username}:{password}")); + let pair = base64::engine::general_purpose::STANDARD.encode(format!("{username}:{password}")); unless_set("Authorization", format!("Basic {pair}"), Wrote::Auth); } RequestAuth::Bearer { token } => { - unless_set( - "Authorization", - format!("Bearer {}", token.trim()), - Wrote::Auth, - ); + unless_set("Authorization", format!("Bearer {}", token.trim()), Wrote::Auth); + } + RequestAuth::ApiKey { name, value, place: KeyPlace::Header } if !name.trim().is_empty() => { + unless_set(name.trim(), value.clone(), Wrote::Auth); } - RequestAuth::ApiKey { - name, - value, - place: KeyPlace::Header, - } if !name.trim().is_empty() => unless_set(name.trim(), value.clone(), Wrote::Auth), _ => {} } if let Some(content_type) = content_type { @@ -428,8 +374,7 @@ pub fn written_for_code( inherited: &Inherited, ) -> Vec<(String, String)> { let basic = matches!(auth_of(document, inherited), RequestAuth::Basic { .. }); - let multipart = - kind == RequestKind::Http && matches!(document.body, RequestBody::Multipart { .. }); + let multipart = kind == RequestKind::Http && matches!(document.body, RequestBody::Multipart { .. }); written(document, inherited, content_type(kind, document)) .into_iter() .filter(|header| header.by != Wrote::Default) @@ -453,23 +398,14 @@ fn host_of(url: &Url) -> Option { if !variables::names_in(host).is_empty() { return None; } - Some( - url.port() - .map_or_else(|| host.to_string(), |port| format!("{host}:{port}")), - ) + Some(url.port().map_or_else(|| host.to_string(), |port| format!("{host}:{port}"))) } /// What a request sends without a row of its own, read from what `compose` writes: the two /// cannot disagree. Nothing is refused here: a URL that does not read yet has no `Host`. -pub fn implied( - kind: RequestKind, - document: &RequestDocument, - inherited: &Inherited, -) -> Vec { +pub fn implied(kind: RequestKind, document: &RequestDocument, inherited: &Inherited) -> Vec { let headers = written(document, inherited, content_type(kind, document)); - let typed_host = headers - .iter() - .any(|known| known.name.eq_ignore_ascii_case("host")); + let typed_host = headers.iter().any(|known| known.name.eq_ignore_ascii_case("host")); let mut listed: Vec = headers .into_iter() .filter_map(|header| { @@ -479,12 +415,7 @@ pub fn implied( Wrote::Body => (ImpliedSource::Body, None), Wrote::Default => (ImpliedSource::Default, None), }; - Some(ImpliedHeader { - name: header.name, - value: header.value, - source, - from, - }) + Some(ImpliedHeader { name: header.name, value: header.value, source, from }) }) .collect(); let url = match kind { @@ -523,11 +454,7 @@ pub fn compose( }; let auth = auth_of(document, inherited); - if let RequestAuth::ApiKey { - name, - value, - place: KeyPlace::Query, - } = auth + if let RequestAuth::ApiKey { name, value, place: KeyPlace::Query } = auth && !name.trim().is_empty() { url.query_pairs_mut().append_pair(name.trim(), value); @@ -538,8 +465,7 @@ pub fn compose( None => body_of(&document.body)?, }; // A multipart type carries its boundary, which reqwest alone knows. - let implied = - content_type(kind, document).filter(|_| !matches!(body, OutgoingBody::Multipart(_))); + let implied = content_type(kind, document).filter(|_| !matches!(body, OutgoingBody::Multipart(_))); let headers = written(document, inherited, implied); // ⚠️ Before the client builds it: its builder says « invalid URL » for a header it refuses. if let Some((header, fault)) = headers @@ -555,10 +481,7 @@ pub fn compose( }, }); } - let headers = headers - .into_iter() - .map(|header| (header.name, header.value)) - .collect(); + let headers = headers.into_iter().map(|header| (header.name, header.value)).collect(); let secrets = match auth { RequestAuth::ApiKey { name, .. } if !name.trim().is_empty() => { @@ -582,14 +505,8 @@ pub fn compose( jar: None, transport: inherited.transport.over(&document.transport), limits: Limits { - timeout: set_by( - document.transport.timeout_ms.is_some(), - &inherited.limits.timeout, - ), - redirects: set_by( - document.transport.max_redirects.is_some(), - &inherited.limits.redirects, - ), + timeout: set_by(document.transport.timeout_ms.is_some(), &inherited.limits.timeout), + redirects: set_by(document.transport.max_redirects.is_some(), &inherited.limits.redirects), }, }) } @@ -606,11 +523,7 @@ fn graphql_body(graphql: &GraphqlDocument, url: &mut Url) -> Result Result { } RequestBody::Multipart { parts } => { let mut fields = Vec::new(); - for part in parts - .iter() - .filter(|part| part.enabled && !part.key.trim().is_empty()) - { + for part in parts.iter().filter(|part| part.enabled && !part.key.trim().is_empty()) { let value = if part.file { Part::File { name: Path::new(&part.value) @@ -659,16 +569,9 @@ fn is_text(content_type: Option<&str>, bytes: &[u8]) -> bool { }; let essence = kind.split(';').next().unwrap_or_default().trim(); if essence.starts_with("text/") - || [ - "json", - "xml", - "javascript", - "x-www-form-urlencoded", - "graphql", - "yaml", - ] - .iter() - .any(|word| essence.contains(word)) + || ["json", "xml", "javascript", "x-www-form-urlencoded", "graphql", "yaml"] + .iter() + .any(|word| essence.contains(word)) { return true; } @@ -730,10 +633,7 @@ pub(crate) fn cause_of( } } let text = current.to_string().to_ascii_lowercase(); - if text.contains("dns error") - || text.contains("failed to lookup") - || text.contains("no such host") - { + if text.contains("dns error") || text.contains("failed to lookup") || text.contains("no such host") { return Some(SendError::Unresolved(current.to_string())); } if text.contains("certificate") || text.contains("invalid peer") { @@ -813,16 +713,12 @@ pub fn exchange(outgoing: &Outgoing) -> Exchange { let body = match &outgoing.body { OutgoingBody::None => SentBody::None, OutgoingBody::Bytes(bytes) => match std::str::from_utf8(bytes) { - Ok(text) => SentBody::Text { - text: hide(&text.chars().take(SHOWN_LIMIT).collect::()), - }, - Err(_) => SentBody::Bytes { - size: u32::try_from(bytes.len()).unwrap_or(u32::MAX), - }, - }, - OutgoingBody::Multipart(parts) => SentBody::Multipart { - fields: parts.iter().map(|(key, _)| key.clone()).collect(), + Ok(text) => SentBody::Text { text: hide(&text.chars().take(SHOWN_LIMIT).collect::()) }, + Err(_) => SentBody::Bytes { size: u32::try_from(bytes.len()).unwrap_or(u32::MAX) }, }, + OutgoingBody::Multipart(parts) => { + SentBody::Multipart { fields: parts.iter().map(|(key, _)| key.clone()).collect() } + } }; Exchange { method: outgoing.method, @@ -830,11 +726,7 @@ pub fn exchange(outgoing: &Outgoing) -> Exchange { headers: outgoing .headers .iter() - .map(|(key, value)| KeyValue { - key: key.clone(), - value: hide(value), - ..KeyValue::default() - }) + .map(|(key, value)| KeyValue { key: key.clone(), value: hide(value), ..KeyValue::default() }) .collect(), body, } @@ -850,20 +742,10 @@ struct Hop { } /// What a redirect to another host does not carry over, as a browser drops them. -const NOT_ACROSS_HOSTS: [&str; 5] = [ - "authorization", - "cookie", - "cookie2", - "proxy-authorization", - "www-authenticate", -]; +const NOT_ACROSS_HOSTS: [&str; 5] = + ["authorization", "cookie", "cookie2", "proxy-authorization", "www-authenticate"]; /// What describes a body a 301, 302 or 303 leaves behind. -const OF_THE_BODY: [&str; 4] = [ - "content-type", - "content-length", - "content-encoding", - "transfer-encoding", -]; +const OF_THE_BODY: [&str; 4] = ["content-type", "content-length", "content-encoding", "transfer-encoding"]; fn without(headers: &mut Vec<(String, String)>, names: &[&str]) { headers.retain(|(name, _)| !names.iter().any(|gone| name.eq_ignore_ascii_case(gone))); @@ -893,19 +775,13 @@ impl Hop { 307 | 308 => true, _ => return None, }; - let location = headers - .iter() - .find(|header| header.key.eq_ignore_ascii_case("location"))?; + let location = headers.iter().find(|header| header.key.eq_ignore_ascii_case("location"))?; let url = self.url.join(location.value.trim()).ok()?; if !matches!(url.scheme(), "http" | "https") { return None; } - let mut next = Self { - method: self.method.clone(), - url, - headers: self.headers.clone(), - body: self.body.clone(), - }; + let mut next = + Self { method: self.method.clone(), url, headers: self.headers.clone(), body: self.body.clone() }; if !keeps_body { next.body = OutgoingBody::None; without(&mut next.headers, &OF_THE_BODY); @@ -928,11 +804,7 @@ impl Hop { /// The jar's `Cookie` for this hop's URL, unless one is typed: what is typed wins, as for /// `Authorization`. fn cookie(&self, jar: Option<&[JarCookie]>) -> Option { - if self - .headers - .iter() - .any(|(name, _)| name.eq_ignore_ascii_case("cookie")) - { + if self.headers.iter().any(|(name, _)| name.eq_ignore_ascii_case("cookie")) { return None; } cookies::header_for(jar?, &self.url, Utc::now()) @@ -968,9 +840,7 @@ fn request(client: &reqwest::Client, hop: &Hop, cookie: Option<&str>) -> reqwest fn file_part(name: &str, bytes: &[u8]) -> reqwest::multipart::Part { let part = || reqwest::multipart::Part::bytes(bytes.to_vec()).file_name(name.to_string()); // Every type of the table parses; a refusal would only leave reqwest's own default. - part() - .mime_str(&super::model::part_type(name)) - .unwrap_or_else(|_| part()) + part().mime_str(&super::model::part_type(name)).unwrap_or_else(|_| part()) } /// A client per send, for its TLS. It follows no redirect: `send` does, a hop at a time. @@ -1046,22 +916,14 @@ impl Chain { } let status = response.status().as_u16(); let Some(next) = self.follows.then(|| hop.after(status, &headers)).flatten() else { - return Ok(Arrival { - response, - headers, - redirects, - cookies, - }); + return Ok(Arrival { response, headers, redirects, cookies }); }; if redirects.len() >= usize::try_from(self.most.value).unwrap_or(usize::MAX) { return Err(SendError::TooManyRedirects(self.most)); } let set: Vec = response::cookies(&headers) .into_iter() - .map(|cookie| Cookie { - from: Some(hop.url.to_string()), - ..cookie - }) + .map(|cookie| Cookie { from: Some(hop.url.to_string()), ..cookie }) .collect(); redirects.push(Redirect { status, @@ -1075,10 +937,7 @@ impl Chain { } } -async fn send( - mut outgoing: Outgoing, - changes: Arc>>, -) -> Result { +async fn send(mut outgoing: Outgoing, changes: Arc>>) -> Result { install_crypto(); let jar = outgoing.jar.take(); let mut exchange = exchange(&outgoing); @@ -1105,12 +964,7 @@ async fn send( let echoed = super::history::sent_secrets(&exchange, &outgoing.secrets); let secret_values = outgoing.secret_values.clone(); - let Arrival { - mut response, - headers, - redirects, - cookies: set_on_the_way, - } = chain.follow(hop).await?; + let Arrival { mut response, headers, redirects, cookies: set_on_the_way } = chain.follow(hop).await?; let failure = |error: reqwest::Error| failure(&error, &timeout); let status = response.status(); let url = response.url().to_string(); @@ -1145,9 +999,7 @@ async fn send( let pretty = (language == Language::Json && !cut) .then(|| response::pretty_json(&shown)) .flatten(); - let graphql = (is_graphql && !cut) - .then(|| graphql::result(&shown)) - .flatten(); + let graphql = (is_graphql && !cut).then(|| graphql::result(&shown)).flatten(); Ok(Received { response: SentResponse { @@ -1156,10 +1008,7 @@ async fn send( millis, size: u32::try_from(bytes.len()).unwrap_or(u32::MAX), url, - cookies: set_on_the_way - .into_iter() - .chain(response::cookies(&headers)) - .collect(), + cookies: set_on_the_way.into_iter().chain(response::cookies(&headers)).collect(), headers, cut, body: shown, @@ -1172,22 +1021,15 @@ async fn send( graphql, scripts: ScriptsAnswer::default(), }, - kept: Kept { - content_type, - bytes, - secret_values, - echoed, - }, + kept: Kept { content_type, bytes, secret_values, echoed }, }) } fn with_cookie(exchange: &mut Exchange, line: Option) { if let Some(line) = line { - exchange.headers.push(KeyValue { - key: "Cookie".to_string(), - value: line, - ..KeyValue::default() - }); + exchange + .headers + .push(KeyValue { key: "Cookie".to_string(), value: line, ..KeyValue::default() }); } } @@ -1195,13 +1037,8 @@ fn with_cookie(exchange: &mut Exchange, line: Option) { /// hops did to the jar. pub(crate) async fn alone(outgoing: Outgoing) -> (Result, Vec) { let changes: Arc>> = Arc::default(); - let answer = send(outgoing, Arc::clone(&changes)) - .await - .map(|received| received.response); - let changes = changes - .lock() - .map(|mut set| std::mem::take(&mut *set)) - .unwrap_or_default(); + let answer = send(outgoing, Arc::clone(&changes)).await.map(|received| received.response); + let changes = changes.lock().map(|mut set| std::mem::take(&mut *set)).unwrap_or_default(); (answer, changes) } @@ -1219,11 +1056,7 @@ pub struct Sending { /// A task aborted was cancelled; one that panicked fell, which a cancel must not hide. fn ended(error: &tokio::task::JoinError) -> SendError { - if error.is_panic() { - SendError::Fell - } else { - SendError::Cancelled - } + if error.is_panic() { SendError::Fell } else { SendError::Cancelled } } impl Sending { @@ -1240,32 +1073,23 @@ impl Sending { let task = runtime.spawn(send(outgoing, Arc::clone(&changes))); let number = self.started.fetch_add(1, Ordering::Relaxed); if let Ok(mut running) = self.running.lock() - && let Some((_, previous)) = - running.insert(id.to_string(), (number, task.abort_handle())) + && let Some((_, previous)) = running.insert(id.to_string(), (number, task.abort_handle())) { previous.abort(); } let answer = task.await; if let Ok(mut running) = self.running.lock() - && running - .get(id) - .is_some_and(|(current, _)| *current == number) + && running.get(id).is_some_and(|(current, _)| *current == number) { running.remove(id); } - let answer = answer - .map_err(|error| ended(&error)) - .flatten() - .map(|received| { - if let Ok(mut bodies) = self.bodies.lock() { - bodies.insert(id.to_string(), Arc::new(received.kept)); - } - received.response - }); - let changes = changes - .lock() - .map(|mut set| std::mem::take(&mut *set)) - .unwrap_or_default(); + let answer = answer.map_err(|error| ended(&error)).flatten().map(|received| { + if let Ok(mut bodies) = self.bodies.lock() { + bodies.insert(id.to_string(), Arc::new(received.kept)); + } + received.response + }); + let changes = changes.lock().map(|mut set| std::mem::take(&mut *set)).unwrap_or_default(); (answer, changes) } @@ -1320,12 +1144,10 @@ impl Sending { pub fn image(&self, id: &str) -> Option { let kept = self.kept(id)?; let kind = kept.content_type.as_deref()?.split(';').next()?.trim(); - (kind.to_ascii_lowercase().starts_with("image/") && kept.bytes.len() <= IMAGE_LIMIT).then( - || { - let encoded = base64::engine::general_purpose::STANDARD.encode(&kept.bytes); - format!("data:{kind};base64,{encoded}") - }, - ) + (kind.to_ascii_lowercase().starts_with("image/") && kept.bytes.len() <= IMAGE_LIMIT).then(|| { + let encoded = base64::engine::general_purpose::STANDARD.encode(&kept.bytes); + format!("data:{kind};base64,{encoded}") + }) } /// The text of an answer made a note: what the request sent as a secret masked wherever it @@ -1340,10 +1162,7 @@ impl Sending { echoed.sort_by_key(|value| std::cmp::Reverse(value.len())); } let masked = super::history::masked_echo(&hidden, &echoed); - NoteText { - masked: masked != text, - text: masked, - } + NoteText { masked: masked != text, text: masked } } fn kept(&self, id: &str) -> Option> { @@ -1365,33 +1184,19 @@ mod tests { use crate::http::transport::TransportSettings; fn row(key: &str, value: &str) -> KeyValue { - KeyValue { - key: key.to_string(), - value: value.to_string(), - ..KeyValue::default() - } + KeyValue { key: key.to_string(), value: value.to_string(), ..KeyValue::default() } } fn off(key: &str) -> KeyValue { - KeyValue { - enabled: false, - ..row(key, "x") - } + KeyValue { enabled: false, ..row(key, "x") } } fn document(url: &str) -> RequestDocument { - RequestDocument { - url: url.to_string(), - ..RequestDocument::default() - } + RequestDocument { url: url.to_string(), ..RequestDocument::default() } } fn origin(name: &str) -> HttpOrigin { - HttpOrigin { - kind: HttpItemKind::Collection, - id: name.to_lowercase(), - name: name.to_string(), - } + HttpOrigin { kind: HttpItemKind::Collection, id: name.to_lowercase(), name: name.to_string() } } fn above(settings: ContainerSettings) -> Inherited { @@ -1399,10 +1204,7 @@ mod tests { } fn headers_above(rows: Vec) -> Inherited { - above(ContainerSettings { - headers: rows, - ..ContainerSettings::default() - }) + above(ContainerSettings { headers: rows, ..ContainerSettings::default() }) } fn post(document: &RequestDocument, inherited: &Inherited) -> Result { @@ -1434,10 +1236,9 @@ mod tests { "not a url with spaces://", ] { match post(&document(url), &inherit(&[])) { - Err(SendError::InvalidUrl(reason)) => assert!( - !reason.contains("s3cret") && !reason.contains("hosts"), - "{url}: {reason}" - ), + Err(SendError::InvalidUrl(reason)) => { + assert!(!reason.contains("s3cret") && !reason.contains("hosts"), "{url}: {reason}"); + } other => panic!("{url}: {other:?}"), } } @@ -1452,10 +1253,8 @@ mod tests { let in_url = post(&held, &inherit(&[])); held.url = "https://shop.test/".to_string(); let in_header = post(&held, &inherit(&[])); - let above = post( - &document("https://shop.test/"), - &headers_above(vec![row("X-Tenant", "{{tenant}}")]), - ); + let above = + post(&document("https://shop.test/"), &headers_above(vec![row("X-Tenant", "{{tenant}}")])); assert_eq!(in_url, Err(SendError::Variable("path".to_string()))); assert_eq!(in_header, Err(SendError::Variable("token".to_string()))); @@ -1467,18 +1266,10 @@ mod tests { #[test] fn its_own_headers_go_over_the_inherited_ones_by_name() { let mut held = document("https://shop.test/"); - held.headers = vec![ - row("x-tenant", "mine"), - off("X-Debug"), - row(" ", "unnamed"), - row(" X-Own ", "1"), - ]; - - let sent = post( - &held, - &headers_above(vec![row("X-Tenant", "theirs"), row("X-Debug", "1")]), - ) - .unwrap(); + held.headers = + vec![row("x-tenant", "mine"), off("X-Debug"), row(" ", "unnamed"), row(" X-Own ", "1")]; + + let sent = post(&held, &headers_above(vec![row("X-Tenant", "theirs"), row("X-Debug", "1")])).unwrap(); assert_eq!(value(&sent, "X-Tenant"), Some("mine")); assert_eq!(value(&sent, "X-Debug"), Some("1")); @@ -1490,25 +1281,14 @@ mod tests { /// own already writes it — and an API key's name is what the history masks. #[test] fn the_auth_becomes_a_header_or_a_query_pair_unless_a_row_writes_it() { - let with = |auth: RequestAuth| RequestDocument { - auth, - ..document("https://shop.test/a?x=1") - }; + let with = |auth: RequestAuth| RequestDocument { auth, ..document("https://shop.test/a?x=1") }; let basic = post( - &with(RequestAuth::Basic { - username: "ada".to_string(), - password: "pw".to_string(), - }), - &inherit(&[]), - ) - .unwrap(); - let bearer = post( - &with(RequestAuth::Bearer { - token: " t0k3n ".to_string(), - }), + &with(RequestAuth::Basic { username: "ada".to_string(), password: "pw".to_string() }), &inherit(&[]), ) .unwrap(); + let bearer = + post(&with(RequestAuth::Bearer { token: " t0k3n ".to_string() }), &inherit(&[])).unwrap(); let header_key = post( &with(RequestAuth::ApiKey { name: " X-Api-Key ".to_string(), @@ -1539,37 +1319,24 @@ mod tests { let inherited = post( &document("https://shop.test/"), &above(ContainerSettings { - auth: RequestAuth::Bearer { - token: "above".to_string(), - }, + auth: RequestAuth::Bearer { token: "above".to_string() }, ..ContainerSettings::default() }), ) .unwrap(); - let mut typed = with(RequestAuth::Bearer { - token: "t".to_string(), - }); + let mut typed = with(RequestAuth::Bearer { token: "t".to_string() }); typed.headers = vec![row("authorization", "Custom x")]; let typed = post(&typed, &inherit(&[])).unwrap(); assert_eq!(value(&basic, "Authorization"), Some("Basic YWRhOnB3")); assert_eq!(value(&bearer, "Authorization"), Some("Bearer t0k3n")); assert_eq!( - ( - value(&header_key, "X-Api-Key"), - header_key.secrets.as_slice() - ), + (value(&header_key, "X-Api-Key"), header_key.secrets.as_slice()), (Some("k"), ["x-api-key".to_string()].as_slice()) ); - assert_eq!( - query_key.url.as_str(), - "https://shop.test/a?x=1&api+key=k%261" - ); + assert_eq!(query_key.url.as_str(), "https://shop.test/a?x=1&api+key=k%261"); assert_eq!(query_key.secrets, ["api key"]); - assert_eq!( - (unnamed_key.url.as_str(), unnamed_key.secrets.len()), - ("https://shop.test/a?x=1", 0) - ); + assert_eq!((unnamed_key.url.as_str(), unnamed_key.secrets.len()), ("https://shop.test/a?x=1", 0)); assert_eq!(value(&inherited, "Authorization"), Some("Bearer above")); assert_eq!(value(&typed, "Authorization"), Some("Custom x")); } @@ -1588,27 +1355,18 @@ mod tests { let sent = post(&unnamed, &inherit(&[])).unwrap(); let names: Vec<&str> = sent.headers.iter().map(|(name, _)| name.as_str()).collect(); - assert_eq!( - (names, sent.secrets.len()), - (vec!["User-Agent", "Accept"], 0) - ); + assert_eq!((names, sent.secrets.len()), (vec!["User-Agent", "Accept"], 0)); } /// Its tool alone knows the boundary. #[test] fn a_program_is_not_handed_a_multipart_form_s_type() { - let with = |body: RequestBody| RequestDocument { - body, - ..document("https://shop.test/") - }; - let written = - |body: RequestBody| written_for_code(RequestKind::Http, &with(body), &inherit(&[])); + let with = |body: RequestBody| RequestDocument { body, ..document("https://shop.test/") }; + let written = |body: RequestBody| written_for_code(RequestKind::Http, &with(body), &inherit(&[])); assert!(written(RequestBody::Multipart { parts: Vec::new() }).is_empty()); assert_eq!( - written(RequestBody::Json { - text: String::new() - }), + written(RequestBody::Json { text: String::new() }), [("Content-Type".to_string(), "application/json".to_string())] ); } @@ -1619,24 +1377,15 @@ mod tests { fn the_application_names_itself_unless_a_row_says_otherwise() { let plain = post(&document("https://shop.test/"), &inherit(&[])).unwrap(); let mut own = document("https://shop.test/"); - own.headers = vec![ - row("User-Agent", "curl/8"), - row("accept", "application/json"), - ]; + own.headers = vec![row("User-Agent", "curl/8"), row("accept", "application/json")]; let own = post(&own, &inherit(&[])).unwrap(); let mut silenced = document("https://shop.test/"); silenced.headers = vec![off("user-agent")]; let silenced = post(&silenced, &inherit(&[])).unwrap(); - let silenced_above = post( - &document("https://shop.test/"), - &headers_above(vec![off("User-Agent")]), - ) - .unwrap(); + let silenced_above = + post(&document("https://shop.test/"), &headers_above(vec![off("User-Agent")])).unwrap(); - assert_eq!( - (value(&plain, "User-Agent"), value(&plain, "Accept")), - (Some(USER_AGENT), Some("*/*")) - ); + assert_eq!((value(&plain, "User-Agent"), value(&plain, "Accept")), (Some(USER_AGENT), Some("*/*"))); assert_eq!( (value(&own, "User-Agent"), value(&own, "Accept")), (Some("curl/8"), Some("application/json")) @@ -1665,10 +1414,7 @@ mod tests { own.headers = vec![row("X Bad", "1")]; let mine = post(&own, &inherit(&[])); - let theirs = post( - &document("https://shop.test/"), - &headers_above(vec![row("X-Id", "a\nb")]), - ); + let theirs = post(&document("https://shop.test/"), &headers_above(vec![row("X-Id", "a\nb")])); assert_eq!( mine, @@ -1692,50 +1438,28 @@ mod tests { /// text as typed. #[test] fn a_body_carries_its_type_unless_one_is_typed() { - let with = |body: RequestBody| RequestDocument { - body, - ..document("https://shop.test/") - }; - let json = post( - &with(RequestBody::Json { - text: "{\"a\":1}".to_string(), - }), - &inherit(&[]), - ) - .unwrap(); + let with = |body: RequestBody| RequestDocument { body, ..document("https://shop.test/") }; + let json = post(&with(RequestBody::Json { text: "{\"a\":1}".to_string() }), &inherit(&[])).unwrap(); let form = post( - &with(RequestBody::Form { - fields: vec![row(" a b ", "x&y"), off("c"), row("", "z")], - }), + &with(RequestBody::Form { fields: vec![row(" a b ", "x&y"), off("c"), row("", "z")] }), &inherit(&[]), ) .unwrap(); - let mut typed = with(RequestBody::Text { - text: "t".to_string(), - }); + let mut typed = with(RequestBody::Text { text: "t".to_string() }); typed.headers = vec![row("content-type", "text/csv")]; let typed = post(&typed, &inherit(&[])).unwrap(); let none = post(&with(RequestBody::None), &inherit(&[])).unwrap(); assert_eq!( (value(&json, "Content-Type"), &json.body), - ( - Some("application/json"), - &OutgoingBody::Bytes(b"{\"a\":1}".to_vec()) - ) + (Some("application/json"), &OutgoingBody::Bytes(b"{\"a\":1}".to_vec())) ); assert_eq!( (value(&form, "Content-Type"), &form.body), - ( - Some("application/x-www-form-urlencoded"), - &OutgoingBody::Bytes(b"a+b=x%26y".to_vec()) - ) + (Some("application/x-www-form-urlencoded"), &OutgoingBody::Bytes(b"a+b=x%26y".to_vec())) ); assert_eq!(value(&typed, "Content-Type"), Some("text/csv")); - assert_eq!( - (value(&none, "Content-Type"), &none.body), - (None, &OutgoingBody::None) - ); + assert_eq!((value(&none, "Content-Type"), &none.body), (None, &OutgoingBody::None)); } /// A file is read when it is sent: a part keeps its file's name, a missing one is named, one @@ -1759,10 +1483,7 @@ mod tests { file, ..FormPart::default() }; - let with = |body: RequestBody| RequestDocument { - body, - ..document("https://shop.test/") - }; + let with = |body: RequestBody| RequestDocument { body, ..document("https://shop.test/") }; let multipart = post( &with(RequestBody::Multipart { @@ -1776,50 +1497,25 @@ mod tests { &inherit(&[]), ) .unwrap(); - let binary = post( - &with(RequestBody::Binary { path: path.clone() }), - &inherit(&[]), - ) - .unwrap(); - let missing = scratch - .path() - .join("missing.bin") - .to_str() - .unwrap() - .to_string(); + let binary = post(&with(RequestBody::Binary { path: path.clone() }), &inherit(&[])).unwrap(); + let missing = scratch.path().join("missing.bin").to_str().unwrap().to_string(); assert_eq!( multipart.body, OutgoingBody::Multipart(vec![ ("title".to_string(), Part::Text("Facture".to_string())), - ( - "scan".to_string(), - Part::File { - name: "scan.pdf".to_string(), - bytes: b"%PDF".to_vec() - } - ) + ("scan".to_string(), Part::File { name: "scan.pdf".to_string(), bytes: b"%PDF".to_vec() }) ]) ); assert_eq!(value(&multipart, "Content-Type"), None); assert_eq!(binary.body, OutgoingBody::Bytes(b"%PDF".to_vec())); assert_eq!( - post( - &with(RequestBody::Binary { - path: missing.clone() - }), - &inherit(&[]) - ), + post(&with(RequestBody::Binary { path: missing.clone() }), &inherit(&[])), Err(SendError::FileUnreadable(missing)) ); let heavy = heavy.to_str().unwrap().to_string(); assert_eq!( - post( - &with(RequestBody::Binary { - path: heavy.clone() - }), - &inherit(&[]) - ), + post(&with(RequestBody::Binary { path: heavy.clone() }), &inherit(&[])), Err(SendError::FileTooLarge(heavy)) ); } @@ -1833,42 +1529,19 @@ mod tests { held.graphql.variables = "{\"a\":1}".to_string(); held.graphql.operation_name = Some("Me".to_string()); - let posted = compose( - RequestKind::Graphql, - HttpMethod::Delete, - &held, - &inherit(&[]), - ) - .unwrap(); + let posted = compose(RequestKind::Graphql, HttpMethod::Delete, &held, &inherit(&[])).unwrap(); held.graphql.as_get = true; - let got = compose( - RequestKind::Graphql, - HttpMethod::Delete, - &held, - &inherit(&[]), - ) - .unwrap(); + let got = compose(RequestKind::Graphql, HttpMethod::Delete, &held, &inherit(&[])).unwrap(); held.graphql.variables = "[1]".to_string(); - let refused = compose( - RequestKind::Graphql, - HttpMethod::Delete, - &held, - &inherit(&[]), - ); + let refused = compose(RequestKind::Graphql, HttpMethod::Delete, &held, &inherit(&[])); assert_eq!( - ( - posted.method, - value(&posted, "Content-Type"), - posted.graphql - ), + (posted.method, value(&posted, "Content-Type"), posted.graphql), (HttpMethod::Post, Some("application/json"), true) ); assert_eq!( posted.body, - OutgoingBody::Bytes( - br#"{"query":"{ me }","variables":{"a":1},"operationName":"Me"}"#.to_vec() - ) + OutgoingBody::Bytes(br#"{"query":"{ me }","variables":{"a":1},"operationName":"Me"}"#.to_vec()) ); assert_eq!( (got.method, value(&got, "Content-Type"), &got.body), @@ -1890,10 +1563,7 @@ mod tests { let sent = compose(RequestKind::Graphql, HttpMethod::Get, &held, &inherit(&[])).unwrap(); - assert_eq!( - sent.url.as_str(), - "https://shop.test/graphql?query=%7Bme%7D" - ); + assert_eq!(sent.url.as_str(), "https://shop.test/graphql?query=%7Bme%7D"); } /// Its own transport over what it inherits, and who set the delay and the redirects a send @@ -1913,24 +1583,9 @@ mod tests { let sent = post(&own, &inherited).unwrap(); - assert_eq!( - sent.timeout(), - Limit { - value: 1_000, - set_by: SetBy::Request - } - ); - assert_eq!( - sent.redirects(), - Limit { - value: 3, - set_by: SetBy::Above(origin("Shop")) - } - ); - assert_eq!( - (sent.jar.is_none(), sent.secret_values.is_empty()), - (true, true) - ); + assert_eq!(sent.timeout(), Limit { value: 1_000, set_by: SetBy::Request }); + assert_eq!(sent.redirects(), Limit { value: 3, set_by: SetBy::Above(origin("Shop")) }); + assert_eq!((sent.jar.is_none(), sent.secret_values.is_empty()), (true, true)); } fn implied_names( @@ -1949,24 +1604,14 @@ mod tests { #[test] fn what_leaves_without_a_row_is_listed_with_who_put_it_there() { let mut held = document("https://shop.test:8443/a"); - held.body = RequestBody::Json { - text: "{}".to_string(), - }; + held.body = RequestBody::Json { text: "{}".to_string() }; held.headers = vec![row("X-Own", "1")]; - held.auth = RequestAuth::Bearer { - token: "t".to_string(), - }; + held.auth = RequestAuth::Bearer { token: "t".to_string() }; - let listed = implied( - RequestKind::Http, - &held, - &headers_above(vec![row("X-Tenant", "acme")]), - ); + let listed = implied(RequestKind::Http, &held, &headers_above(vec![row("X-Tenant", "acme")])); - let shown: Vec<(&str, ImpliedSource)> = listed - .iter() - .map(|header| (header.name.as_str(), header.source)) - .collect(); + let shown: Vec<(&str, ImpliedSource)> = + listed.iter().map(|header| (header.name.as_str(), header.source)).collect(); assert_eq!( shown, [ @@ -2002,23 +1647,16 @@ mod tests { Some("shop.test".to_string()) ); assert_eq!(host(RequestKind::Http, &document("")), None); - assert_eq!( - host(RequestKind::Http, &document("https://{{base}}/a")), - None - ); + assert_eq!(host(RequestKind::Http, &document("https://{{base}}/a")), None); assert_eq!(host(RequestKind::Http, &typed), None); assert_eq!( host(RequestKind::Websocket, &document("wss://live.test:9000/")), Some("live.test:9000".to_string()) ); assert!( - !implied_names( - RequestKind::Websocket, - &document("wss://live.test/"), - &inherit(&[]) - ) - .iter() - .any(|(name, ..)| name == "Content-Type") + !implied_names(RequestKind::Websocket, &document("wss://live.test/"), &inherit(&[])) + .iter() + .any(|(name, ..)| name == "Content-Type") ); assert!( !implied_names(RequestKind::Graphql, &graphql_get, &inherit(&[])) @@ -2034,36 +1672,24 @@ mod tests { let mut outgoing = post(&document("https://shop.test/?t=t0k3n"), &inherit(&[])).unwrap(); outgoing.headers = vec![("X-Token".to_string(), "t0k3n".to_string())]; outgoing.secret_values = vec![("token".to_string(), "t0k3n".to_string())]; - outgoing.body = - OutgoingBody::Bytes(format!("{}{}", "t0k3n ", "a".repeat(SHOWN_LIMIT)).into_bytes()); + outgoing.body = OutgoingBody::Bytes(format!("{}{}", "t0k3n ", "a".repeat(SHOWN_LIMIT)).into_bytes()); let text = exchange(&outgoing); outgoing.body = OutgoingBody::Bytes(vec![0xff, 0xfe, 0x00]); let bytes = exchange(&outgoing); - outgoing.body = - OutgoingBody::Multipart(vec![("title".to_string(), Part::Text("x".to_string()))]); + outgoing.body = OutgoingBody::Multipart(vec![("title".to_string(), Part::Text("x".to_string()))]); let form = exchange(&outgoing); assert_eq!(text.url, "https://shop.test/?t={{token}}"); assert_eq!(text.headers[0].value, "{{token}}"); - let SentBody::Text { text: shown } = &text.body else { - panic!("no text") - }; + let SentBody::Text { text: shown } = &text.body else { panic!("no text") }; assert!(shown.starts_with("{{token}} ") && shown.chars().count() < SHOWN_LIMIT + 10); assert_eq!(bytes.body, SentBody::Bytes { size: 3 }); - assert_eq!( - form.body, - SentBody::Multipart { - fields: vec!["title".to_string()] - } - ); + assert_eq!(form.body, SentBody::Multipart { fields: vec!["title".to_string()] }); } #[derive(Debug)] - struct Wrapped( - &'static str, - Option>, - ); + struct Wrapped(&'static str, Option>); impl std::fmt::Display for Wrapped { fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { @@ -2073,9 +1699,7 @@ mod tests { impl std::error::Error for Wrapped { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - self.1 - .as_deref() - .map(|inner| inner as &(dyn std::error::Error + 'static)) + self.1.as_deref().map(|inner| inner as &(dyn std::error::Error + 'static)) } } @@ -2085,13 +1709,9 @@ mod tests { #[test] fn a_failure_is_read_off_the_chain_of_its_causes() { use std::io::{Error, ErrorKind}; - let limit = Limit { - value: 5_000, - set_by: SetBy::Request, - }; - let wrap = |inner: Box| { - Wrapped("error sending request", Some(inner)) - }; + let limit = Limit { value: 5_000, set_by: SetBy::Request }; + let wrap = + |inner: Box| Wrapped("error sending request", Some(inner)); let kind_of = |error: &(dyn std::error::Error + 'static), limit: Option<&Limit>| { cause_of(error, limit).map(|found| std::mem::discriminant(&found)) }; @@ -2101,10 +1721,7 @@ mod tests { let tls = SendError::Tls(String::new()); assert_eq!( - kind_of( - &wrap(Box::new(Error::from(ErrorKind::ConnectionRefused))), - None - ), + kind_of(&wrap(Box::new(Error::from(ErrorKind::ConnectionRefused))), None), Some(std::mem::discriminant(&refused)) ); assert_eq!( @@ -2124,24 +1741,15 @@ mod tests { ); } assert_eq!( - kind_of( - &Error::other(Wrapped("invalid peer certificate: UnknownIssuer", None)), - None - ), + kind_of(&Error::other(Wrapped("invalid peer certificate: UnknownIssuer", None)), None), Some(std::mem::discriminant(&tls)) ); assert_eq!( - kind_of( - &Error::other(rustls::Error::General("handshake".to_string())), - None - ), + kind_of(&Error::other(rustls::Error::General("handshake".to_string())), None), Some(std::mem::discriminant(&tls)) ); assert_eq!(kind_of(&Wrapped("something else", None), None), None); - assert_eq!( - innermost(&wrap(Box::new(Wrapped("the root", None)))), - "the root" - ); + assert_eq!(innermost(&wrap(Box::new(Wrapped("the root", None)))), "the root"); } /// Windows words its errors in the system's language: the code names the failure. @@ -2150,10 +1758,7 @@ mod tests { fn a_name_that_does_not_resolve_is_read_by_its_code_on_windows() { for code in [11001, 11002, 11003, 11004] { let error = std::io::Error::from_raw_os_error(code); - assert!( - matches!(cause_of(&error, None), Some(SendError::Unresolved(_))), - "{code}" - ); + assert!(matches!(cause_of(&error, None), Some(SendError::Unresolved(_))), "{code}"); } for code in [11000, 11005, 10054] { let error = std::io::Error::from_raw_os_error(code); @@ -2217,11 +1822,7 @@ mod tests { assert_eq!( (moved.method.clone(), moved.url.as_str(), &moved.body), - ( - reqwest::Method::GET, - "https://shop.test/c?x=1", - &OutgoingBody::None - ) + (reqwest::Method::GET, "https://shop.test/c?x=1", &OutgoingBody::None) ); assert_eq!(names(&moved), ["X-Keep", "Referer"]); assert_eq!( @@ -2261,21 +1862,10 @@ mod tests { let same = first.after(302, &location("/b")).unwrap(); let other_host = first.after(302, &location("https://cdn.test/b")).unwrap(); - let other_port = first - .after(302, &location("https://shop.test:8443/b")) - .unwrap(); + let other_port = first.after(302, &location("https://shop.test:8443/b")).unwrap(); let plain = first.after(302, &location("http://shop.test/b")).unwrap(); - assert_eq!( - names(&same), - [ - "Authorization", - "Cookie", - "Proxy-Authorization", - "X-Keep", - "Referer" - ] - ); + assert_eq!(names(&same), ["Authorization", "Cookie", "Proxy-Authorization", "X-Keep", "Referer"]); assert_eq!(same.headers.last().unwrap().1, "https://shop.test/a"); assert_eq!(names(&other_host), ["X-Keep", "Referer"]); assert_eq!(names(&other_port), ["X-Keep", "Referer"]); @@ -2304,23 +1894,12 @@ mod tests { .as_deref(), Some("sid=1") ); + assert_eq!(hop(reqwest::Method::GET, "https://other.test/", &[]).cookie(Some(&jar)), None); assert_eq!( - hop(reqwest::Method::GET, "https://other.test/", &[]).cookie(Some(&jar)), - None - ); - assert_eq!( - hop( - reqwest::Method::GET, - "https://shop.test/", - &[("cookie", "typed=1")] - ) - .cookie(Some(&jar)), - None - ); - assert_eq!( - hop(reqwest::Method::GET, "https://shop.test/", &[]).cookie(None), + hop(reqwest::Method::GET, "https://shop.test/", &[("cookie", "typed=1")]).cookie(Some(&jar)), None ); + assert_eq!(hop(reqwest::Method::GET, "https://shop.test/", &[]).cookie(None), None); } /// Text by its type, or failing one by its bytes reading as UTF-8. Private: an answer's body diff --git a/crates/engine/src/http/settings.rs b/crates/engine/src/http/settings.rs index 15345555a..2a176ce07 100644 --- a/crates/engine/src/http/settings.rs +++ b/crates/engine/src/http/settings.rs @@ -2,9 +2,7 @@ use super::transport::{self, Limits, SetBy, Transport, TransportSettings}; -use super::model::{ - ContainerSettings, HttpItemKind, KeyValue, RequestAuth, RequestBody, RequestScripts, -}; +use super::model::{ContainerSettings, HttpItemKind, KeyValue, RequestAuth, RequestBody, RequestScripts}; use super::variables::{VariableLayer, VariableScope}; /// Where an inherited value was set: what the request says it comes from. @@ -67,10 +65,7 @@ pub fn inherit(levels: &[(HttpOrigin, ContainerSettings)]) -> Inherited { .iter() .filter(|header| header.enabled && !header.key.trim().is_empty()) { - let inherited = InheritedHeader { - header: header.clone(), - from: origin.clone(), - }; + let inherited = InheritedHeader { header: header.clone(), from: origin.clone() }; match headers .iter_mut() .find(|known| known.header.key.eq_ignore_ascii_case(&header.key)) @@ -98,9 +93,7 @@ pub fn inherit(levels: &[(HttpOrigin, ContainerSettings)]) -> Inherited { timeout: set_by(|transport| transport.timeout_ms.is_some()), redirects: set_by(|transport| transport.max_redirects.is_some()), }, - user_agent_off: levels - .iter() - .any(|(_, settings)| switches_off(&settings.headers, "user-agent")), + user_agent_off: levels.iter().any(|(_, settings)| switches_off(&settings.headers, "user-agent")), variables: levels .iter() .rev() @@ -125,8 +118,7 @@ pub fn inherit(levels: &[(HttpOrigin, ContainerSettings)]) -> Inherited { /// Whether a row of that name is written and switched off. pub fn switches_off(rows: &[KeyValue], name: &str) -> bool { - rows.iter() - .any(|row| !row.enabled && row.key.trim().eq_ignore_ascii_case(name)) + rows.iter().any(|row| !row.enabled && row.key.trim().eq_ignore_ascii_case(name)) } /// The `Content-Type` a body implies, sent unless the request sets one by hand. A multipart one @@ -148,11 +140,7 @@ mod tests { use crate::http::environments::Variable; fn origin(kind: HttpItemKind, name: &str) -> HttpOrigin { - HttpOrigin { - kind, - id: name.to_lowercase(), - name: name.to_string(), - } + HttpOrigin { kind, id: name.to_lowercase(), name: name.to_string() } } fn collection() -> HttpOrigin { @@ -164,44 +152,27 @@ mod tests { } fn row(key: &str, value: &str) -> KeyValue { - KeyValue { - key: key.to_string(), - value: value.to_string(), - ..KeyValue::default() - } + KeyValue { key: key.to_string(), value: value.to_string(), ..KeyValue::default() } } fn off(key: &str) -> KeyValue { - KeyValue { - enabled: false, - ..row(key, "") - } + KeyValue { enabled: false, ..row(key, "") } } fn bearer(token: &str) -> RequestAuth { - RequestAuth::Bearer { - token: token.to_string(), - } + RequestAuth::Bearer { token: token.to_string() } } fn with_auth(auth: RequestAuth) -> ContainerSettings { - ContainerSettings { - auth, - ..ContainerSettings::default() - } + ContainerSettings { auth, ..ContainerSettings::default() } } /// The nearest level that sets one wins, and is named; `Inherit` all the way up is none. #[test] fn the_nearest_auth_set_is_inherited_and_named() { - let both = inherit(&[ - (collection(), with_auth(bearer("c"))), - (folder(), with_auth(bearer("f"))), - ]); - let up = inherit(&[ - (collection(), with_auth(bearer("c"))), - (folder(), with_auth(RequestAuth::Inherit)), - ]); + let both = inherit(&[(collection(), with_auth(bearer("c"))), (folder(), with_auth(bearer("f")))]); + let up = + inherit(&[(collection(), with_auth(bearer("c"))), (folder(), with_auth(RequestAuth::Inherit))]); let nothing = inherit(&[(collection(), with_auth(RequestAuth::Inherit))]); assert_eq!((both.auth, both.auth_from), (bearer("f"), Some(folder()))); @@ -214,12 +185,7 @@ mod tests { #[test] fn a_folder_s_header_overrides_its_collection_s_of_the_same_name() { let above = ContainerSettings { - headers: vec![ - row("Accept", "text/plain"), - row("X-Shop", "1"), - off("X-Off"), - row(" ", "unnamed"), - ], + headers: vec![row("Accept", "text/plain"), row("X-Shop", "1"), off("X-Off"), row(" ", "unnamed")], ..ContainerSettings::default() }; let near = ContainerSettings { @@ -232,21 +198,11 @@ mod tests { let shown: Vec<(&str, &str, &str)> = inherited .headers .iter() - .map(|known| { - ( - known.header.key.as_str(), - known.header.value.as_str(), - known.from.name.as_str(), - ) - }) + .map(|known| (known.header.key.as_str(), known.header.value.as_str(), known.from.name.as_str())) .collect(); assert_eq!( shown, - [ - ("accept", "application/json", "Orders"), - ("X-Shop", "1", "Shop"), - ("X-Orders", "2", "Orders"), - ] + [("accept", "application/json", "Orders"), ("X-Shop", "1", "Shop"), ("X-Orders", "2", "Orders"),] ); } @@ -274,13 +230,7 @@ mod tests { let inherited = inherit(&[(collection(), above), (folder(), near)]); let bare = inherit(&[(collection(), ContainerSettings::default())]); - assert_eq!( - ( - inherited.transport.timeout_ms, - inherited.transport.max_redirects - ), - (2_000, 3) - ); + assert_eq!((inherited.transport.timeout_ms, inherited.transport.max_redirects), (2_000, 3)); assert!(!inherited.transport.verify_tls); assert_eq!(inherited.limits.timeout, SetBy::Above(folder())); assert_eq!(inherited.limits.redirects, SetBy::Above(collection())); @@ -290,18 +240,9 @@ mod tests { /// A level holding a `User-Agent` row switched off: the application's own is not sent. #[test] fn a_user_agent_switched_off_above_keeps_the_application_s_off() { - let above = ContainerSettings { - headers: vec![off(" user-agent ")], - ..ContainerSettings::default() - }; + let above = ContainerSettings { headers: vec![off(" user-agent ")], ..ContainerSettings::default() }; - assert!( - inherit(&[ - (collection(), above), - (folder(), ContainerSettings::default()) - ]) - .user_agent_off - ); + assert!(inherit(&[(collection(), above), (folder(), ContainerSettings::default())]).user_agent_off); assert!(!inherit(&[(collection(), ContainerSettings::default())]).user_agent_off); } @@ -310,14 +251,8 @@ mod tests { #[test] fn variables_come_nearest_first_and_scripts_from_the_collection_down() { let settings = |name: &str| ContainerSettings { - variables: vec![Variable { - name: name.to_string(), - ..Variable::default() - }], - scripts: RequestScripts { - before: name.to_string(), - ..RequestScripts::default() - }, + variables: vec![Variable { name: name.to_string(), ..Variable::default() }], + scripts: RequestScripts { before: name.to_string(), ..RequestScripts::default() }, ..ContainerSettings::default() }; @@ -326,20 +261,11 @@ mod tests { let layers: Vec<(VariableScope, &str, &str)> = inherited .variables .iter() - .map(|layer| { - ( - layer.scope, - layer.from.as_str(), - layer.variables[0].name.as_str(), - ) - }) + .map(|layer| (layer.scope, layer.from.as_str(), layer.variables[0].name.as_str())) .collect(); assert_eq!( layers, - [ - (VariableScope::Folder, "Orders", "f"), - (VariableScope::Collection, "Shop", "c") - ] + [(VariableScope::Folder, "Orders", "f"), (VariableScope::Collection, "Shop", "c")] ); let scripts: Vec<(&str, &str)> = inherited .scripts @@ -354,32 +280,11 @@ mod tests { fn a_body_implies_its_content_type() { for (body, implied) in [ (RequestBody::None, None), - ( - RequestBody::Json { - text: String::new(), - }, - Some("application/json"), - ), - ( - RequestBody::Text { - text: String::new(), - }, - Some("text/plain"), - ), - ( - RequestBody::Form { fields: Vec::new() }, - Some("application/x-www-form-urlencoded"), - ), - ( - RequestBody::Multipart { parts: Vec::new() }, - Some("multipart/form-data"), - ), - ( - RequestBody::Binary { - path: String::new(), - }, - Some("application/octet-stream"), - ), + (RequestBody::Json { text: String::new() }, Some("application/json")), + (RequestBody::Text { text: String::new() }, Some("text/plain")), + (RequestBody::Form { fields: Vec::new() }, Some("application/x-www-form-urlencoded")), + (RequestBody::Multipart { parts: Vec::new() }, Some("multipart/form-data")), + (RequestBody::Binary { path: String::new() }, Some("application/octet-stream")), ] { assert_eq!(implied_content_type(&body), implied, "{body:?}"); } diff --git a/crates/engine/src/http/store.rs b/crates/engine/src/http/store.rs index 03cba6e5a..ee7e04baf 100644 --- a/crates/engine/src/http/store.rs +++ b/crates/engine/src/http/store.rs @@ -9,9 +9,9 @@ use diesel::prelude::*; use uuid::Uuid; use super::model::{ - ContainerSettings, HttpCollection, HttpCollectionNode, HttpContents, HttpFolder, HttpItem, - HttpItemKind, HttpNode, HttpPlace, HttpRequest, HttpRequestDraft, HttpRequestPatch, - HttpRequestSummary, HttpTree, RequestDocument, + ContainerSettings, HttpCollection, HttpCollectionNode, HttpContents, HttpFolder, HttpItem, HttpItemKind, + HttpNode, HttpPlace, HttpRequest, HttpRequestDraft, HttpRequestPatch, HttpRequestSummary, HttpTree, + RequestDocument, }; use super::search::{Candidate, RequestHit}; use super::settings::{HttpOrigin, Inherited}; @@ -61,10 +61,7 @@ fn rank(position: i32) -> u32 { } fn instant(id: &str, field: &'static str, text: &str) -> Result, StorageError> { - iso8601::parse(text).map_err(|_| StorageError::CorruptRow { - id: id.to_string(), - field, - }) + iso8601::parse(text).map_err(|_| StorageError::CorruptRow { id: id.to_string(), field }) } impl CollectionRow { @@ -107,12 +104,8 @@ impl RequestRow { fn open(self, vault: &Vault) -> Result { let summary = self.summary(vault)?; - let document = serde_json::from_str(&vault.open(&self.document)?).map_err(|_| { - StorageError::CorruptRow { - id: self.id.clone(), - field: "document", - } - })?; + let document = serde_json::from_str(&vault.open(&self.document)?) + .map_err(|_| StorageError::CorruptRow { id: self.id.clone(), field: "document" })?; Ok(HttpRequest { created_at: instant(&self.id, "createdAt", &self.created_at)?, updated_at: instant(&self.id, "updatedAt", &self.updated_at)?, @@ -137,10 +130,7 @@ fn seal_json(vault: &Vault, value: &T) -> Result Result { +fn find_collection(connection: &mut SqliteConnection, id: &str) -> Result { http_collections::table .find(id) .select(CollectionRow::as_select()) @@ -178,9 +168,7 @@ fn folder_of_collection( if let Some(folder_id) = folder_id && find_folder(connection, folder_id)?.collection_id != collection_id { - return Err( - ValidationError::new("folderId", "the folder belongs to another collection").into(), - ); + return Err(ValidationError::new("folderId", "the folder belongs to another collection").into()); } Ok(()) } @@ -192,12 +180,8 @@ pub fn tree(connection: &mut Library) -> Result { .select(CollectionRow::as_select()) .order((http_collections::position.asc(), http_collections::id.asc())) .load(connection)?; - let folders = http_folders::table - .select(FolderRow::as_select()) - .load(connection)?; - let requests = http_requests::table - .select(RequestRow::as_select()) - .load(connection)?; + let folders = http_folders::table.select(FolderRow::as_select()).load(connection)?; + let requests = http_requests::table.select(RequestRow::as_select()).load(connection)?; let mut nodes: Branches = HashMap::new(); for row in folders { @@ -205,24 +189,14 @@ pub fn tree(connection: &mut Library) -> Result { nodes .entry((folder.collection_id.clone(), folder.parent_id.clone())) .or_default() - .push(( - folder.position, - 0, - folder.id.clone(), - Branch::Folder(folder), - )); + .push((folder.position, 0, folder.id.clone(), Branch::Folder(folder))); } for row in &requests { let request = row.summary(vault)?; nodes .entry((request.collection_id.clone(), request.folder_id.clone())) .or_default() - .push(( - request.position, - 1, - request.id.clone(), - Branch::Request(request), - )); + .push((request.position, 1, request.id.clone(), Branch::Request(request))); } for siblings in nodes.values_mut() { siblings.sort_by(|a, b| (a.0, a.1, &a.2).cmp(&(b.0, b.1, &b.2))); @@ -233,10 +207,7 @@ pub fn tree(connection: &mut Library) -> Result { .map(|row| { let collection = row.open(vault)?; let children = grow(&mut nodes, &collection.id, None); - Ok(HttpCollectionNode { - collection, - children, - }) + Ok(HttpCollectionNode { collection, children }) }) .collect::>()?; @@ -263,9 +234,7 @@ pub fn search_candidates(connection: &mut Library) -> Result, Sto Ok((folder.id.clone(), (folder.parent_id, folder.name))) }) .collect::, StorageError>>()?; - let requests = http_requests::table - .select(RequestRow::as_select()) - .load(connection)?; + let requests = http_requests::table.select(RequestRow::as_select()).load(connection)?; requests .iter() @@ -289,10 +258,7 @@ pub fn search_candidates(connection: &mut Library) -> Result, Sto folder.clone_from(parent); } let collection = collections.get(&summary.collection_id).cloned(); - let place = collection - .into_iter() - .chain(chain.into_iter().rev()) - .collect(); + let place = collection.into_iter().chain(chain.into_iter().rev()).collect(); Ok(Candidate { updated_at: instant(&row.id, "updatedAt", &row.updated_at)?, @@ -324,10 +290,9 @@ fn grow(nodes: &mut Branches, collection_id: &str, folder_id: Option<&str>) -> V siblings .into_iter() .map(|(_, _, id, branch)| match branch { - Branch::Folder(folder) => HttpNode::Folder { - children: grow(nodes, collection_id, Some(&id)), - folder, - }, + Branch::Folder(folder) => { + HttpNode::Folder { children: grow(nodes, collection_id, Some(&id)), folder } + } Branch::Request(request) => HttpNode::Request { request }, }) .collect() @@ -371,11 +336,7 @@ fn siblings( Ok(ranked .into_iter() .map(|(_, kind, id)| HttpItem { - kind: if kind == 0 { - HttpItemKind::Folder - } else { - HttpItemKind::Request - }, + kind: if kind == 0 { HttpItemKind::Folder } else { HttpItemKind::Request }, id, }) .collect()) @@ -424,10 +385,7 @@ fn collections_in_order(connection: &mut SqliteConnection) -> Result(connection)? .into_iter() - .map(|id| HttpItem { - kind: HttpItemKind::Collection, - id, - }) + .map(|id| HttpItem { kind: HttpItemKind::Collection, id }) .collect()) } @@ -487,10 +445,7 @@ fn insert_folder( insert_at( connection, others, - HttpItem { - kind: HttpItemKind::Folder, - id: folder.id.clone(), - }, + HttpItem { kind: HttpItemKind::Folder, id: folder.id.clone() }, usize::MAX, )?; Ok(folder) @@ -521,15 +476,7 @@ fn insert_request( http_requests::updated_at.eq(iso8601::format(now)), )) .execute(connection)?; - insert_at( - connection, - others, - HttpItem { - kind: HttpItemKind::Request, - id: id.clone(), - }, - usize::MAX, - )?; + insert_at(connection, others, HttpItem { kind: HttpItemKind::Request, id: id.clone() }, usize::MAX)?; find_request(connection, &id)?.open(vault) } @@ -581,14 +528,7 @@ pub fn create_request_in( } if let Some(folder) = folder { let parent = placed.folder_id.as_deref(); - let created = insert_folder( - connection, - vault, - &placed.collection_id, - parent, - folder, - now, - )?; + let created = insert_folder(connection, vault, &placed.collection_id, parent, folder, now)?; placed.folder_id = Some(created.id); } insert_request(connection, vault, &placed, name, now) @@ -659,12 +599,8 @@ pub fn delete(connection: &mut Library, item: &HttpItem) -> Result<(), StorageEr HttpItemKind::Collection => { diesel::delete(http_collections::table.find(&item.id)).execute(connection)? } - HttpItemKind::Folder => { - diesel::delete(http_folders::table.find(&item.id)).execute(connection)? - } - HttpItemKind::Request => { - diesel::delete(http_requests::table.find(&item.id)).execute(connection)? - } + HttpItemKind::Folder => diesel::delete(http_folders::table.find(&item.id)).execute(connection)?, + HttpItemKind::Request => diesel::delete(http_requests::table.find(&item.id)).execute(connection)?, }; if deleted == 0 { return Err(not_found(&item.id)); @@ -673,10 +609,7 @@ pub fn delete(connection: &mut Library, item: &HttpItem) -> Result<(), StorageEr } /// Every folder below `folder_id`, at any depth, not counting it. -fn descendants( - connection: &mut SqliteConnection, - folder_id: &str, -) -> Result, StorageError> { +fn descendants(connection: &mut SqliteConnection, folder_id: &str) -> Result, StorageError> { let mut found: Vec = Vec::new(); let mut frontier = vec![folder_id.to_string()]; while !frontier.is_empty() { @@ -685,10 +618,7 @@ fn descendants( .select(http_folders::id) .load(connection)?; // A damaged library may name a folder its own ancestor: what was met is not walked again. - frontier = next - .into_iter() - .filter(|id| id != folder_id && !found.contains(id)) - .collect(); + frontier = next.into_iter().filter(|id| id != folder_id && !found.contains(id)).collect(); found.extend(frontier.iter().cloned()); } Ok(found) @@ -711,10 +641,7 @@ pub fn contents(connection: &mut Library, item: &HttpItem) -> Result { find_folder(connection, &item.id)?; @@ -739,11 +666,7 @@ pub fn contents(connection: &mut Library, item: &HttpItem) -> Result Result<(), StorageError> { +pub fn move_item(connection: &mut Library, item: &HttpItem, place: &HttpPlace) -> Result<(), StorageError> { connection.transaction(|connection, _| { let target_folder = place.folder_id.as_deref(); folder_of_collection(connection, &place.collection_id, target_folder)?; @@ -751,9 +674,7 @@ pub fn move_item( let (from_collection, from_folder) = match item.kind { HttpItemKind::Collection => { - return Err( - ValidationError::new("kind", "a collection is reordered, not moved").into(), - ); + return Err(ValidationError::new("kind", "a collection is reordered, not moved").into()); } HttpItemKind::Folder => { let folder = find_folder(connection, &item.id)?; @@ -761,11 +682,7 @@ pub fn move_item( if target_folder .is_some_and(|target| target == item.id || below.iter().any(|id| id == target)) { - return Err(ValidationError::new( - "folderId", - "a folder cannot move into itself", - ) - .into()); + return Err(ValidationError::new("folderId", "a folder cannot move into itself").into()); } if folder.collection_id != place.collection_id { let mut subtree = below; @@ -773,11 +690,9 @@ pub fn move_item( diesel::update(http_folders::table.filter(http_folders::id.eq_any(&subtree))) .set(http_folders::collection_id.eq(&place.collection_id)) .execute(connection)?; - diesel::update( - http_requests::table.filter(http_requests::folder_id.eq_any(&subtree)), - ) - .set(http_requests::collection_id.eq(&place.collection_id)) - .execute(connection)?; + diesel::update(http_requests::table.filter(http_requests::folder_id.eq_any(&subtree))) + .set(http_requests::collection_id.eq(&place.collection_id)) + .execute(connection)?; } diesel::update(http_folders::table.find(&item.id)) .set(http_folders::parent_id.eq(target_folder)) @@ -803,21 +718,14 @@ pub fn move_item( }) } -pub fn reorder_collection( - connection: &mut Library, - id: &str, - index: u32, -) -> Result<(), StorageError> { +pub fn reorder_collection(connection: &mut Library, id: &str, index: u32) -> Result<(), StorageError> { connection.transaction(|connection, _| { find_collection(connection, id)?; let order = collections_in_order(connection)?; insert_at( connection, order, - HttpItem { - kind: HttpItemKind::Collection, - id: id.to_string(), - }, + HttpItem { kind: HttpItemKind::Collection, id: id.to_string() }, usize::try_from(index).unwrap_or(usize::MAX), ) }) @@ -847,20 +755,14 @@ pub fn duplicate( )) .execute(connection)?; copy_children(connection, &item.id, None, &id, None, now)?; - let copy = HttpItem { - kind: HttpItemKind::Collection, - id, - }; + let copy = HttpItem { kind: HttpItemKind::Collection, id }; let order = collections_in_order(connection)?; place_after(connection, order, item, copy.clone())?; copy } HttpItemKind::Folder => { let source = find_folder(connection, &item.id)?; - let renamed = FolderRow { - name: sealed, - ..source.clone() - }; + let renamed = FolderRow { name: sealed, ..source.clone() }; let id = copy_folder( connection, &renamed, @@ -868,24 +770,14 @@ pub fn duplicate( source.parent_id.as_deref(), now, )?; - let copy = HttpItem { - kind: HttpItemKind::Folder, - id, - }; - let others = siblings( - connection, - &source.collection_id, - source.parent_id.as_deref(), - )?; + let copy = HttpItem { kind: HttpItemKind::Folder, id }; + let others = siblings(connection, &source.collection_id, source.parent_id.as_deref())?; place_after(connection, others, item, copy.clone())?; copy } HttpItemKind::Request => { let source = find_request(connection, &item.id)?; - let renamed = RequestRow { - name: sealed, - ..source.clone() - }; + let renamed = RequestRow { name: sealed, ..source.clone() }; let id = copy_request( connection, &renamed, @@ -893,15 +785,8 @@ pub fn duplicate( source.folder_id.as_deref(), now, )?; - let copy = HttpItem { - kind: HttpItemKind::Request, - id, - }; - let others = siblings( - connection, - &source.collection_id, - source.folder_id.as_deref(), - )?; + let copy = HttpItem { kind: HttpItemKind::Request, id }; + let others = siblings(connection, &source.collection_id, source.folder_id.as_deref())?; place_after(connection, others, item, copy.clone())?; copy } @@ -970,14 +855,7 @@ fn copy_folder( http_folders::created_at.eq(iso8601::format(now)), )) .execute(connection)?; - copy_children( - connection, - &source.collection_id, - Some(&source.id), - collection_id, - Some(&id), - now, - )?; + copy_children(connection, &source.collection_id, Some(&source.id), collection_id, Some(&id), now)?; Ok(id) } @@ -1014,25 +892,18 @@ fn copy_children( } fn open_settings(vault: &Vault, id: &str, sealed: &str) -> Result { - serde_json::from_str(&vault.open(sealed)?).map_err(|_| StorageError::CorruptRow { - id: id.to_string(), - field: "settings", - }) + serde_json::from_str(&vault.open(sealed)?) + .map_err(|_| StorageError::CorruptRow { id: id.to_string(), field: "settings" }) } /// A collection's or a folder's own settings, what its requests inherit. -pub fn settings( - connection: &mut Library, - item: &HttpItem, -) -> Result { +pub fn settings(connection: &mut Library, item: &HttpItem) -> Result { let (connection, vault) = connection.split(); let sealed = match item.kind { HttpItemKind::Collection => find_collection(connection, &item.id)?.settings, HttpItemKind::Folder => find_folder(connection, &item.id)?.settings, HttpItemKind::Request => { - return Err( - ValidationError::new("kind", "a request has no settings of its own").into(), - ); + return Err(ValidationError::new("kind", "a request has no settings of its own").into()); } }; open_settings(vault, &item.id, &sealed) @@ -1053,9 +924,7 @@ pub fn save_settings( .set(http_folders::settings.eq(sealed)) .execute(connection)?, HttpItemKind::Request => { - return Err( - ValidationError::new("kind", "a request has no settings of its own").into(), - ); + return Err(ValidationError::new("kind", "a request has no settings of its own").into()); } }; if changed == 0 { @@ -1095,11 +964,7 @@ pub fn inherited( )]; for folder in folders.into_iter().rev() { levels.push(( - HttpOrigin { - kind: HttpItemKind::Folder, - id: folder.id.clone(), - name: vault.open(&folder.name)?, - }, + HttpOrigin { kind: HttpItemKind::Folder, id: folder.id.clone(), name: vault.open(&folder.name)? }, open_settings(vault, &folder.id, &folder.settings)?, )); } diff --git a/crates/engine/src/http/transport.rs b/crates/engine/src/http/transport.rs index d26a3c28b..520b3cd2d 100644 --- a/crates/engine/src/http/transport.rs +++ b/crates/engine/src/http/transport.rs @@ -99,11 +99,7 @@ impl Transport { /// From the collection down: the nearest set wins. pub fn resolve<'a>(levels: impl IntoIterator) -> Transport { - levels - .into_iter() - .fold(Transport::default(), |transport, settings| { - transport.over(settings) - }) + levels.into_iter().fold(Transport::default(), Transport::over) } #[cfg(test)] @@ -160,10 +156,7 @@ mod tests { /// Under a tenth of a second is a slip of the keyboard, not a choice. #[test] fn a_timeout_too_short_to_mean_it_is_raised() { - let settings = TransportSettings { - timeout_ms: Some(5), - ..TransportSettings::default() - }; + let settings = TransportSettings { timeout_ms: Some(5), ..TransportSettings::default() }; assert_eq!(resolve([&settings]).timeout_ms, 100); } diff --git a/crates/engine/src/http/variables.rs b/crates/engine/src/http/variables.rs index fc930840f..acca364ae 100644 --- a/crates/engine/src/http/variables.rs +++ b/crates/engine/src/http/variables.rs @@ -61,13 +61,7 @@ const NESTING: usize = 8; /// Postman's names for a value made when the request leaves, a new one each time it is written: /// `{{$guid}}`. No level can set one, `$` being no letter of a name. -const DYNAMIC: &[&str] = &[ - "$guid", - "$randomUUID", - "$timestamp", - "$isoTimestamp", - "$randomInt", -]; +const DYNAMIC: &[&str] = &["$guid", "$randomUUID", "$timestamp", "$isoTimestamp", "$randomInt"]; #[must_use] pub fn is_dynamic(name: &str) -> bool { @@ -351,15 +345,8 @@ pub fn resolve( /// Every text of a request a `{{name}}` can stand in, in the order the editor shows them: what /// is sent from it, and nothing that is not. #[must_use] -pub fn texts<'a>( - kind: RequestKind, - document: &'a RequestDocument, - inherited: &'a Inherited, -) -> Vec<&'a str> { - let sent = |rows: &'a [KeyValue]| { - rows.iter() - .filter(|row| row.enabled && !row.key.trim().is_empty()) - }; +pub fn texts<'a>(kind: RequestKind, document: &'a RequestDocument, inherited: &'a Inherited) -> Vec<&'a str> { + let sent = |rows: &'a [KeyValue]| rows.iter().filter(|row| row.enabled && !row.key.trim().is_empty()); let mut texts: Vec<&str> = vec![&document.url]; for row in inherited .headers @@ -383,10 +370,7 @@ pub fn texts<'a>( } match kind { RequestKind::Graphql => { - texts.extend([ - document.graphql.query.as_str(), - document.graphql.variables.as_str(), - ]); + texts.extend([document.graphql.query.as_str(), document.graphql.variables.as_str()]); } RequestKind::Websocket => {} RequestKind::Http => match &document.body { @@ -415,26 +399,15 @@ mod tests { use crate::http::settings::{HttpOrigin, inherit}; fn variable(name: &str, value: &str) -> Variable { - Variable { - name: name.to_string(), - value: value.to_string(), - ..Variable::default() - } + Variable { name: name.to_string(), value: value.to_string(), ..Variable::default() } } fn secret(name: &str, value: &str) -> Variable { - Variable { - kind: VariableKind::Secret, - ..variable(name, value) - } + Variable { kind: VariableKind::Secret, ..variable(name, value) } } fn layer(scope: VariableScope, from: &str, variables: Vec) -> VariableLayer { - VariableLayer { - scope, - from: from.to_string(), - variables, - } + VariableLayer { scope, from: from.to_string(), variables } } fn resolver(variables: Vec) -> Resolver { @@ -442,51 +415,29 @@ mod tests { } fn row(key: &str, value: &str) -> KeyValue { - KeyValue { - key: key.to_string(), - value: value.to_string(), - ..KeyValue::default() - } + KeyValue { key: key.to_string(), value: value.to_string(), ..KeyValue::default() } } fn off(key: &str, value: &str) -> KeyValue { - KeyValue { - enabled: false, - ..row(key, value) - } + KeyValue { enabled: false, ..row(key, value) } } fn part(key: &str, value: &str, enabled: bool) -> FormPart { - FormPart { - enabled, - key: key.to_string(), - value: value.to_string(), - ..FormPart::default() - } + FormPart { enabled, key: key.to_string(), value: value.to_string(), ..FormPart::default() } } fn origin() -> HttpOrigin { - HttpOrigin { - kind: HttpItemKind::Collection, - id: "c-1".to_string(), - name: "Shop".to_string(), - } + HttpOrigin { kind: HttpItemKind::Collection, id: "c-1".to_string(), name: "Shop".to_string() } } /// What a collection hands down: a header and an auth. fn inherited(header: KeyValue, auth: RequestAuth) -> Inherited { - let settings = ContainerSettings { - auth, - headers: vec![header], - ..ContainerSettings::default() - }; + let settings = ContainerSettings { auth, headers: vec![header], ..ContainerSettings::default() }; inherit(&[(origin(), settings)]) } fn bearer(token: &str) -> RequestAuth { - RequestAuth::Bearer { - token: token.to_string(), - } + RequestAuth::Bearer { token: token.to_string() } } /// Braces around anything but a name are text; a dynamic value is a name too. @@ -519,21 +470,9 @@ mod tests { #[test] fn the_nearest_level_setting_a_name_wins_and_names_what_it_hides() { let layers = [ - layer( - VariableScope::Request, - "", - vec![variable("host", "request")], - ), - layer( - VariableScope::Folder, - "Auth", - vec![variable("host", "folder"), variable("user", "ada")], - ), - layer( - VariableScope::Environment, - "Prod", - vec![variable("host", "prod")], - ), + layer(VariableScope::Request, "", vec![variable("host", "request")]), + layer(VariableScope::Folder, "Auth", vec![variable("host", "folder"), variable("user", "ada")]), + layer(VariableScope::Environment, "Prod", vec![variable("host", "prod")]), layer(VariableScope::Globals, "", vec![variable("region", "eu")]), ]; @@ -544,15 +483,9 @@ mod tests { (host.value.as_str(), host.scope, host.from.as_deref()), ("request", VariableScope::Request, None) ); - assert_eq!( - host.shadows, - [VariableScope::Folder, VariableScope::Environment] - ); + assert_eq!(host.shadows, [VariableScope::Folder, VariableScope::Environment]); let user = resolver.get("user").unwrap(); - assert_eq!( - (user.scope, user.from.as_deref()), - (VariableScope::Folder, Some("Auth")) - ); + assert_eq!((user.scope, user.from.as_deref()), (VariableScope::Folder, Some("Auth"))); assert_eq!(resolver.get("region").unwrap().from, None); assert_eq!(resolver.get("missing"), None); } @@ -562,16 +495,10 @@ mod tests { #[test] fn a_row_switched_off_unnamed_or_faulty_is_left_out() { let near = vec![ - Variable { - enabled: false, - ..variable("off", "near") - }, + Variable { enabled: false, ..variable("off", "near") }, variable(" ", "nameless"), variable("bad name", "near"), - Variable { - kind: VariableKind::Number, - ..variable("count", "many") - }, + Variable { kind: VariableKind::Number, ..variable("count", "many") }, variable("twice", "first"), variable("twice", "second"), ]; @@ -597,10 +524,7 @@ mod tests { layer( VariableScope::Request, "", - vec![ - variable("url", "{{scheme}}://{{host}}"), - variable("me", "{{me}}!"), - ], + vec![variable("url", "{{scheme}}://{{host}}"), variable("me", "{{me}}!")], ), layer( VariableScope::Globals, @@ -614,14 +538,8 @@ mod tests { ]); assert_eq!(resolver.get("url").unwrap().value, "https://api.shop.test"); - assert_eq!( - resolver.get("me").unwrap().value, - format!("{{{{me}}}}{}", "!".repeat(NESTING + 1)) - ); - assert_eq!( - resolver.fill("{{url}}/{{unknown}}"), - "https://api.shop.test/{{unknown}}" - ); + assert_eq!(resolver.get("me").unwrap().value, format!("{{{{me}}}}{}", "!".repeat(NESTING + 1))); + assert_eq!(resolver.fill("{{url}}/{{unknown}}"), "https://api.shop.test/{{unknown}}"); } /// The spelling a scope is written in reads back as that scope. @@ -659,23 +577,12 @@ mod tests { layer( VariableScope::Request, "", - vec![ - secret("token", "{{prefix}}-42"), - secret("empty", ""), - variable("prefix", "tk"), - ], - ), - layer( - VariableScope::Globals, - "", - vec![secret("token", "hidden by the request")], + vec![secret("token", "{{prefix}}-42"), secret("empty", ""), variable("prefix", "tk")], ), + layer(VariableScope::Globals, "", vec![secret("token", "hidden by the request")]), ]); - assert_eq!( - resolver.secrets(), - [("token".to_string(), "tk-42".to_string())] - ); + assert_eq!(resolver.secrets(), [("token".to_string(), "tk-42".to_string())]); } /// What the editor lists under a request: each name once, with what it resolves to. @@ -687,20 +594,11 @@ mod tests { let shown: Vec<(&str, Option)> = used .iter() - .map(|used| { - ( - used.name.as_str(), - used.resolved.as_ref().map(|found| found.scope), - ) - }) + .map(|used| (used.name.as_str(), used.resolved.as_ref().map(|found| found.scope))) .collect(); assert_eq!( shown, - [ - ("host", Some(VariableScope::Request)), - ("id", None), - ("$guid", Some(VariableScope::Dynamic)), - ] + [("host", Some(VariableScope::Request)), ("id", None), ("$guid", Some(VariableScope::Dynamic)),] ); } @@ -729,30 +627,17 @@ mod tests { let resolver = resolver(vec![variable("v", "1")]); let bodies = |v: &str| { [ - RequestBody::Json { - text: v.to_string(), - }, - RequestBody::Text { - text: v.to_string(), - }, - RequestBody::Form { - fields: vec![row(v, v)], - }, - RequestBody::Multipart { - parts: vec![part(v, v, true)], - }, - RequestBody::Binary { - path: v.to_string(), - }, + RequestBody::Json { text: v.to_string() }, + RequestBody::Text { text: v.to_string() }, + RequestBody::Form { fields: vec![row(v, v)] }, + RequestBody::Multipart { parts: vec![part(v, v, true)] }, + RequestBody::Binary { path: v.to_string() }, RequestBody::None, ] }; for (body, expected) in bodies("{{v}}").into_iter().zip(bodies(&ones("{{v}}"))) { - let document = RequestDocument { - body, - ..RequestDocument::default() - }; + let document = RequestDocument { body, ..RequestDocument::default() }; let (sent, _) = resolve(&document, &inherit(&[]), &resolver); @@ -766,25 +651,15 @@ mod tests { let resolver = resolver(vec![variable("v", "1")]); let auths = |v: &str| { [ - RequestAuth::Basic { - username: v.to_string(), - password: v.to_string(), - }, + RequestAuth::Basic { username: v.to_string(), password: v.to_string() }, bearer(v), - RequestAuth::ApiKey { - name: v.to_string(), - value: v.to_string(), - place: KeyPlace::Query, - }, + RequestAuth::ApiKey { name: v.to_string(), value: v.to_string(), place: KeyPlace::Query }, RequestAuth::None, ] }; for (auth, expected) in auths("{{v}}").into_iter().zip(auths("1")) { - let document = RequestDocument { - auth: auth.clone(), - ..RequestDocument::default() - }; + let document = RequestDocument { auth: auth.clone(), ..RequestDocument::default() }; let (sent, handed) = resolve(&document, &inherited(row("H", "h"), auth), &resolver); @@ -810,14 +685,8 @@ mod tests { let (sent, handed) = resolve(&document, &handed, &resolver); assert_eq!(sent.url, "https://1"); - assert_eq!( - (sent.params, sent.headers), - (vec![row("1", "1")], vec![row("1", "1")]) - ); - assert_eq!( - (sent.graphql.query.as_str(), sent.graphql.variables.as_str()), - ("1", "1") - ); + assert_eq!((sent.params, sent.headers), (vec![row("1", "1")], vec![row("1", "1")])); + assert_eq!((sent.graphql.query.as_str(), sent.graphql.variables.as_str()), ("1", "1")); assert_eq!(handed.headers[0].header, row("X-1", "1")); } @@ -828,9 +697,7 @@ mod tests { let mut document = RequestDocument { url: "u".to_string(), headers: vec![row("Own", "o"), off("Off", "x"), row(" ", "unnamed")], - body: RequestBody::Json { - text: "body".to_string(), - }, + body: RequestBody::Json { text: "body".to_string() }, ..RequestDocument::default() }; document.graphql.query = "query".to_string(); @@ -841,10 +708,7 @@ mod tests { let websocket = texts(RequestKind::Websocket, &document, &handed); assert_eq!(http, ["u", "Inh", "i", "Own", "o", "inherited", "body"]); - assert_eq!( - graphql, - ["u", "Inh", "i", "Own", "o", "inherited", "query", "vars"] - ); + assert_eq!(graphql, ["u", "Inh", "i", "Own", "o", "inherited", "query", "vars"]); assert_eq!(websocket, ["u", "Inh", "i", "Own", "o", "inherited"]); } @@ -853,27 +717,14 @@ mod tests { fn each_body_and_auth_gives_the_texts_it_sends() { let none = inherit(&[]); let cases: [(RequestBody, RequestAuth, &[&str]); 6] = [ + (RequestBody::Text { text: "t".to_string() }, RequestAuth::None, &["t"]), ( - RequestBody::Text { - text: "t".to_string(), - }, - RequestAuth::None, - &["t"], - ), - ( - RequestBody::Form { - fields: vec![row("k", "v"), off("x", "y")], - }, - RequestAuth::Basic { - username: "u".to_string(), - password: "p".to_string(), - }, + RequestBody::Form { fields: vec![row("k", "v"), off("x", "y")] }, + RequestAuth::Basic { username: "u".to_string(), password: "p".to_string() }, &["u", "p", "k", "v"], ), ( - RequestBody::Multipart { - parts: vec![part("k", "v", true), part("x", "y", false)], - }, + RequestBody::Multipart { parts: vec![part("k", "v", true), part("x", "y", false)] }, RequestAuth::ApiKey { name: "n".to_string(), value: "a".to_string(), @@ -881,22 +732,12 @@ mod tests { }, &["n", "a", "k", "v"], ), - ( - RequestBody::Binary { - path: "f".to_string(), - }, - bearer("b"), - &["b", "f"], - ), + (RequestBody::Binary { path: "f".to_string() }, bearer("b"), &["b", "f"]), (RequestBody::None, RequestAuth::Inherit, &[]), (RequestBody::None, RequestAuth::None, &[]), ]; for (body, auth, expected) in cases { - let document = RequestDocument { - body, - auth, - ..RequestDocument::default() - }; + let document = RequestDocument { body, auth, ..RequestDocument::default() }; let found = texts(RequestKind::Http, &document, &none); diff --git a/crates/engine/src/http/websocket.rs b/crates/engine/src/http/websocket.rs index c8a03477c..ad65976dc 100644 --- a/crates/engine/src/http/websocket.rs +++ b/crates/engine/src/http/websocket.rs @@ -116,12 +116,8 @@ pub fn socket_url(typed: &str) -> Result { match scheme.to_ascii_lowercase().as_str() { "wss" => Ok(format!("https://{rest}")), "ws" => Ok(format!("http://{rest}")), - "https" => Err(SendError::SocketScheme { - twin: Some(format!("wss://{rest}")), - }), - "http" => Err(SendError::SocketScheme { - twin: Some(format!("ws://{rest}")), - }), + "https" => Err(SendError::SocketScheme { twin: Some(format!("wss://{rest}")) }), + "http" => Err(SendError::SocketScheme { twin: Some(format!("ws://{rest}")) }), _ => Err(SendError::SocketScheme { twin: None }), } } @@ -164,8 +160,7 @@ fn failure(error: &tungstenite::Error, timeout: Option<&Limit>) -> SendError { /// The system's verifier, or with « verify TLS » off any certificate, as a request takes it. fn tls_config(verify: bool) -> Result { if verify { - return ClientConfig::with_platform_verifier() - .map_err(|error| SendError::Tls(error.to_string())); + return ClientConfig::with_platform_verifier().map_err(|error| SendError::Tls(error.to_string())); } let provider = CryptoProvider::get_default() .cloned() @@ -228,11 +223,7 @@ impl ServerCertVerifier for AnyCertificate { } fn emit(events: &dyn EventSink, id: &str, event: SocketEvent) { - events.emit(EngineEvent::Socket(WebsocketEvent { - id: id.to_string(), - at: Utc::now(), - event, - })); + events.emit(EngineEvent::Socket(WebsocketEvent { id: id.to_string(), at: Utc::now(), event })); } impl Sockets { @@ -256,8 +247,8 @@ impl Sockets { for (key, value) in &outgoing.headers { let name = tungstenite::http::HeaderName::from_bytes(key.as_bytes()) .map_err(|error| SendError::Network(error.to_string()))?; - let value = HeaderValue::from_str(value) - .map_err(|error| SendError::Network(error.to_string()))?; + let value = + HeaderValue::from_str(value).map_err(|error| SendError::Network(error.to_string()))?; request.headers_mut().insert(name, value); } let protocols: Vec<&str> = protocols @@ -268,19 +259,12 @@ impl Sockets { if !protocols.is_empty() { let value = HeaderValue::from_str(&protocols.join(", ")) .map_err(|error| SendError::Network(error.to_string()))?; - request - .headers_mut() - .insert("Sec-WebSocket-Protocol", value); + request.headers_mut().insert("Sec-WebSocket-Protocol", value); } let tls = tls_config(outgoing.transport.verify_tls)?; let (stream, response) = tokio::time::timeout( Duration::from_millis(u64::from(timeout.value)), - connect_async_tls_with_config( - request, - None, - false, - Some(Connector::Rustls(Arc::new(tls))), - ), + connect_async_tls_with_config(request, None, false, Some(Connector::Rustls(Arc::new(tls)))), ) .await .map_err(|_| SendError::Timeout(timeout.clone()))? @@ -296,13 +280,7 @@ impl Sockets { let (outbound, inbound) = mpsc::unbounded_channel(); let task = runtime.spawn(run(events, id.clone(), stream, inbound)); if let Ok(mut open) = self.open.lock() - && let Some(previous) = open.insert( - id, - Socket { - outbound, - task: task.abort_handle(), - }, - ) + && let Some(previous) = open.insert(id, Socket { outbound, task: task.abort_handle() }) { previous.task.abort(); } @@ -314,10 +292,7 @@ impl Sockets { self.open .lock() .ok() - .and_then(|open| { - open.get(id) - .map(|socket| socket.outbound.send(Outbound::Text(text)).is_ok()) - }) + .and_then(|open| open.get(id).map(|socket| socket.outbound.send(Outbound::Text(text)).is_ok())) .unwrap_or(false) } @@ -346,8 +321,7 @@ impl Sockets { } } -type Stream = - tokio_tungstenite::WebSocketStream>; +type Stream = tokio_tungstenite::WebSocketStream>; async fn run( events: Arc, @@ -424,9 +398,7 @@ async fn run( fn closed(frame: Option<&CloseFrame>) -> SocketEvent { SocketEvent::Closed { code: frame.map(|frame| u16::from(frame.code)), - reason: frame - .map(|frame| frame.reason.to_string()) - .unwrap_or_default(), + reason: frame.map(|frame| frame.reason.to_string()).unwrap_or_default(), } } @@ -440,28 +412,15 @@ mod tests { #[test] fn a_socket_url_is_checked_as_http_or_refused_with_its_twin() { for (typed, checked) in [ - ( - " wss://echo.test/live?x=1 ", - Ok("https://echo.test/live?x=1".to_string()), - ), + (" wss://echo.test/live?x=1 ", Ok("https://echo.test/live?x=1".to_string())), ("WS://echo.test", Ok("http://echo.test".to_string())), ("echo.test:8080/", Ok("echo.test:8080/".to_string())), ( "https://echo.test/a", - Err(SendError::SocketScheme { - twin: Some("wss://echo.test/a".to_string()), - }), - ), - ( - "Http://echo.test", - Err(SendError::SocketScheme { - twin: Some("ws://echo.test".to_string()), - }), - ), - ( - "ftp://echo.test", - Err(SendError::SocketScheme { twin: None }), + Err(SendError::SocketScheme { twin: Some("wss://echo.test/a".to_string()) }), ), + ("Http://echo.test", Err(SendError::SocketScheme { twin: Some("ws://echo.test".to_string()) })), + ("ftp://echo.test", Err(SendError::SocketScheme { twin: None })), ] { assert_eq!(socket_url(typed), checked, "{typed}"); } @@ -470,8 +429,7 @@ mod tests { /// Stored with the request: a document written before a field existed still opens. #[test] fn a_websocket_document_written_before_its_fields_still_opens() { - let document: WebsocketDocument = - serde_json::from_str(r#"{"protocols":["chat"]}"#).unwrap(); + let document: WebsocketDocument = serde_json::from_str(r#"{"protocols":["chat"]}"#).unwrap(); assert_eq!(document.protocols, ["chat"]); assert!(document.messages.is_empty()); diff --git a/crates/engine/src/index.rs b/crates/engine/src/index.rs index 026ab377f..ae276d578 100644 --- a/crates/engine/src/index.rs +++ b/crates/engine/src/index.rs @@ -43,15 +43,7 @@ impl IndexedNote { impl Drop for IndexedNote { fn drop(&mut self) { - let Note { - title, - content, - source, - tags, - items, - placeholder_values, - .. - } = &mut self.note; + let Note { title, content, source, tags, items, placeholder_values, .. } = &mut self.note; title.zeroize(); content.zeroize(); source.zeroize(); @@ -60,13 +52,7 @@ impl Drop for IndexedNote { item.text.zeroize(); } wipe_values(placeholder_values); - let Folded { - title, - tags, - content, - items, - source, - } = &mut self.folded; + let Folded { title, tags, content, items, source } = &mut self.folded; title.zeroize(); tags.zeroize(); content.zeroize(); @@ -84,10 +70,7 @@ fn wipe_values(values: &mut BTreeMap) { /// What a write touched, for the index to read again (`Engine::write`). #[derive(Debug, Default)] -#[allow( - clippy::struct_excessive_bools, - reason = "one flag a decoration the index keeps, read again whole" -)] +#[allow(clippy::struct_excessive_bools, reason = "one flag a decoration the index keeps, read again whole")] pub struct Changed { /// Notes whose row or side tables changed; one no longer live leaves the index. pub notes: Vec, @@ -100,17 +83,11 @@ pub struct Changed { impl Changed { pub fn notes(ids: impl IntoIterator) -> Self { - Self { - notes: ids.into_iter().collect(), - ..Self::default() - } + Self { notes: ids.into_iter().collect(), ..Self::default() } } pub fn everything() -> Self { - Self { - rebuild: true, - ..Self::default() - } + Self { rebuild: true, ..Self::default() } } } @@ -191,11 +168,7 @@ impl NoteIndex { /// Reads again what `changed` names. An index not started on `library` has nothing to /// keep true: the next read builds it whole. - pub(crate) fn refresh( - &mut self, - library: &mut Library, - changed: &Changed, - ) -> Result<(), StorageError> { + pub(crate) fn refresh(&mut self, library: &mut Library, changed: &Changed) -> Result<(), StorageError> { if self.library != Some(library.number()) { return Ok(()); } @@ -220,8 +193,7 @@ impl NoteIndex { self.notes.remove(id); } for note in fresh { - self.notes - .insert(note.id.clone(), Arc::new(IndexedNote::of(note))); + self.notes.insert(note.id.clone(), Arc::new(IndexedNote::of(note))); } self.counted.get_mut().clear(); } @@ -238,10 +210,7 @@ impl NoteIndex { } let mut fresh = Self::default(); fresh.start(library).map_err(|error| error.to_string())?; - while fresh - .next_slice(library) - .map_err(|error| error.to_string())? - {} + while fresh.next_slice(library).map_err(|error| error.to_string())? {} let mut ids: Vec<&String> = self.notes.keys().collect(); let mut expected: Vec<&String> = fresh.notes.keys().collect(); @@ -299,13 +268,8 @@ impl NoteIndex { .values() .filter(|entry| { let note = &entry.note; - query - .space_id - .as_ref() - .is_none_or(|space| ¬e.space_id == space) - && folders.is_none_or(|ids| { - note.folder_id.as_ref().is_some_and(|id| ids.contains(id)) - }) + query.space_id.as_ref().is_none_or(|space| ¬e.space_id == space) + && folders.is_none_or(|ids| note.folder_id.as_ref().is_some_and(|id| ids.contains(id))) && criteria.passes_rails(note) }) .collect(); @@ -342,9 +306,8 @@ impl NoteIndex { .filter(|note| space_id.is_none_or(|space| note.space_id == space)); for note in notes { for tag in ¬e.tags { - let (spelling, count) = tags - .entry(tag.to_ascii_lowercase()) - .or_insert_with(|| (tag.clone(), 0)); + let (spelling, count) = + tags.entry(tag.to_ascii_lowercase()).or_insert_with(|| (tag.clone(), 0)); if tag < spelling { spelling.clone_from(tag); } @@ -357,10 +320,7 @@ impl NoteIndex { *priorities.entry(note.priority.as_str()).or_default() += 1; } let rows = |counts: HashMap<&str, i64>| -> Vec<(String, i64)> { - counts - .into_iter() - .map(|(value, count)| (value.to_string(), count)) - .collect() + counts.into_iter().map(|(value, count)| (value.to_string(), count)).collect() }; Facets { tags: view::count_tags(tags.into_values().collect()), @@ -410,9 +370,7 @@ pub(crate) fn search(entries: &[&Arc], needle: &str) -> Vec { } entries .par_iter() - .filter_map(|entry| { - view::answers(&entry.note, &entry.folded, needle).map(|hit| card(entry, hit)) - }) + .filter_map(|entry| view::answers(&entry.note, &entry.folded, needle).map(|hit| card(entry, hit))) .collect() } @@ -498,9 +456,7 @@ mod tests { fn shelf() -> Shelf { let mut library = open_in_memory().unwrap(); - let space = crate::spaces::store::create(&mut library, "Work") - .unwrap() - .id; + let space = crate::spaces::store::create(&mut library, "Work").unwrap().id; Shelf { library, space } } @@ -535,9 +491,7 @@ mod tests { } fn written(&mut self, draft: NoteDraft) -> String { - store::create(&mut self.library, draft, minutes(0)) - .unwrap() - .id + store::create(&mut self.library, draft, minutes(0)).unwrap().id } fn full_index(&mut self) -> NoteIndex { @@ -548,11 +502,7 @@ mod tests { } fn titles(index: &NoteIndex) -> Vec { - let mut titles: Vec = index - .notes - .values() - .map(|entry| entry.note.title.clone()) - .collect(); + let mut titles: Vec = index.notes.values().map(|entry| entry.note.title.clone()).collect(); titles.sort(); titles } @@ -576,11 +526,7 @@ mod tests { } } - fn selected( - index: &NoteIndex, - request: &NotesQuery, - folders: Option<&HashSet>, - ) -> Vec { + fn selected(index: &NoteIndex, request: &NotesQuery, folders: Option<&HashSet>) -> Vec { index .select(request, folders) .0 @@ -637,9 +583,7 @@ mod tests { let mut index = NoteIndex::default(); index.start(&mut shelf.library).unwrap(); - let answers: Vec = (0..3) - .map(|_| index.next_slice(&mut shelf.library).unwrap()) - .collect(); + let answers: Vec = (0..3).map(|_| index.next_slice(&mut shelf.library).unwrap()).collect(); assert_eq!(answers, [true, true, false]); assert!(index.is_complete()); @@ -735,10 +679,7 @@ mod tests { let edited = shelf.note("before", 0); let trashed = shelf.note("trashed", 0); let mut index = shelf.full_index(); - let retitle = NotePatch { - title: Some("after".into()), - ..NotePatch::default() - }; + let retitle = NotePatch { title: Some("after".into()), ..NotePatch::default() }; store::update(&mut shelf.library, &edited, &retitle, minutes(1)).unwrap(); store::trash::trash(&mut shelf.library, &trashed, minutes(1)).unwrap(); let created = shelf.note("new", 2); @@ -756,8 +697,7 @@ mod tests { let id = shelf.note("a", 0); let mut index = shelf.full_index(); let space = shelf.space.clone(); - crate::folders::store::create(&mut shelf.library, &space, None, "Infra", minutes(1)) - .unwrap(); + crate::folders::store::create(&mut shelf.library, &space, None, "Infra", minutes(1)).unwrap(); store::replace_global_placeholder_values( &mut shelf.library, &[("host".to_string(), "db".to_string())].into(), @@ -774,12 +714,7 @@ mod tests { let (db, vault) = shelf.library.split(); crate::attachments::store::create(db, vault, &attachment).unwrap(); - let changed = Changed { - attachments: true, - folders: true, - globals: true, - ..Changed::default() - }; + let changed = Changed { attachments: true, folders: true, globals: true, ..Changed::default() }; index.refresh(&mut shelf.library, &changed).unwrap(); let decorations = index.decorations(); @@ -795,9 +730,7 @@ mod tests { shelf.note("a", 0); let mut index = shelf.full_index(); - index - .refresh(&mut shelf.library, &Changed::everything()) - .unwrap(); + index.refresh(&mut shelf.library, &Changed::everything()).unwrap(); assert!(index.is_empty()); assert!(!index.is_complete()); @@ -810,9 +743,7 @@ mod tests { let mut second = shelf(); let mut index = first.full_index(); - index - .refresh(&mut second.library, &Changed::everything()) - .unwrap(); + index.refresh(&mut second.library, &Changed::everything()).unwrap(); assert_eq!(index.len(), 1); } @@ -822,17 +753,11 @@ mod tests { let mut shelf = shelf(); let id = shelf.note("before", 0); let index = shelf.full_index(); - let retitle = NotePatch { - title: Some("after".into()), - ..NotePatch::default() - }; + let retitle = NotePatch { title: Some("after".into()), ..NotePatch::default() }; store::update(&mut shelf.library, &id, &retitle, minutes(1)).unwrap(); let mut other = self::shelf(); - assert_eq!( - index.matches(&mut shelf.library), - Err(format!("note {id} differs")) - ); + assert_eq!(index.matches(&mut shelf.library), Err(format!("note {id} differs"))); assert_eq!(index.matches(&mut other.library), Ok(())); } @@ -843,12 +768,8 @@ mod tests { let space = shelf.space.clone(); let index = shelf.full_index(); - crate::folders::store::create(&mut shelf.library, &space, None, "Infra", minutes(1)) - .unwrap(); - assert_eq!( - index.matches(&mut shelf.library), - Err("folders differ".to_string()) - ); + crate::folders::store::create(&mut shelf.library, &space, None, "Infra", minutes(1)).unwrap(); + assert_eq!(index.matches(&mut shelf.library), Err("folders differ".to_string())); let index = shelf.full_index(); store::replace_global_placeholder_values( @@ -856,10 +777,7 @@ mod tests { &[("host".to_string(), "db".to_string())].into(), ) .unwrap(); - assert_eq!( - index.matches(&mut shelf.library), - Err("global values differ".to_string()) - ); + assert_eq!(index.matches(&mut shelf.library), Err("global values differ".to_string())); let index = shelf.full_index(); let attachment = Attachment { @@ -872,10 +790,7 @@ mod tests { }; let (db, vault) = shelf.library.split(); crate::attachments::store::create(db, vault, &attachment).unwrap(); - assert_eq!( - index.matches(&mut shelf.library), - Err("attachment counts differ".to_string()) - ); + assert_eq!(index.matches(&mut shelf.library), Err("attachment counts differ".to_string())); } #[test] @@ -885,12 +800,7 @@ mod tests { let index = shelf.full_index(); shelf.note("b", 1); - assert!( - index - .matches(&mut shelf.library) - .unwrap_err() - .starts_with("notes ") - ); + assert!(index.matches(&mut shelf.library).unwrap_err().starts_with("notes ")); } // --- Reading it. @@ -899,13 +809,8 @@ mod tests { fn a_selection_keeps_the_space_and_runs_from_the_last_edit_then_the_id() { let mut shelf = shelf(); shelf.note("old", 0); - let mut tie = [ - (shelf.note("b-new", 5), "b-new"), - (shelf.note("a-new", 5), "a-new"), - ]; - let elsewhere = crate::spaces::store::create(&mut shelf.library, "Home") - .unwrap() - .id; + let mut tie = [(shelf.note("b-new", 5), "b-new"), (shelf.note("a-new", 5), "a-new")]; + let elsewhere = crate::spaces::store::create(&mut shelf.library, "Home").unwrap().id; shelf.written(draft(&elsewhere, "home")); let index = shelf.full_index(); let space = shelf.space.clone(); @@ -920,26 +825,15 @@ mod tests { fn a_selection_keeps_the_notes_filed_in_the_folders_given_and_the_rails() { let mut shelf = shelf(); let space = shelf.space.clone(); - let folder = - crate::folders::store::create(&mut shelf.library, &space, None, "Infra", minutes(0)) - .unwrap() - .id; - shelf.written(NoteDraft { - folder_id: Some(folder.clone()), - pinned: true, - ..draft(&space, "filed") - }); + let folder = crate::folders::store::create(&mut shelf.library, &space, None, "Infra", minutes(0)) + .unwrap() + .id; + shelf.written(NoteDraft { folder_id: Some(folder.clone()), pinned: true, ..draft(&space, "filed") }); shelf.written(draft(&space, "loose")); let index = shelf.full_index(); - let pinned = NotesQuery { - filter: NoteFilter::Pinned, - ..query(None) - }; + let pinned = NotesQuery { filter: NoteFilter::Pinned, ..query(None) }; - assert_eq!( - selected(&index, &query(None), Some(&[folder].into())), - ["filed"] - ); + assert_eq!(selected(&index, &query(None), Some(&[folder].into())), ["filed"]); assert_eq!(selected(&index, &pinned, None), ["filed"]); } @@ -947,43 +841,22 @@ mod tests { fn facets_count_the_space_s_notes_by_folded_tag_alike_but_for_case_as_one() { let mut shelf = shelf(); let space = shelf.space.clone(); - shelf.written(NoteDraft { - tags: vec!["ops".into()], - ..draft(&space, "a") - }); + shelf.written(NoteDraft { tags: vec!["ops".into()], ..draft(&space, "a") }); shelf.written(NoteDraft { tags: vec!["OPS".into(), "ci".into()], kind: NoteKind::Note, ..draft(&space, "b") }); - let elsewhere = crate::spaces::store::create(&mut shelf.library, "Home") - .unwrap() - .id; - shelf.written(NoteDraft { - tags: vec!["home".into()], - ..draft(&elsewhere, "c") - }); + let elsewhere = crate::spaces::store::create(&mut shelf.library, "Home").unwrap().id; + shelf.written(NoteDraft { tags: vec!["home".into()], ..draft(&elsewhere, "c") }); let index = shelf.full_index(); let facets = index.facets(Some(&space)); - let tags: Vec<_> = facets - .tags - .iter() - .map(|tag| (tag.value.as_str(), tag.count)) - .collect(); + let tags: Vec<_> = facets.tags.iter().map(|tag| (tag.value.as_str(), tag.count)).collect(); assert_eq!(tags, [("ci", 1), ("OPS", 2)]); - assert_eq!( - facets.languages, - view::count_languages(&[("sh".to_string(), 1)]) - ); - assert_eq!( - facets.kinds[1], - view::FacetCount { - value: NoteKind::Note, - count: 1 - } - ); + assert_eq!(facets.languages, view::count_languages(&[("sh".to_string(), 1)])); + assert_eq!(facets.kinds[1], view::FacetCount { value: NoteKind::Note, count: 1 }); assert_eq!(index.facets(None).tags.len(), 3); } @@ -993,15 +866,10 @@ mod tests { let id = shelf.note("a", 0); let mut index = shelf.full_index(); assert!(index.facets(None).tags.is_empty()); - let tag = NotePatch { - tags: Some(vec!["ops".into()]), - ..NotePatch::default() - }; + let tag = NotePatch { tags: Some(vec!["ops".into()]), ..NotePatch::default() }; store::update(&mut shelf.library, &id, &tag, minutes(1)).unwrap(); - index - .refresh(&mut shelf.library, &Changed::notes([id])) - .unwrap(); + index.refresh(&mut shelf.library, &Changed::notes([id])).unwrap(); assert_eq!(index.facets(None).tags[0].value, "ops"); } @@ -1016,10 +884,7 @@ mod tests { store::update( &mut shelf.library, "ed, - &NotePatch { - content: Some("psql -h db".into()), - ..NotePatch::default() - }, + &NotePatch { content: Some("psql -h db".into()), ..NotePatch::default() }, minutes(0), ) .unwrap(); @@ -1043,10 +908,7 @@ mod tests { let id = shelf.note("a", 0); let index = shelf.full_index(); - assert_eq!( - index.get(&id).map(|entry| entry.note.title.as_str()), - Some("a") - ); + assert_eq!(index.get(&id).map(|entry| entry.note.title.as_str()), Some("a")); assert!(index.get("missing").is_none()); } @@ -1087,16 +949,8 @@ mod tests { .map(|step| step.detail) .collect(); - assert!( - plan.iter().any(|step| step.contains("notes_updated_at")), - "{plan:?}" - ); - assert!( - !plan - .iter() - .any(|step| step == "USE TEMP B-TREE FOR ORDER BY"), - "{plan:?}" - ); + assert!(plan.iter().any(|step| step.contains("notes_updated_at")), "{plan:?}"); + assert!(!plan.iter().any(|step| step == "USE TEMP B-TREE FOR ORDER BY"), "{plan:?}"); } /// Nothing of the index reaches the disk, and what it held is wiped when it goes. diff --git a/crates/engine/src/index/oracle.rs b/crates/engine/src/index/oracle.rs index 855c520e0..95d99f449 100644 --- a/crates/engine/src/index/oracle.rs +++ b/crates/engine/src/index/oracle.rs @@ -15,9 +15,7 @@ use crate::notes::kind::NoteKind; use crate::notes::language::Language; use crate::notes::model::{NoteDraft, NoteLifecycle, NotePatch}; use crate::notes::priority::Priority; -use crate::notes::view::{ - Grouping, NoteFilter, NoteOrder, NotesQuery, NotesView, SortDirection, SortKey, -}; +use crate::notes::view::{Grouping, NoteFilter, NoteOrder, NotesQuery, NotesView, SortDirection, SortKey}; use crate::spaces::model::SpaceDraft; use crate::{Engine, Paths, RecordingSink, folders, notes, spaces}; @@ -51,29 +49,15 @@ struct World { impl World { fn new(seed: u64) -> Self { - let runtime = tokio::runtime::Builder::new_current_thread() - .build() - .unwrap(); - let paths = Paths { - profile: std::env::temp_dir(), - }; - let engine = Arc::new(Engine::new( - paths, - Arc::new(RecordingSink::default()), - runtime.handle().clone(), - )); + let runtime = tokio::runtime::Builder::new_current_thread().build().unwrap(); + let paths = Paths { profile: std::env::temp_dir() }; + let engine = + Arc::new(Engine::new(paths, Arc::new(RecordingSink::default()), runtime.handle().clone())); *engine.db.lock().unwrap() = Some(open_in_memory().unwrap()); - let mut world = Self { - _runtime: runtime, - engine, - spaces: Vec::new(), - folders: Vec::new(), - dice: Dice(seed), - }; + let mut world = + Self { _runtime: runtime, engine, spaces: Vec::new(), folders: Vec::new(), dice: Dice(seed) }; for name in ["Perso", "Travail"] { - let draft = SpaceDraft { - name: name.to_string(), - }; + let draft = SpaceDraft { name: name.to_string() }; let id = spaces::create_space(&world.engine, &draft).unwrap().id; world.spaces.push(id); } @@ -87,11 +71,8 @@ impl World { } fn folder(&mut self, name: &str, space: usize) { - let draft = FolderDraft { - space_id: self.spaces[space].clone(), - name: name.to_string(), - parent_id: None, - }; + let draft = + FolderDraft { space_id: self.spaces[space].clone(), name: name.to_string(), parent_id: None }; let id = folders::create_folder(&self.engine, &draft).unwrap().id; self.folders.push(id); } @@ -106,9 +87,7 @@ impl World { space_id: self.dice.pick(&self.spaces).clone(), folder_id: None, title: self.text(), - language: *self - .dice - .pick(&[Language::Txt, Language::Sql, Language::Py]), + language: *self.dice.pick(&[Language::Txt, Language::Sql, Language::Py]), content: if kind == NoteKind::Checklist { String::new() } else { @@ -118,19 +97,14 @@ impl World { tags: vec![(*self.dice.pick(&TAGS)).to_string()], pinned: self.dice.roll(3) == 0, lifecycle: if self.dice.roll(4) == 0 { - NoteLifecycle::Expires { - at: at(NOW) + TimeDelta::days(3), - } + NoteLifecycle::Expires { at: at(NOW) + TimeDelta::days(3) } } else { NoteLifecycle::Permanent }, kind, priority: *self.dice.pick(&Priority::ALL), items: if kind == NoteKind::Checklist { - vec![ChecklistItem { - text: self.text(), - done: false, - }] + vec![ChecklistItem { text: self.text(), done: false }] } else { Vec::new() }, @@ -172,11 +146,7 @@ impl World { 2 => drop(notes::tag_notes(&engine, &one, &[tag])), 3 => drop(notes::remove_tag(&engine, &one, tag)), 4 => drop(notes::set_pinned(&engine, &one, self.dice.roll(2) == 0)), - 5 => drop(notes::set_priority( - &engine, - &one, - *self.dice.pick(&Priority::ALL), - )), + 5 => drop(notes::set_priority(&engine, &one, *self.dice.pick(&Priority::ALL))), 6 => drop(notes::delete_notes(&engine, &one)), 7 => { let space = self.dice.pick(&self.spaces).clone(); @@ -213,29 +183,15 @@ impl World { space_id, folder_id, search: (*self.dice.pick(&NEEDLES)).to_string(), - filter: *self - .dice - .pick(&[NoteFilter::All, NoteFilter::Pinned, NoteFilter::Untriaged]), + filter: *self.dice.pick(&[NoteFilter::All, NoteFilter::Pinned, NoteFilter::Untriaged]), tags: if self.dice.roll(4) == 0 { vec![(*self.dice.pick(&TAGS)).to_string()] } else { Vec::new() }, - languages: if self.dice.roll(6) == 0 { - vec![Language::Sql] - } else { - Vec::new() - }, - kinds: if self.dice.roll(6) == 0 { - vec![NoteKind::Checklist] - } else { - Vec::new() - }, - priorities: if self.dice.roll(6) == 0 { - vec![Priority::High] - } else { - Vec::new() - }, + languages: if self.dice.roll(6) == 0 { vec![Language::Sql] } else { Vec::new() }, + kinds: if self.dice.roll(6) == 0 { vec![NoteKind::Checklist] } else { Vec::new() }, + priorities: if self.dice.roll(6) == 0 { vec![Priority::High] } else { Vec::new() }, order: NoteOrder { key: *self.dice.pick(&[ SortKey::Modified, @@ -244,9 +200,7 @@ impl World { SortKey::Format, SortKey::Title, ]), - direction: *self - .dice - .pick(&[SortDirection::Descending, SortDirection::Ascending]), + direction: *self.dice.pick(&[SortDirection::Descending, SortDirection::Ascending]), }, grouping: *self.dice.pick(&[ Grouping::Date, @@ -269,11 +223,7 @@ fn drawn(view: &NotesView) -> String { .sections .iter() .map(|section| { - let cards: Vec<_> = section - .cards - .iter() - .map(|card| view.display(card)) - .collect(); + let cards: Vec<_> = section.cards.iter().map(|card| view.display(card)).collect(); ( §ion.key, §ion.id, @@ -309,13 +259,8 @@ fn every_query_answers_what_the_database_answers_through_random_writes() { for _ in 0..4 { let query = world.query(); let from_index = notes::query_notes(&world.engine, &query).unwrap(); - let from_database = - notes::query_notes_from_database(&world.engine, &query).unwrap(); - assert_eq!( - drawn(&from_index), - drawn(&from_database), - "seed {seed}, step {step}, {query:?}" - ); + let from_database = notes::query_notes_from_database(&world.engine, &query).unwrap(); + assert_eq!(drawn(&from_index), drawn(&from_database), "seed {seed}, step {step}, {query:?}"); } let tags = notes::list_tags(&world.engine).unwrap(); let mut library = crate::db::lock(&world.engine.db).unwrap(); diff --git a/crates/engine/src/json/layout.rs b/crates/engine/src/json/layout.rs index 211698850..52a70e167 100644 --- a/crates/engine/src/json/layout.rs +++ b/crates/engine/src/json/layout.rs @@ -36,13 +36,7 @@ pub(crate) fn place(nodes: &mut [JsonNode], column_gap: u32, node_gap: u32) -> ( } /// Where the subtree under `index` ends, placed from `top` down. -fn subtree( - nodes: &mut [JsonNode], - children: &[Vec], - index: usize, - top: u32, - gap: u32, -) -> u32 { +fn subtree(nodes: &mut [JsonNode], children: &[Vec], index: usize, top: u32, gap: u32) -> u32 { nodes[index].y = top; let mut bottom = top + nodes[index].height; let mut next = top; diff --git a/crates/engine/src/json/model.rs b/crates/engine/src/json/model.rs index d0c447342..8defc0645 100644 --- a/crates/engine/src/json/model.rs +++ b/crates/engine/src/json/model.rs @@ -166,11 +166,7 @@ pub fn explore(query: &JsonQuery) -> JsonView { graph: graph(&entries, &open, folded), tree, tree_truncated, - matches: hits - .iter() - .take(MAX_MATCHES) - .map(|entry| entry.path.clone()) - .collect(), + matches: hits.iter().take(MAX_MATCHES).map(|entry| entry.path.clone()).collect(), match_count: count(hits.len()), notices, } @@ -180,17 +176,8 @@ impl JsonView { fn invalid(error: JsonError, bytes: u32) -> Self { Self { error: Some(error), - stats: JsonStats { - keys: 0, - depth: 0, - bytes, - }, - graph: JsonGraph { - nodes: Vec::new(), - width: 0, - height: 0, - folded: false, - }, + stats: JsonStats { keys: 0, depth: 0, bytes }, + graph: JsonGraph { nodes: Vec::new(), width: 0, height: 0, folded: false }, tree: Vec::new(), tree_truncated: false, matches: Vec::new(), @@ -221,15 +208,7 @@ struct Entry { impl Entry { fn flatten(root: &Node, needle: &str) -> Vec { let mut entries = Vec::new(); - visit( - root, - None, - "$".to_string(), - "$".to_string(), - false, - &mut entries, - needle, - ); + visit(root, None, "$".to_string(), "$".to_string(), false, &mut entries, needle); entries } @@ -252,8 +231,7 @@ fn visit( let (kind, value, size, searched) = describe(&node.value); let hit = parent.is_some() && !needle.is_empty() - && (fold(&key).contains(needle) - || searched.is_some_and(|text| fold(text).contains(needle))); + && (fold(&key).contains(needle) || searched.is_some_and(|text| fold(text).contains(needle))); entries.push(Entry { parent, @@ -281,15 +259,7 @@ fn visit( Value::Object(members) => { for (name, child) in members { let path = member_path(&entries[index].path, name); - visit( - child, - Some(index), - name.clone(), - path, - false, - entries, - needle, - ); + visit(child, Some(index), name.clone(), path, false, entries, needle); } } Value::Array(items) => { @@ -306,24 +276,9 @@ fn visit( /// The kind, what a row shows, the size, and what the search reads of a scalar. fn describe(value: &Value) -> (JsonKind, String, u32, Option<&str>) { match value { - Value::Object(members) => ( - JsonKind::Object, - "{ … }".to_string(), - count(members.len()), - None, - ), - Value::Array(items) => ( - JsonKind::Array, - format!("[ {} ]", items.len()), - count(items.len()), - None, - ), - Value::String(text) => ( - JsonKind::String, - format!("\"{}\"", cut(text)), - 0, - Some(text), - ), + Value::Object(members) => (JsonKind::Object, "{ … }".to_string(), count(members.len()), None), + Value::Array(items) => (JsonKind::Array, format!("[ {} ]", items.len()), count(items.len()), None), + Value::String(text) => (JsonKind::String, format!("\"{}\"", cut(text)), 0, Some(text)), Value::Number(raw) => (JsonKind::Number, cut(raw), 0, Some(raw)), Value::Bool(true) => (JsonKind::Boolean, "true".to_string(), 0, Some("true")), Value::Bool(false) => (JsonKind::Boolean, "false".to_string(), 0, Some("false")), @@ -340,10 +295,7 @@ fn cut(text: &str) -> String { .take(VALUE_CHARS + 1) .collect(); if line.chars().count() > VALUE_CHARS { - format!( - "{}…", - line.chars().take(VALUE_CHARS - 1).collect::() - ) + format!("{}…", line.chars().take(VALUE_CHARS - 1).collect::()) } else { line } @@ -355,16 +307,11 @@ pub(crate) fn member_path(parent: &str, key: &str) -> String { .chars() .next() .is_some_and(|c| c.is_ascii_alphabetic() || c == '_' || c == '$') - && key - .chars() - .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$'); + && key.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$'); if identifier { format!("{parent}.{key}") } else { - format!( - "{parent}['{}']", - key.replace('\\', "\\\\").replace('\'', "\\'") - ) + format!("{parent}['{}']", key.replace('\\', "\\\\").replace('\'', "\\'")) } } @@ -377,11 +324,7 @@ fn stats(entries: &[Entry], bytes: u32) -> JsonStats { .max() .unwrap_or(0); - JsonStats { - keys: count(keys), - depth, - bytes, - } + JsonStats { keys: count(keys), depth, bytes } } /// Which containers are open, in breadth-first order so a cap keeps the levels nearest the @@ -400,9 +343,7 @@ fn opened(entries: &[Entry], opening: &JsonOpening) -> (BTreeSet, bool) { JsonOpening::Paths { .. } => { index == 0 || revealed.contains(&index) - || asked - .as_ref() - .is_some_and(|asked| asked.contains(entry.path.as_str())) + || asked.as_ref().is_some_and(|asked| asked.contains(entry.path.as_str())) } } }; @@ -443,11 +384,7 @@ fn opened(entries: &[Entry], opening: &JsonOpening) -> (BTreeSet, bool) { /// The containers above the path to reveal, which open whatever the paths say. fn revealed(entries: &[Entry], opening: &JsonOpening) -> BTreeSet { - let JsonOpening::Paths { - reveal: Some(target), - .. - } = opening - else { + let JsonOpening::Paths { reveal: Some(target), .. } = opening else { return BTreeSet::new(); }; let mut above = BTreeSet::new(); @@ -512,12 +449,7 @@ fn graph(entries: &[Entry], open: &BTreeSet, folded: bool) -> JsonGraph { .collect(); let (width, height) = super::layout::place(&mut nodes, COLUMN_GAP, NODE_GAP); - JsonGraph { - nodes, - width, - height, - folded, - } + JsonGraph { nodes, width, height, folded } } /// Wide enough for its widest row, within bounds: the front cuts what still overflows. @@ -527,9 +459,7 @@ fn width(entry: &Entry, rows: &[JsonRow]) -> u32 { let header = entry.key.chars().count() + 12; let widest = rows .iter() - .map(|row| { - row.key.chars().count() + row.value.chars().count() + if row.opens { 8 } else { 5 } - }) + .map(|row| row.key.chars().count() + row.value.chars().count() + if row.opens { 8 } else { 5 }) .max() .unwrap_or(0); @@ -620,10 +550,7 @@ mod tests { } fn paths(paths: &[&str]) -> JsonOpening { - JsonOpening::Paths { - paths: paths.iter().map(|path| (*path).to_string()).collect(), - reveal: None, - } + JsonOpening::Paths { paths: paths.iter().map(|path| (*path).to_string()).collect(), reveal: None } } fn searched(search: &str) -> JsonView { @@ -632,11 +559,7 @@ mod tests { /// The nodes drawn, by path. fn drawn(view: &JsonView) -> Vec<&str> { - view.graph - .nodes - .iter() - .map(|node| node.path.as_str()) - .collect() + view.graph.nodes.iter().map(|node| node.path.as_str()).collect() } fn node<'a>(view: &'a JsonView, path: &str) -> &'a JsonNode { @@ -657,9 +580,7 @@ mod tests { /// `count` arrays of `each` objects, in one object. fn arrays(count: usize, each: usize) -> String { - let arrays: Vec = (0..count) - .map(|i| format!(r#""a{i}": {}"#, objects(each))) - .collect(); + let arrays: Vec = (0..count).map(|i| format!(r#""a{i}": {}"#, objects(each))).collect(); format!("{{{}}}", arrays.join(",")) } @@ -697,27 +618,15 @@ mod tests { assert_eq!(drawn(&view), ["$"]); let data = &node(&view, "$").rows[3]; - assert_eq!( - (data.path.as_str(), data.child, data.size), - ("$.data", None, 1) - ); + assert_eq!((data.path.as_str(), data.child, data.size), ("$.data", None, 1)); } #[test] fn a_path_revealed_opens_everything_above_it() { - let reveal = |path: &str| JsonOpening::Paths { - paths: Vec::new(), - reveal: Some(path.to_string()), - }; + let reveal = |path: &str| JsonOpening::Paths { paths: Vec::new(), reveal: Some(path.to_string()) }; let view = opening(INVOICE, reveal("$.data.object.lines[1].description")); - let expected = [ - "$", - "$.data", - "$.data.object", - "$.data.object.lines", - "$.data.object.lines[1]", - ]; + let expected = ["$", "$.data", "$.data.object", "$.data.object.lines", "$.data.object.lines[1]"]; assert_eq!(drawn(&view), expected); assert_eq!(drawn(&opening(INVOICE, reveal("$.gone"))), ["$"]); } @@ -730,12 +639,7 @@ mod tests { assert!(view.graph.folded); assert_eq!(view.graph.nodes.len(), 21); let first = &view.graph.nodes[1]; - assert!( - first - .rows - .iter() - .all(|row| row.opens && row.child.is_none()) - ); + assert!(first.rows.iter().all(|row| row.opens && row.child.is_none())); } /// The cap keeps the levels nearest the root, and nothing says the arrays were folded. @@ -749,19 +653,9 @@ mod tests { .chain((0..20).map(|i| format!("$.a{i}"))) .collect(); - let view = opening( - &text, - JsonOpening::Paths { - paths: every, - reveal: None, - }, - ); + let view = opening(&text, JsonOpening::Paths { paths: every, reveal: None }); - let arrays = view - .graph - .nodes - .iter() - .filter(|node| node.kind == JsonKind::Array); + let arrays = view.graph.nodes.iter().filter(|node| node.kind == JsonKind::Array); assert_eq!(arrays.count(), 20); assert!(view.graph.nodes.len() <= MAX_NODES); } @@ -789,21 +683,14 @@ mod tests { #[test] fn a_node_lists_its_values_as_rows_of_one_line() { - let text = r#"{"s": "paid", "n": 4900, "t": true, "f": false, "z": null, "o": {"a": 1}, "l": [1, 2, 3]}"#; + let text = + r#"{"s": "paid", "n": 4900, "t": true, "f": false, "z": null, "o": {"a": 1}, "l": [1, 2, 3]}"#; let view = explored(text); let rows: Vec<_> = node(&view, "$") .rows .iter() - .map(|row| { - ( - row.key.as_str(), - row.value.as_str(), - row.kind, - row.size, - row.opens, - ) - }) + .map(|row| (row.key.as_str(), row.value.as_str(), row.kind, row.size, row.opens)) .collect(); assert_eq!( rows, @@ -822,41 +709,27 @@ mod tests { #[test] fn a_node_says_what_it_is_under_and_links_the_rows_it_opened() { let view = explored(INVOICE); - let (root, data, lines) = ( - node(&view, "$"), - node(&view, "$.data"), - node(&view, "$.data.object.lines"), - ); + let (root, data, lines) = + (node(&view, "$"), node(&view, "$.data"), node(&view, "$.data.object.lines")); assert_eq!( (root.label.as_str(), root.kind, root.size, root.parent), ("$", JsonKind::Object, 4, None) ); - assert_eq!( - (data.parent, root.rows[3].child), - (Some(root.id), Some(data.id)) - ); - assert_eq!( - (lines.label.as_str(), lines.kind, lines.size), - ("lines", JsonKind::Array, 2) - ); + assert_eq!((data.parent, root.rows[3].child), (Some(root.id), Some(data.id))); + assert_eq!((lines.label.as_str(), lines.kind, lines.size), ("lines", JsonKind::Array, 2)); assert_eq!(node(&view, "$.data.object.lines[0]").label, "[0]"); assert_eq!(lines.rows[1].key, "[1]"); } #[test] fn a_long_array_shows_its_first_rows_and_counts_the_rest() { - for (count, rows, hidden, height) in [ - (ROWS_PER_NODE, 200, 0, 201), - (ROWS_PER_NODE + 1, 200, 1, 202), - (500, 200, 300, 202), - ] { + for (count, rows, hidden, height) in + [(ROWS_PER_NODE, 200, 0, 201), (ROWS_PER_NODE + 1, 200, 1, 202), (500, 200, 300, 202)] + { let view = explored(&numbers(count)); let root = node(&view, "$"); - assert_eq!( - (root.rows.len(), root.hidden_rows, root.height), - (rows, hidden, height) - ); + assert_eq!((root.rows.len(), root.hidden_rows, root.height), (rows, hidden, height)); } } @@ -865,10 +738,7 @@ mod tests { let view = explored(INVOICE); let row = &node(&view, "$").rows[0]; - assert_eq!( - &INVOICE[row.span.start as usize..row.span.end as usize], - "\"evt_1PqX4c\"" - ); + assert_eq!(&INVOICE[row.span.start as usize..row.span.end as usize], "\"evt_1PqX4c\""); } /// « Copier la valeur » put `"Lyon"` in the clipboard, its quotes with it (COD-23). @@ -876,11 +746,7 @@ mod tests { fn a_string_carries_its_own_text_unquoted_and_nothing_else_does() { let view = explored(r#"{"ville": "Ly\"oné", "n": 4, "o": {"a": 1}}"#); - let texts: Vec<_> = node(&view, "$") - .rows - .iter() - .map(|row| row.text.as_deref()) - .collect(); + let texts: Vec<_> = node(&view, "$").rows.iter().map(|row| row.text.as_deref()).collect(); assert_eq!(texts, [Some("Ly\"oné"), None, None]); let lines: Vec<_> = view.tree.iter().map(|line| line.text.as_deref()).collect(); assert_eq!(lines, [None, Some("Ly\"oné"), None, None, None]); @@ -888,23 +754,13 @@ mod tests { #[test] fn a_value_is_cut_to_one_line_of_what_a_row_holds() { - let shown = |text: &str| { - node(&explored(&format!("[{text}]")), "$").rows[0] - .value - .clone() - }; + let shown = |text: &str| node(&explored(&format!("[{text}]")), "$").rows[0].value.clone(); let long = |count: usize| format!("\"{}\"", "x".repeat(count)); assert_eq!(shown(r#""a\nb\tc""#), "\"a b c\""); assert_eq!(shown(&long(VALUE_CHARS)), long(VALUE_CHARS)); - assert_eq!( - shown(&long(VALUE_CHARS + 1)), - format!("\"{}…\"", "x".repeat(VALUE_CHARS - 1)) - ); - assert_eq!( - shown(&"1".repeat(60)), - format!("{}…", "1".repeat(VALUE_CHARS - 1)) - ); + assert_eq!(shown(&long(VALUE_CHARS + 1)), format!("\"{}…\"", "x".repeat(VALUE_CHARS - 1))); + assert_eq!(shown(&"1".repeat(60)), format!("{}…", "1".repeat(VALUE_CHARS - 1))); } #[test] @@ -913,11 +769,7 @@ mod tests { r#"{"a key": 1, "it's": 2, "b\\s": 3, "1a": 4, "ok_1": 5, "$x": 6, "_": 7, "é": 8, "": 9}"#, ); - let paths: Vec<&str> = node(&view, "$") - .rows - .iter() - .map(|row| row.path.as_str()) - .collect(); + let paths: Vec<&str> = node(&view, "$").rows.iter().map(|row| row.path.as_str()).collect(); assert_eq!( paths, [ @@ -944,15 +796,9 @@ mod tests { let (root, data) = (column("$"), column("$.data")); assert_eq!(root.0, 0); assert_eq!(data.0, root.1 + COLUMN_GAP); - let (customer, lines) = ( - column("$.data.object.customer"), - column("$.data.object.lines"), - ); + let (customer, lines) = (column("$.data.object.customer"), column("$.data.object.lines")); assert_eq!(customer.0, lines.0); - assert_eq!( - column("$.data.object.lines[0]").0, - customer.0 + customer.1.max(lines.1) + COLUMN_GAP - ); + assert_eq!(column("$.data.object.lines[0]").0, customer.0 + customer.1.max(lines.1) + COLUMN_GAP); let period = column("$.data.object.lines[0].period"); assert_eq!(view.graph.width, period.0 + period.1); } @@ -970,12 +816,7 @@ mod tests { assert_eq!(data.y, 1 + 3); assert_eq!(customer.y, node(&view, "$.data.object").y + 1 + 1); assert_eq!(lines.y, customer.y + customer.height + NODE_GAP); - let bottom = view - .graph - .nodes - .iter() - .map(|node| node.y + node.height) - .max(); + let bottom = view.graph.nodes.iter().map(|node| node.y + node.height).max(); assert_eq!(Some(view.graph.height), bottom); } @@ -986,10 +827,7 @@ mod tests { assert_eq!(width(r#"{"a": 1}"#), MIN_WIDTH); assert_eq!(width(r#"{"a key of some length": 1234}"#), 20 + 4 + 5); assert_eq!(width(r#"{"a key of some length": {}}"#), 20 + 5 + 8); - assert_eq!( - width(&format!(r#"{{"key": "{}"}}"#, "x".repeat(200))), - MAX_WIDTH - ); + assert_eq!(width(&format!(r#"{{"key": "{}"}}"#, "x".repeat(200))), MAX_WIDTH); let long = explored(r#"{"a label longer than its rows": {"a": 1}}"#); assert_eq!(long.graph.nodes[1].width, 28 + 12); } @@ -1025,12 +863,8 @@ mod tests { assert!(node(&view, "$.data.object.lines[0].period").hit); assert!(node(&view, "$.data.object.lines[0]").rows[1].hit); assert!(!node(&view, "$.data.object.lines[0]").rows[0].hit); - let marked: Vec<&str> = view - .tree - .iter() - .filter(|line| line.hit) - .map(|line| line.key.as_str()) - .collect(); + let marked: Vec<&str> = + view.tree.iter().filter(|line| line.hit).map(|line| line.key.as_str()).collect(); assert_eq!(marked, ["period"]); } @@ -1039,10 +873,7 @@ mod tests { fn a_search_covers_what_is_not_open_in_the_document_s_order() { let view = explore(&query(INVOICE, "description", paths(&[]))); - let expected = [ - "$.data.object.lines[0].description", - "$.data.object.lines[1].description", - ]; + let expected = ["$.data.object.lines[0].description", "$.data.object.lines[1].description"]; assert_eq!(view.matches, expected); assert_eq!(view.graph.nodes.len(), 1); } @@ -1086,10 +917,7 @@ mod tests { let whole = opening(&numbers(MAX_TREE_LINES - 1), JsonOpening::All); let cut = opening(&numbers(MAX_TREE_LINES), JsonOpening::All); - assert_eq!( - (whole.tree.len(), whole.tree_truncated), - (MAX_TREE_LINES, false) - ); + assert_eq!((whole.tree.len(), whole.tree_truncated), (MAX_TREE_LINES, false)); assert_eq!((cut.tree.len(), cut.tree_truncated), (MAX_TREE_LINES, true)); } @@ -1103,11 +931,7 @@ mod tests { (r#"[{"é": [[1]]}]"#, 1, 3), ] { let stats = explored(text).stats; - assert_eq!( - (stats.keys, stats.depth, stats.bytes as usize), - (keys, depth, text.len()), - "{text}" - ); + assert_eq!((stats.keys, stats.depth, stats.bytes as usize), (keys, depth, text.len()), "{text}"); } } @@ -1118,14 +942,7 @@ mod tests { let error = view.error.unwrap(); assert_eq!((error.line, error.column), (1, 7)); assert!(view.graph.nodes.is_empty() && view.tree.is_empty() && view.matches.is_empty()); - assert_eq!( - view.stats, - JsonStats { - keys: 0, - depth: 0, - bytes: 7 - } - ); + assert_eq!(view.stats, JsonStats { keys: 0, depth: 0, bytes: 7 }); } #[test] @@ -1141,19 +958,10 @@ mod tests { #[test] fn another_format_is_explored_in_the_same_model_under_the_same_caps() { let yaml = |text: &str, opening| { - explore(&JsonQuery { - format: StructureFormat::Yaml, - ..query(text, "", opening) - }) + explore(&JsonQuery { format: StructureFormat::Yaml, ..query(text, "", opening) }) }; - let items = (0..150) - .map(|i| format!(" - i: {i}\n")) - .collect::>() - .concat(); - let lists = (0..20) - .map(|i| format!("a{i}:\n{items}")) - .collect::>() - .concat(); + let items = (0..150).map(|i| format!(" - i: {i}\n")).collect::>().concat(); + let lists = (0..20).map(|i| format!("a{i}:\n{items}")).collect::>().concat(); let capped = yaml(&lists, JsonOpening::All); assert_eq!((capped.graph.folded, capped.graph.nodes.len()), (true, 21)); @@ -1164,10 +972,7 @@ mod tests { assert_eq!(small.notices, [JsonNotice::FirstDocumentOnly]); let broken = yaml("a: [1\n", JsonOpening::Initial); - assert_eq!( - broken.error.map(|error| error.reason), - Some(JsonErrorReason::Malformed) - ); + assert_eq!(broken.error.map(|error| error.reason), Some(JsonErrorReason::Malformed)); } #[test] @@ -1178,9 +983,6 @@ mod tests { }); let row = &node(&view, "$").rows[0]; - assert_eq!( - (row.kind, row.value.as_str(), row.hit), - (JsonKind::Datetime, "1979-05-27", true) - ); + assert_eq!((row.kind, row.value.as_str(), row.hit), (JsonKind::Datetime, "1979-05-27", true)); } } diff --git a/crates/engine/src/json/parse.rs b/crates/engine/src/json/parse.rs index f7275a5fc..e55ecc8df 100644 --- a/crates/engine/src/json/parse.rs +++ b/crates/engine/src/json/parse.rs @@ -56,15 +56,9 @@ pub struct JsonError { pub(crate) const MAX_DEPTH: usize = 256; pub(crate) fn parse(text: &str) -> Result { - let mut parser = Parser { - bytes: text.as_bytes(), - at: 0, - utf16: 0, - }; - - let root = parser - .value(0) - .map_err(|reason| parser.error(text, reason))?; + let mut parser = Parser { bytes: text.as_bytes(), at: 0, utf16: 0 }; + + let root = parser.value(0).map_err(|reason| parser.error(text, reason))?; parser.whitespace(); if parser.at < parser.bytes.len() { return Err(parser.error(text, JsonErrorReason::TrailingCharacters)); @@ -130,13 +124,7 @@ impl Parser<'_> { Some(b'-' | b'0'..=b'9') => Value::Number(self.number()?), Some(_) => return Err(JsonErrorReason::UnexpectedCharacter), }; - Ok(Node { - value, - span: Span { - start, - end: self.utf16, - }, - }) + Ok(Node { value, span: Span { start, end: self.utf16 } }) } fn object(&mut self, depth: usize) -> Parsed { @@ -309,9 +297,7 @@ impl Parser<'_> { for _ in 0..4 { let digit = match self.peek() { None => return Err(JsonErrorReason::UnexpectedEnd), - Some(byte) => char::from(byte) - .to_digit(16) - .ok_or(JsonErrorReason::InvalidEscape)?, + Some(byte) => char::from(byte).to_digit(16).ok_or(JsonErrorReason::InvalidEscape)?, }; self.bump(); code = code * 16 + digit; @@ -393,27 +379,14 @@ mod tests { let keys: Vec<&str> = members.iter().map(|(key, _)| key.as_str()).collect(); assert_eq!(keys, ["b", "a", "b"]); - assert!( - matches!(&members[1].1.value, Value::Array(items) if items[1].value == number("3")) - ); - assert!( - matches!(&members[2].1.value, Value::Object(inner) if inner[0].1.value == number("4")) - ); + assert!(matches!(&members[1].1.value, Value::Array(items) if items[1].value == number("3"))); + assert!(matches!(&members[2].1.value, Value::Object(inner) if inner[0].1.value == number("4"))); } /// `1e3` stays `1e3`, and a number past `f64` loses nothing. #[test] fn a_number_is_kept_as_written() { - for text in [ - "0", - "-0", - "10", - "-1.50", - "1e3", - "1E+3", - "-1.5e-10", - "123456789012345678901234567890", - ] { + for text in ["0", "-0", "10", "-1.50", "1e3", "1E+3", "-1.5e-10", "123456789012345678901234567890"] { assert_eq!(read(text), number(text)); } } @@ -452,10 +425,8 @@ mod tests { let text = r#" ["😀", "é", {"a": 1}] "#; let root = parse(text).unwrap(); - let spans: Vec<(u32, u32)> = items(text) - .iter() - .map(|item| (item.span.start, item.span.end)) - .collect(); + let spans: Vec<(u32, u32)> = + items(text).iter().map(|item| (item.span.start, item.span.end)).collect(); assert_eq!(root.span, Span { start: 1, end: 22 }); assert_eq!(spans, [(2, 6), (8, 11), (13, 21)]); } @@ -532,10 +503,7 @@ mod tests { let objects = |depth: usize| format!("{}1{}", "{\"a\":".repeat(depth), "}".repeat(depth)); assert!(parse(&nested(MAX_DEPTH + 1)).is_ok()); - assert_eq!( - error(&nested(MAX_DEPTH + 2)).reason, - JsonErrorReason::TooDeep - ); + assert_eq!(error(&nested(MAX_DEPTH + 2)).reason, JsonErrorReason::TooDeep); assert_eq!(error(&"[".repeat(10_000)).reason, JsonErrorReason::TooDeep); assert!(parse(&objects(MAX_DEPTH)).is_ok()); let too_deep = error(&objects(MAX_DEPTH + 1)); diff --git a/crates/engine/src/json/position.rs b/crates/engine/src/json/position.rs index 3d2488e41..ad8bea94f 100644 --- a/crates/engine/src/json/position.rs +++ b/crates/engine/src/json/position.rs @@ -50,10 +50,7 @@ impl<'a> Positions<'a> { } pub(crate) fn span(&self, start: usize, end: usize) -> Span { - Span { - start: self.utf16(start), - end: self.utf16(end.max(start)), - } + Span { start: self.utf16(start), end: self.utf16(end.max(start)) } } pub(crate) fn error(&self, reason: JsonErrorReason, byte: usize) -> JsonError { @@ -102,11 +99,7 @@ mod tests { (2, 99, TEXT), (9, 0, TEXT), ] { - assert_eq!( - positions.byte_at(line, column), - before.len(), - "{line}:{column}" - ); + assert_eq!(positions.byte_at(line, column), before.len(), "{line}:{column}"); } } diff --git a/crates/engine/src/json/read.rs b/crates/engine/src/json/read.rs index 6ac639804..d151b0c91 100644 --- a/crates/engine/src/json/read.rs +++ b/crates/engine/src/json/read.rs @@ -28,10 +28,7 @@ pub(crate) struct Read { pub(crate) fn read(text: &str, format: StructureFormat) -> Result { match format { - StructureFormat::Json => parse(text).map(|root| Read { - root, - notices: Vec::new(), - }), + StructureFormat::Json => parse(text).map(|root| Read { root, notices: Vec::new() }), StructureFormat::Yaml => yaml::read(text), StructureFormat::Toml => toml::read(text), StructureFormat::Xml => xml::read(text), @@ -84,16 +81,9 @@ mod tests { let Value::Object(members) = read.root.value else { panic!("{format:?}"); }; - assert_eq!( - (members[0].0.as_str(), &members[0].1.value), - ("a", &Value::String("b".to_string())) - ); + assert_eq!((members[0].0.as_str(), &members[0].1.value), ("a", &Value::String("b".to_string()))); } - for format in [ - StructureFormat::Json, - StructureFormat::Toml, - StructureFormat::Xml, - ] { + for format in [StructureFormat::Json, StructureFormat::Toml, StructureFormat::Xml] { assert!(read("a: b", format).is_err(), "{format:?}"); } } diff --git a/crates/engine/src/json/toml.rs b/crates/engine/src/json/toml.rs index 64c741df4..d400408d3 100644 --- a/crates/engine/src/json/toml.rs +++ b/crates/engine/src/json/toml.rs @@ -17,17 +17,10 @@ pub(crate) fn read(text: &str) -> Result { })?; // The document's own span is empty: the root is the whole text. let root = table(root.get_ref(), &positions, 0, text.len(), 0)?; - Ok(Read { - root, - notices: Vec::new(), - }) + Ok(Read { root, notices: Vec::new() }) } -fn value( - spanned: &Spanned>, - positions: &Positions<'_>, - depth: usize, -) -> Result { +fn value(spanned: &Spanned>, positions: &Positions<'_>, depth: usize) -> Result { let span = spanned.span(); if depth > MAX_DEPTH { return Err(positions.error(JsonErrorReason::TooDeep, span.start)); @@ -46,10 +39,7 @@ fn value( ), DeValue::Table(members) => return table(members, positions, span.start, span.end, depth), }; - Ok(Node { - value, - span: positions.span(span.start, span.end), - }) + Ok(Node { value, span: positions.span(span.start, span.end) }) } /// A table written as `[name]` is placed on its header, an implicit one on its key. @@ -67,17 +57,9 @@ fn table( written.sort_by_key(|(key, _)| key.span().start); let members = written .into_iter() - .map(|(key, child)| { - Ok(( - key.get_ref().to_string(), - value(child, positions, depth + 1)?, - )) - }) + .map(|(key, child)| Ok((key.get_ref().to_string(), value(child, positions, depth + 1)?))) .collect::>()?; - Ok(Node { - value: Value::Object(members), - span: positions.span(start, end), - }) + Ok(Node { value: Value::Object(members), span: positions.span(start, end) }) } #[cfg(test)] @@ -100,10 +82,7 @@ mod tests { fn the_tables_and_keys_keep_the_order_they_were_written_in() { let root = root(CONFIG); - assert_eq!( - keys(&root), - ["title", "when", "site", "server", "a", "products"] - ); + assert_eq!(keys(&root), ["title", "when", "site", "server", "a", "products"]); let products = array(&members(&root)[5].1); assert_eq!(keys(&products[1]), ["inline", "name"]); } @@ -167,11 +146,7 @@ mod tests { fn an_unreadable_document_says_where_it_breaks() { for (text, line) in [("a = 1\nb = \n", 2), ("a = 1\na = 2", 2), ("\n\n[a", 3)] { let error = read(text).expect_err(text); - assert_eq!( - (error.reason, error.line), - (JsonErrorReason::Malformed, line), - "{text}" - ); + assert_eq!((error.reason, error.line), (JsonErrorReason::Malformed, line), "{text}"); } } @@ -186,14 +161,8 @@ mod tests { assert!(read(&nested(79, "1")).is_ok()); let too_deep = nested(39, &format!("{{ {} = 1 }}", path("c"))); - assert_eq!( - read(&too_deep).expect_err("too deep").reason, - JsonErrorReason::TooDeep - ); + assert_eq!(read(&too_deep).expect_err("too deep").reason, JsonErrorReason::TooDeep); let brackets = format!("a = {}1{}", "[".repeat(300), "]".repeat(300)); - assert_eq!( - read(&brackets).expect_err("too deep").reason, - JsonErrorReason::Malformed - ); + assert_eq!(read(&brackets).expect_err("too deep").reason, JsonErrorReason::Malformed); } } diff --git a/crates/engine/src/json/xml.rs b/crates/engine/src/json/xml.rs index b0c17e61c..8d5e54872 100644 --- a/crates/engine/src/json/xml.rs +++ b/crates/engine/src/json/xml.rs @@ -27,12 +27,7 @@ struct Element { } impl Element { - fn open( - tag: &BytesStart<'_>, - start: usize, - end: usize, - positions: &Positions<'_>, - ) -> Result { + fn open(tag: &BytesStart<'_>, start: usize, end: usize, positions: &Positions<'_>) -> Result { let mut element = Self { name: tag.name().as_ref().to_owned(), start, @@ -52,22 +47,14 @@ impl Element { let (from, to) = match &attribute.value { Cow::Borrowed(raw) => { let from = (raw.as_ptr() as usize).wrapping_sub(source.as_ptr() as usize); - if from <= source.len() { - (from, from + raw.len()) - } else { - (start, end) - } + if from <= source.len() { (from, from + raw.len()) } else { (start, end) } } Cow::Owned(_) => (start, end), }; let key = format!("@{}", attribute.key.as_ref()); - element.members.push(( - key, - Node { - value: Value::String(value), - span: positions.span(from, to), - }, - )); + element + .members + .push((key, Node { value: Value::String(value), span: positions.span(from, to) })); } Ok(element) } @@ -93,21 +80,12 @@ impl Element { self.empty = false; match self.members.iter_mut().find(|(key, _)| *key == name) { Some((_, existing)) => { - let span = Span { - start: existing.span.start, - end: node.span.end, - }; + let span = Span { start: existing.span.start, end: node.span.end }; if let Value::Array(items) = &mut existing.value { items.push(node); } else { let first = std::mem::replace(&mut existing.value, Value::Null); - existing.value = Value::Array(vec![ - Node { - value: first, - span: existing.span, - }, - node, - ]); + existing.value = Value::Array(vec![Node { value: first, span: existing.span }, node]); } existing.span = span; } @@ -120,35 +98,19 @@ impl Element { fn close(mut self, end: usize, positions: &Positions<'_>) -> (String, Node) { let text = self.text.trim().to_owned(); let whole = positions.span(self.start, end); - let written = self - .text_at - .map_or(whole, |(from, to)| positions.span(from, to)); + let written = self.text_at.map_or(whole, |(from, to)| positions.span(from, to)); let node = if self.members.is_empty() { if text.is_empty() && self.empty { - Node { - value: Value::Null, - span: whole, - } + Node { value: Value::Null, span: whole } } else { - Node { - value: Value::String(text), - span: written, - } + Node { value: Value::String(text), span: written } } } else { if !text.is_empty() { - self.members.push(( - "#text".to_owned(), - Node { - value: Value::String(text), - span: written, - }, - )); - } - Node { - value: Value::Object(self.members), - span: whole, + self.members + .push(("#text".to_owned(), Node { value: Value::String(text), span: written })); } + Node { value: Value::Object(self.members), span: whole } }; (self.name, node) } @@ -157,11 +119,7 @@ impl Element { /// A character reference, or one of XML's five entities: without a DTD, no other is defined. fn resolve(reference: &BytesRef<'_>) -> Option { if reference.is_char_ref() { - return reference - .resolve_char_ref() - .ok() - .flatten() - .map(String::from); + return reference.resolve_char_ref().ok().flatten().map(String::from); } resolve_predefined_entity(reference).map(str::to_owned) } @@ -174,10 +132,7 @@ pub(crate) struct Refusal { impl Refusal { fn malformed(at: usize) -> Self { - Self { - at, - reason: JsonErrorReason::Malformed, - } + Self { at, reason: JsonErrorReason::Malformed } } } @@ -191,17 +146,12 @@ pub(crate) fn document(text: &str) -> Result { loop { let before = at(&reader); - let event = reader - .read_event() - .map_err(|_| Refusal::malformed(at(&reader)))?; + let event = reader.read_event().map_err(|_| Refusal::malformed(at(&reader)))?; let after = at(&reader); match event { Event::Start(tag) => { if open.len() >= MAX_DEPTH { - return Err(Refusal { - at: before, - reason: JsonErrorReason::TooDeep, - }); + return Err(Refusal { at: before, reason: JsonErrorReason::TooDeep }); } let element = Element::open(&tag, before, after, &positions) .map_err(|()| Refusal::malformed(before))?; @@ -211,14 +161,12 @@ pub(crate) fn document(text: &str) -> Result { let element = Element::open(&tag, before, after, &positions) .map_err(|()| Refusal::malformed(before))?; let (name, node) = element.close(after, &positions); - attach(&mut open, &mut root, name, node) - .map_err(|()| Refusal::malformed(before))?; + attach(&mut open, &mut root, name, node).map_err(|()| Refusal::malformed(before))?; } Event::End(_) => { let element = open.pop().ok_or_else(|| Refusal::malformed(before))?; let (name, node) = element.close(after, &positions); - attach(&mut open, &mut root, name, node) - .map_err(|()| Refusal::malformed(before))?; + attach(&mut open, &mut root, name, node).map_err(|()| Refusal::malformed(before))?; } Event::Text(raw) => { let content = raw.xml10_content(); @@ -261,10 +209,7 @@ pub(crate) fn document(text: &str) -> Result { return Err(Refusal::malformed(text.len())); } let (name, node) = root.ok_or_else(|| Refusal::malformed(0))?; - Ok(Node { - value: Value::Object(vec![(name, node)]), - span: positions.span(0, text.len()), - }) + Ok(Node { value: Value::Object(vec![(name, node)]), span: positions.span(0, text.len()) }) } fn attach( @@ -288,10 +233,7 @@ fn attach( pub(crate) fn read(text: &str) -> Result { document(text) - .map(|root| Read { - root, - notices: Vec::new(), - }) + .map(|root| Read { root, notices: Vec::new() }) .map_err(|refusal| Positions::new(text).error(refusal.reason, refusal.at)) } @@ -299,10 +241,7 @@ pub(crate) fn read(text: &str) -> Result { pub(crate) fn to_value(node: &Node) -> serde_json::Value { match &node.value { Value::Object(members) => serde_json::Value::Object( - members - .iter() - .map(|(key, child)| (key.clone(), to_value(child))) - .collect(), + members.iter().map(|(key, child)| (key.clone(), to_value(child))).collect(), ), Value::Array(items) => serde_json::Value::Array(items.iter().map(to_value).collect()), Value::String(text) | Value::Number(text) | Value::Datetime(text) => { @@ -353,19 +292,10 @@ mod tests { ("
    x", serde_json::json!("x")), (" x y ", serde_json::json!("x y")), ("", serde_json::json!({ "@x": "1" })), - ( - "t", - serde_json::json!({ "@x": "1", "#text": "t" }), - ), + ("t", serde_json::json!({ "@x": "1", "#text": "t" })), ("1", serde_json::json!({ "b": "1" })), - ( - "tu", - serde_json::json!({ "b": null, "#text": "tu" }), - ), - ( - "123", - serde_json::json!({ "b": ["1", "2", "3"], "c": null }), - ), + ("tu", serde_json::json!({ "b": null, "#text": "tu" })), + ("123", serde_json::json!({ "b": ["1", "2", "3"], "c": null })), ("", serde_json::json!({ "b": "" })), ("x ]]>y", serde_json::json!("x y")), ("x", serde_json::json!("x")), @@ -378,10 +308,7 @@ mod tests { fn references_are_resolved_in_a_text_and_in_an_attribute() { let read = json("&<>"'😀A"); - assert_eq!( - read, - serde_json::json!({ "a": { "@k": "1 < 2 é", "#text": "&<>\"'😀A" } }) - ); + assert_eq!(read, serde_json::json!({ "a": { "@k": "1 < 2 é", "#text": "&<>\"'😀A" } })); } #[test] @@ -390,10 +317,7 @@ mod tests { let note = members(&members(&order)[3].1); assert_eq!((note[0].0.as_str(), note[1].0.as_str()), ("b", "#text")); - assert_eq!( - note[1].1.value, - Value::String("payée & livrée".to_string()) - ); + assert_eq!(note[1].1.value, Value::String("payée & livrée".to_string())); } /// A text-only element on its text, an attribute on its value, a list from its first to its @@ -405,17 +329,11 @@ mod tests { let lines = array(&top[2].1); assert_eq!(slice(ORDER, &top[1].1), "42"); - assert_eq!( - slice(ORDER, &lines[0]), - "Pro · mensuel" - ); + assert_eq!(slice(ORDER, &lines[0]), "Pro · mensuel"); assert_eq!(slice(ORDER, &members(&lines[0])[1].1), "Pro · mensuel"); let both = "Pro · mensuel\n Stockage"; assert_eq!(slice(ORDER, &top[2].1), both); - assert_eq!( - slice(ORDER, &members(&top[3].1)[1].1), - "payée & vite livrée" - ); + assert_eq!(slice(ORDER, &members(&top[3].1)[1].1), "payée & vite livrée"); assert_eq!(slice(ORDER, &top[4].1), "a < b"); assert_eq!(slice(ORDER, &top[5].1), ""); } @@ -460,11 +378,7 @@ mod tests { ("", 1), ] { let error = read(text).expect_err(text); - assert_eq!( - (error.reason, error.line), - (JsonErrorReason::Malformed, line), - "{text}" - ); + assert_eq!((error.reason, error.line), (JsonErrorReason::Malformed, line), "{text}"); } } @@ -473,19 +387,13 @@ mod tests { let nested = |depth: usize| format!("{}{}", "".repeat(depth), "".repeat(depth)); assert!(read(&nested(MAX_DEPTH)).is_ok()); - assert_eq!( - read(&nested(MAX_DEPTH + 1)).expect_err("too deep").reason, - JsonErrorReason::TooDeep - ); + assert_eq!(read(&nested(MAX_DEPTH + 1)).expect_err("too deep").reason, JsonErrorReason::TooDeep); } /// A tree of another format goes through the same conversion. #[test] fn a_number_a_date_and_a_boolean_are_handed_as_values() { - let node = |value: Value| Node { - value, - span: Span { start: 0, end: 0 }, - }; + let node = |value: Value| Node { value, span: Span { start: 0, end: 0 } }; let list = Value::Array(vec![ node(Value::Number("1".to_string())), node(Value::Datetime("1979-05-27".to_string())), @@ -493,9 +401,6 @@ mod tests { node(Value::Null), ]); - assert_eq!( - to_value(&node(list)), - serde_json::json!(["1", "1979-05-27", true, null]) - ); + assert_eq!(to_value(&node(list)), serde_json::json!(["1", "1979-05-27", true, null])); } } diff --git a/crates/engine/src/json/yaml.rs b/crates/engine/src/json/yaml.rs index b151f3a87..24f710d6f 100644 --- a/crates/engine/src/json/yaml.rs +++ b/crates/engine/src/json/yaml.rs @@ -17,19 +17,8 @@ use super::read::{JsonNotice, Read}; const MAX_VALUES: usize = 200_000; enum Frame { - Mapping { - start: usize, - anchor: usize, - members: Vec<(String, Node)>, - key: Option, - end: usize, - }, - Sequence { - start: usize, - anchor: usize, - items: Vec, - end: usize, - }, + Mapping { start: usize, anchor: usize, members: Vec<(String, Node)>, key: Option, end: usize }, + Sequence { start: usize, anchor: usize, items: Vec, end: usize }, } struct Reader<'a> { @@ -53,9 +42,7 @@ pub(crate) fn read(text: &str) -> Result { let mut notices = Vec::new(); loop { - let (event, marker) = parser - .next_token() - .map_err(|error| reader.refused(&error))?; + let (event, marker) = parser.next_token().map_err(|error| reader.refused(&error))?; let at = reader.byte(&marker); match event { Event::StreamEnd => break, @@ -66,19 +53,12 @@ pub(crate) fn read(text: &str) -> Result { break; } } - Event::MappingStart(anchor, _) => reader.open(Frame::Mapping { - start: at, - anchor, - members: Vec::new(), - key: None, - end: at, - })?, - Event::SequenceStart(anchor, _) => reader.open(Frame::Sequence { - start: at, - anchor, - items: Vec::new(), - end: at, - })?, + Event::MappingStart(anchor, _) => { + reader.open(Frame::Mapping { start: at, anchor, members: Vec::new(), key: None, end: at })?; + } + Event::SequenceStart(anchor, _) => { + reader.open(Frame::Sequence { start: at, anchor, items: Vec::new(), end: at })?; + } Event::MappingEnd | Event::SequenceEnd => reader.close(at)?, Event::Scalar(raw, style, anchor, tag) => { reader.scalar(raw, style, anchor, tag.as_ref(), at)?; @@ -88,10 +68,9 @@ pub(crate) fn read(text: &str) -> Result { } } - let root = reader.root.unwrap_or(Node { - value: Value::Null, - span: reader.positions.span(0, 0), - }); + let root = reader + .root + .unwrap_or(Node { value: Value::Null, span: reader.positions.span(0, 0) }); Ok(Read { root, notices }) } @@ -129,25 +108,13 @@ impl Reader<'_> { let text = self.positions.text(); let bracket = matches!(text.as_bytes().get(at), Some(b'}' | b']')); let (value, start, anchor, last) = match frame { - Frame::Mapping { - start, - anchor, - members, - end, - .. - } => (Value::Object(members), start, anchor, end), - Frame::Sequence { - start, - anchor, - items, - end, - } => (Value::Array(items), start, anchor, end), + Frame::Mapping { start, anchor, members, end, .. } => { + (Value::Object(members), start, anchor, end) + } + Frame::Sequence { start, anchor, items, end } => (Value::Array(items), start, anchor, end), }; let end = if bracket { at + 1 } else { last }; - let node = Node { - value, - span: self.positions.span(start, end), - }; + let node = Node { value, span: self.positions.span(start, end) }; self.place(node, anchor, None, start, end) } @@ -162,17 +129,12 @@ impl Reader<'_> { let text = self.positions.text(); // A `|` or `>` block is marked on its first line of content: it starts on its indicator. let at = match style { - TScalarStyle::Literal | TScalarStyle::Folded => { - text[..at].rfind(['|', '>']).unwrap_or(at) - } + TScalarStyle::Literal | TScalarStyle::Folded => text[..at].rfind(['|', '>']).unwrap_or(at), _ => at, }; let end = scalar_end(text, at, &raw, style); let value = typed(&raw, style, tag); - let node = Node { - value, - span: self.positions.span(at, end), - }; + let node = Node { value, span: self.positions.span(at, end) }; self.place(node, anchor, Some(raw), at, end) } @@ -203,9 +165,7 @@ impl Reader<'_> { ) -> Result<(), JsonError> { self.values += 1; if self.values > MAX_VALUES { - return Err(self - .positions - .error(JsonErrorReason::TooLarge, end.saturating_sub(1))); + return Err(self.positions.error(JsonErrorReason::TooLarge, end.saturating_sub(1))); } if anchor > 0 { self.anchors.insert(anchor, node.clone()); @@ -213,13 +173,7 @@ impl Reader<'_> { let text = self.positions.text(); match self.stack.last_mut() { None => self.root = Some(node), - Some(Frame::Mapping { - members, - key, - start: first, - end: last, - .. - }) => { + Some(Frame::Mapping { members, key, start: first, end: last, .. }) => { *first = (*first).min(start); *last = (*last).max(end); match key.take() { @@ -227,12 +181,7 @@ impl Reader<'_> { Some(name) => members.push((name, node)), } } - Some(Frame::Sequence { - items, - start: first, - end: last, - .. - }) => { + Some(Frame::Sequence { items, start: first, end: last, .. }) => { *first = (*first).min(start); *last = (*last).max(end); items.push(node); @@ -327,9 +276,7 @@ fn block_end(text: &str, start: usize) -> usize { let mut at = end; while at < text.len() { let next = at + 1; - let line_end = text[next..] - .find('\n') - .map_or(text.len(), |offset| next + offset); + let line_end = text[next..].find('\n').map_or(text.len(), |offset| next + offset); let line = &text[next..line_end]; if !line.trim().is_empty() { if indentation(line) <= indent { @@ -368,10 +315,7 @@ mod tests { assert_eq!(top[0].1.value, Value::String("api".to_string())); assert_eq!(array(&top[1].1)[1].value, Value::Number("443".to_string())); let env = members(&top[2].1); - assert_eq!( - (&env[0].1.value, &env[1].1.value), - (&Value::Bool(true), &Value::Null) - ); + assert_eq!((&env[0].1.value, &env[1].1.value), (&Value::Bool(true), &Value::Null)); } /// The core schema: quoted, or tagged as a string, it stays one. @@ -393,11 +337,7 @@ mod tests { ("\"true\"", string("true")), ("!!str 12", string("12")), ] { - assert_eq!( - members(&root(&format!("a: {text}\n")))[0].1.value, - value, - "{text}" - ); + assert_eq!(members(&root(&format!("a: {text}\n")))[0].1.value, value, "{text}"); } assert_eq!(members(&root("a: |\n 12\n"))[0].1.value, string("12\n")); assert_eq!(members(&root("a:\n"))[0].1.value, Value::Null); @@ -419,11 +359,7 @@ mod tests { "|-\n kept", ] { let text = format!("a: {written} # note\nb: 1\n").replace("\n ", "\n "); - let text = if written.contains('\n') { - format!("a: {written}\nb: 1\n") - } else { - text - }; + let text = if written.contains('\n') { format!("a: {written}\nb: 1\n") } else { text }; let root = root(&text); assert_eq!(slice(&text, &members(&root)[0].1), written, "{text}"); } @@ -434,10 +370,7 @@ mod tests { let text = "a: one\n two\nb: 1\n"; let root = root(text); - assert_eq!( - members(&root)[0].1.value, - Value::String("one two".to_string()) - ); + assert_eq!(members(&root)[0].1.value, Value::String("one two".to_string())); assert_eq!(slice(text, &members(&root)[0].1), "one"); } @@ -467,10 +400,7 @@ mod tests { let top = members(&root); assert_eq!((top[0].1.span.start, top[0].1.span.end), (4, 11)); - assert_eq!( - (top[1].0.as_str(), slice(text, &top[1].1)), - ("é", "[é]".to_string()) - ); + assert_eq!((top[1].0.as_str(), slice(text, &top[1].1)), ("é", "[é]".to_string())); } /// "Show in code" goes to the anchor; a merge key is kept as read. @@ -522,12 +452,7 @@ mod tests { #[test] fn an_unreadable_document_says_where_it_breaks() { - for text in [ - "a: 1\nb: [1, 2\n", - "ok: 1\n🦀: \"open\n", - "a: 1\n b: 2\n", - "a: 1\nb: *nowhere\n", - ] { + for text in ["a: 1\nb: [1, 2\n", "ok: 1\n🦀: \"open\n", "a: 1\n b: 2\n", "a: 1\nb: *nowhere\n"] { let error = read(text).expect_err(text); assert_eq!(error.reason, JsonErrorReason::Malformed, "{text}"); assert!(error.line >= 2 && error.column >= 1, "{text}: {error:?}"); @@ -538,9 +463,7 @@ mod tests { fn a_nesting_deeper_than_can_be_walked_is_refused() { let flow = format!("{}1{}", "[".repeat(300), "]".repeat(300)); let block = |depth: usize| { - let lines: Vec = (0..depth) - .map(|level| format!("{}a:", " ".repeat(level))) - .collect(); + let lines: Vec = (0..depth).map(|level| format!("{}a:", " ".repeat(level))).collect(); lines.join("\n") }; diff --git a/crates/engine/src/layout.rs b/crates/engine/src/layout.rs index fdfae3b9f..70646ecd4 100644 --- a/crates/engine/src/layout.rs +++ b/crates/engine/src/layout.rs @@ -16,8 +16,7 @@ macro_rules! database { pub(crate) const DATABASE: &str = database!(); /// What SQLite keeps beside the database under WAL; they travel with it. -pub(crate) const DATABASE_SIDECARS: [&str; 2] = - [concat!(database!(), "-wal"), concat!(database!(), "-shm")]; +pub(crate) const DATABASE_SIDECARS: [&str; 2] = [concat!(database!(), "-wal"), concat!(database!(), "-shm")]; /// The library's key, wrapped under the passphrase. pub(crate) const KEY_FILE: &str = "vault.json"; @@ -40,16 +39,10 @@ pub(crate) const REPLACED: &str = "replaced"; pub const PREFERENCES: &str = "preferences.json"; /// Every file a library is made of. -pub(crate) const LIBRARY_FILES: [&str; 4] = [ - DATABASE, - DATABASE_SIDECARS[0], - DATABASE_SIDECARS[1], - KEY_FILE, -]; +pub(crate) const LIBRARY_FILES: [&str; 4] = [DATABASE, DATABASE_SIDECARS[0], DATABASE_SIDECARS[1], KEY_FILE]; /// Every directory a library accumulates. -pub(crate) const LIBRARY_DIRECTORIES: [&str; 5] = - [ATTACHMENTS, BACKUPS, DAMAGED, ARCHIVED, REPLACED]; +pub(crate) const LIBRARY_DIRECTORIES: [&str; 5] = [ATTACHMENTS, BACKUPS, DAMAGED, ARCHIVED, REPLACED]; /// The list of libraries, at the profile root and owned by none of them. pub(crate) const REGISTRY: &str = "libraries.json"; @@ -70,9 +63,7 @@ pub(crate) fn stamp(at: DateTime) -> String { } pub(crate) fn parse_stamp(name: &str) -> Option> { - NaiveDateTime::parse_from_str(name, STAMP) - .ok() - .map(|at| at.and_utc()) + NaiveDateTime::parse_from_str(name, STAMP).ok().map(|at| at.and_utc()) } #[cfg(test)] @@ -117,13 +108,7 @@ mod tests { /// A folder that is not a stamp is never taken for a copy. #[test] fn a_name_that_is_not_a_stamp_reads_as_none() { - for name in [ - "notes", - "2026-07-25", - "2026-07-25 09:05:07", - "../2026-07-25_09-05-07", - "", - ] { + for name in ["notes", "2026-07-25", "2026-07-25 09:05:07", "../2026-07-25_09-05-07", ""] { assert_eq!(parse_stamp(name), None, "{name}"); } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 628cc26cc..b6ed03428 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -69,8 +69,7 @@ impl Engine { /// Whether the next unlock takes the day's copy; it does until told otherwise. pub fn keep_launch_copies(&self, wanted: bool) { - self.launch_copies - .store(wanted, std::sync::atomic::Ordering::Relaxed); + self.launch_copies.store(wanted, std::sync::atomic::Ordering::Relaxed); } /// For the tests, which open a library of their own. @@ -151,9 +150,7 @@ pub(crate) fn sweep(engine: &Engine) { let db = &engine.db; // ⚠️ The copy before the sweeps: it is worth most holding what retention will purge. - let wanted = engine - .launch_copies - .load(std::sync::atomic::Ordering::Relaxed); + let wanted = engine.launch_copies.load(std::sync::atomic::Ordering::Relaxed); backup::take(wanted, db); notes::trash::sweep_at_startup(db); diff --git a/crates/engine/src/libraries.rs b/crates/engine/src/libraries.rs index dded1c581..58207ee07 100644 --- a/crates/engine/src/libraries.rs +++ b/crates/engine/src/libraries.rs @@ -12,8 +12,7 @@ use std::path::PathBuf; use crate::Engine; use crate::error::{AppError, StorageError}; use registry::{ - LibraryEntry, Registry, create_in, delete_in, open_directory_in, point_at, registry_in, - rename_in, + LibraryEntry, Registry, create_in, delete_in, open_directory_in, point_at, registry_in, rename_in, }; /// The directory of the library the registry points at, for what runs while none is open: diff --git a/crates/engine/src/libraries/registry.rs b/crates/engine/src/libraries/registry.rs index a7021c529..63c26ba5c 100644 --- a/crates/engine/src/libraries/registry.rs +++ b/crates/engine/src/libraries/registry.rs @@ -83,10 +83,7 @@ fn read(profile: &Path) -> Option { /// An unreadable registry moved aside, as it was, and the list made again from the folders /// under `libraries/` that hold one. Their names were in the file: they come back unnamed. fn rebuilt(profile: &Path) -> Registry { - let aside = format!( - "{REGISTRY}.unreadable-{}", - Utc::now().format("%Y%m%d-%H%M%S") - ); + let aside = format!("{REGISTRY}.unreadable-{}", Utc::now().format("%Y%m%d-%H%M%S")); if let Err(error) = std::fs::rename(profile.join(REGISTRY), profile.join(&aside)) { log::warn!("The unreadable registry was not set aside: {error}"); } @@ -101,19 +98,11 @@ fn rebuilt(profile: &Path) -> Registry { .metadata() .and_then(|metadata| metadata.created()) .map_or_else(|_| Utc::now(), DateTime::::from); - Some(LibraryEntry { - directory: format!("{LIBRARIES}/{id}"), - id, - name: String::new(), - created_at, - }) + Some(LibraryEntry { directory: format!("{LIBRARIES}/{id}"), id, name: String::new(), created_at }) }) .collect(); libraries.sort_by_key(|entry| entry.created_at); - let registry = Registry { - open: libraries.first().map(|entry| entry.id.clone()), - libraries, - }; + let registry = Registry { open: libraries.first().map(|entry| entry.id.clone()), libraries }; if !registry.libraries.is_empty() { let _ = write(profile, ®istry); } @@ -163,12 +152,7 @@ pub(crate) fn registry_in(profile: &Path) -> Registry { fn fresh(name: String) -> LibraryEntry { let id = uuid::Uuid::new_v4().to_string(); - LibraryEntry { - directory: format!("{LIBRARIES}/{id}"), - id, - name, - created_at: Utc::now(), - } + LibraryEntry { directory: format!("{LIBRARIES}/{id}"), id, name, created_at: Utc::now() } } /// Public for the benchmark that says what an open library saves by not calling it. @@ -253,11 +237,7 @@ mod tests { } fn ids(registry: &Registry) -> Vec<&str> { - registry - .libraries - .iter() - .map(|entry| entry.id.as_str()) - .collect() + registry.libraries.iter().map(|entry| entry.id.as_str()).collect() } /// A first launch: one unnamed library, open, in a folder of its own, written down. @@ -300,10 +280,7 @@ mod tests { assert!(profile.path().join(crate::layout::PREFERENCES).is_file()); std::fs::write(profile.path().join(DATABASE), b"later").unwrap(); registry_in(profile.path()); - assert!( - profile.path().join(DATABASE).is_file(), - "gathered a second time" - ); + assert!(profile.path().join(DATABASE).is_file(), "gathered a second time"); } /// Never taken for an absent file, which a first launch would write over: set aside as it @@ -324,17 +301,9 @@ mod tests { let aside = std::fs::read_dir(profile.path()) .unwrap() .filter_map(Result::ok) - .any(|entry| { - entry - .file_name() - .to_string_lossy() - .starts_with("libraries.json.unreadable-") - }); + .any(|entry| entry.file_name().to_string_lossy().starts_with("libraries.json.unreadable-")); assert!(aside); - assert!( - profile.path().join(&empty.directory).is_dir(), - "a folder is never deleted here" - ); + assert!(profile.path().join(&empty.directory).is_dir(), "a folder is never deleted here"); } /// A registry the system refuses to read is no absent one either. @@ -406,10 +375,7 @@ mod tests { let registry = registry_in(profile.path()); assert_eq!(registry.open.as_deref(), Some(added.id.as_str())); assert_eq!(registry.entry(&added.id).unwrap().name, "Home"); - assert_eq!( - open_directory_in(profile.path()).unwrap(), - profile.path().join(&added.directory) - ); + assert_eq!(open_directory_in(profile.path()).unwrap(), profile.path().join(&added.directory)); } #[test] @@ -447,10 +413,7 @@ mod tests { let profile = profile(); let only = registry_in(profile.path()).libraries[0].clone(); - assert!(matches!( - delete_in(profile.path(), &only.id), - Err(StorageError::LastLibrary) - )); + assert!(matches!(delete_in(profile.path(), &only.id), Err(StorageError::LastLibrary))); assert!(profile.path().join(&only.directory).is_dir()); } } diff --git a/crates/engine/src/name.rs b/crates/engine/src/name.rs index 55fc42051..08b543d39 100644 --- a/crates/engine/src/name.rs +++ b/crates/engine/src/name.rs @@ -7,10 +7,7 @@ use crate::error::ValidationError; pub(crate) fn readable(raw: &str, what: &str) -> Result { let trimmed = raw.trim(); if trimmed.is_empty() { - return Err(ValidationError::new( - "name", - format!("a {what} must have a readable name"), - )); + return Err(ValidationError::new("name", format!("a {what} must have a readable name"))); } Ok(trimmed.to_string()) diff --git a/crates/engine/src/notes.rs b/crates/engine/src/notes.rs index 0c5b5b148..27013e775 100644 --- a/crates/engine/src/notes.rs +++ b/crates/engine/src/notes.rs @@ -57,10 +57,7 @@ pub fn query_notes(engine: &Engine, query: &NotesQuery) -> Result Result { +pub(crate) fn query_notes_from_database(engine: &Engine, query: &NotesQuery) -> Result { let db = &engine.db; let mut connection = lock(db)?; let (notes, facets) = store::fetch(&mut connection, query)?; @@ -104,11 +101,7 @@ pub fn list_drawings(engine: &Engine) -> Result, AppErr Ok(pictures::drawings(connection, vault)?) } -fn picture_of( - engine: &Engine, - id: &str, - which: pictures::Which, -) -> Result, AppError> { +fn picture_of(engine: &Engine, id: &str, which: pictures::Which) -> Result, AppError> { let mut connection = lock(&engine.db)?; let (connection, vault) = connection.split(); Ok(pictures::read(connection, vault, id, which)?) @@ -151,10 +144,7 @@ pub fn duplicate_note(engine: &Engine, id: &str, title: String) -> Result Result { engine.write(|db| { // Read before anything is locked: two PNGs, or the patch is refused. - let drawn = patch - .pictures - .as_ref() - .map(drawing::DrawingPictures::decoded) - .transpose()?; + let drawn = patch.pictures.as_ref().map(drawing::DrawingPictures::decoded).transpose()?; // `Some(None)`: the pictures are taken away, the drawing having been emptied. let mut connection = lock(db)?; - let note = store::update_drawn( - &mut connection, - id, - patch, - drawn.as_ref().map(Option::as_ref), - Utc::now(), - )?; + let note = + store::update_drawn(&mut connection, id, patch, drawn.as_ref().map(Option::as_ref), Utc::now())?; let answer = display(&mut connection, note)?; let changed = Changed::notes([id.to_owned()]); @@ -217,10 +198,7 @@ pub fn convert_note( let mut connection = lock(db)?; let (note, previous) = store::convert(&mut connection, id, into, Utc::now())?; - let answer = convert::NoteConversion { - note: display(&mut connection, note)?, - previous, - }; + let answer = convert::NoteConversion { note: display(&mut connection, note)?, previous }; let changed = Changed::notes([id.to_owned()]); Ok((answer, changed)) }) @@ -239,17 +217,12 @@ pub fn list_revisions(engine: &Engine, id: &str) -> Result, AppErr } /// What going back to a kept body would change, line by line, against the current text. -pub fn revision_diff( - engine: &Engine, - id: &str, - revision_id: String, -) -> Result, AppError> { +pub fn revision_diff(engine: &Engine, id: &str, revision_id: String) -> Result, AppError> { let db = &engine.db; let mut connection = lock(db)?; let (connection, vault) = connection.split(); - let Some((current, version)) = store::revisions::compare(connection, vault, id, &revision_id)? - else { + let Some((current, version)) = store::revisions::compare(connection, vault, id, &revision_id)? else { return Err(StorageError::RevisionNotFound(revision_id).into()); }; @@ -259,11 +232,7 @@ pub fn revision_diff( /// Goes back to a kept body, dropping it and every body kept after it from the history. /// /// Leaves `updated_at` alone: putting something back is not editing it. -pub fn restore_revision( - engine: &Engine, - id: &str, - revision_id: &str, -) -> Result { +pub fn restore_revision(engine: &Engine, id: &str, revision_id: &str) -> Result { engine.write(|db| { let mut connection = lock(db)?; let note = store::restore_revision(&mut connection, id, revision_id)?; @@ -349,10 +318,7 @@ fn trash_matching( pub fn purge_notes(engine: &Engine, ids: &[String]) -> Result { engine.write(|db| { - let changed = Changed { - attachments: true, - ..Changed::notes(ids.to_vec()) - }; + let changed = Changed { attachments: true, ..Changed::notes(ids.to_vec()) }; Ok((count(trash::purge(db, ids)?), changed)) }) } @@ -365,10 +331,7 @@ pub fn empty_trash(engine: &Engine) -> Result { }; let answer = count(trash::purge(db, &ids)?); - let changed = Changed { - attachments: true, - ..Changed::default() - }; + let changed = Changed { attachments: true, ..Changed::default() }; Ok((answer, changed)) }) } @@ -388,10 +351,7 @@ pub fn move_notes( } /// The undo of [`move_notes`]: each note goes back to the space it left. -pub fn move_notes_back( - engine: &Engine, - placements: &[model::NotePlacement], -) -> Result { +pub fn move_notes_back(engine: &Engine, placements: &[model::NotePlacement]) -> Result { engine.write(|db| { let mut connection = lock(db)?; @@ -402,11 +362,7 @@ pub fn move_notes_back( } /// Normalized here as everywhere else, or a typed `#urgent` would not join `urgent`. -pub fn tag_notes( - engine: &Engine, - ids: &[String], - tags: &[String], -) -> Result, AppError> { +pub fn tag_notes(engine: &Engine, ids: &[String], tags: &[String]) -> Result, AppError> { engine.write(|db| { let normalized = model::normalize_tags(tags); @@ -430,11 +386,7 @@ pub fn untag_notes(engine: &Engine, pairs: &[model::NoteTag]) -> Result Result, AppError> { +pub fn remove_tag(engine: &Engine, ids: &[String], tag: String) -> Result, AppError> { engine.write(|db| { let Some(tag) = model::normalize_tags(&[tag]).into_iter().next() else { return Ok((Vec::new(), Changed::default())); @@ -486,10 +438,7 @@ pub fn set_priority( } /// The undo of [`set_priority`]: each note gets back the priority it had. -pub fn restore_priorities( - engine: &Engine, - previous: &[model::NotePriority], -) -> Result { +pub fn restore_priorities(engine: &Engine, previous: &[model::NotePriority]) -> Result { engine.write(|db| { let mut connection = lock(db)?; @@ -506,10 +455,7 @@ pub fn count_notes_tagged(engine: &Engine, tags: &[String]) -> Result Result, AppError> { @@ -521,10 +467,7 @@ pub fn list_tags(engine: &Engine) -> Result, AppError> { .facets(None) .tags .into_iter() - .map(|facet| TagUsage { - tag: facet.value, - note_count: facet.count, - }) + .map(|facet| TagUsage { tag: facet.value, note_count: facet.count }) .collect()) } @@ -585,10 +528,7 @@ pub fn fill_placeholders( let mut connection = lock(db)?; let globals = store::global_placeholder_values(&mut connection)?; - Ok(placeholder::fill( - content, - &placeholder::resolve(&globals, values), - )) + Ok(placeholder::fill(content, &placeholder::resolve(&globals, values))) } pub fn list_global_placeholders(engine: &Engine) -> Result, AppError> { @@ -610,10 +550,7 @@ pub fn set_global_placeholders( store::replace_global_placeholder_values(&mut connection, &retained)?; let answer = retained; - let changed = Changed { - globals: true, - ..Changed::default() - }; + let changed = Changed { globals: true, ..Changed::default() }; Ok((answer, changed)) }) } diff --git a/crates/engine/src/notes/calc.rs b/crates/engine/src/notes/calc.rs index 3abed2c89..a235e832b 100644 --- a/crates/engine/src/notes/calc.rs +++ b/crates/engine/src/notes/calc.rs @@ -32,11 +32,7 @@ pub struct CalcUnit { /// Exact decimals as text: a float would round them before the front decides how to. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde( - tag = "kind", - rename_all = "camelCase", - rename_all_fields = "camelCase" -)] +#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")] pub enum CalcValue { Number { value: String, @@ -86,11 +82,7 @@ pub struct SpanPart { /// Why a line has no result. It stays on its line: the others go on computing. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] -#[serde( - tag = "kind", - rename_all = "camelCase", - rename_all_fields = "camelCase" -)] +#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")] pub enum CalcError { /// In UTF-16 units from the start of the line. Unreadable { @@ -222,17 +214,9 @@ pub const CARD_LINES: usize = 4; /// 16, not 15,999…. Twenty-five figures stay, past what any display shows. fn tidy(decimal: Decimal) -> Decimal { let whole = decimal.trunc().abs(); - let figures = if whole.is_zero() { - 0 - } else { - u32::try_from(whole.to_string().len()).unwrap_or(28) - }; + let figures = if whole.is_zero() { 0 } else { u32::try_from(whole.to_string().len()).unwrap_or(28) }; let places = 25_u32.saturating_sub(figures); - if decimal.scale() > places { - decimal.round_dp(places) - } else { - decimal - } + if decimal.scale() > places { decimal.round_dp(places) } else { decimal } } fn text(decimal: Decimal) -> String { @@ -257,15 +241,8 @@ impl Units { .enumerate() .flat_map(|(index, unit)| unit.symbols.iter().map(move |symbol| (*symbol, index))) .collect(); - let factors = table - .iter() - .map(|unit| (unit.id, (unit.factor, unit.dim))) - .collect(); - Self { - table, - symbols, - factors, - } + let factors = table.iter().map(|unit| (unit.id, (unit.factor, unit.dim))).collect(); + Self { table, symbols, factors } } /// Base units in one, as above over below: a pixel's and an `em`'s size follow the sheet's @@ -300,11 +277,7 @@ impl Units { let amount = quantity.amount.abs(); let unit = [UnitId::Day, UnitId::Hour, UnitId::Minute, UnitId::Second] .into_iter() - .find(|unit| { - self.factors - .get(unit) - .is_some_and(|(factor, _)| amount >= *factor) - }) + .find(|unit| self.factors.get(unit).is_some_and(|(factor, _)| amount >= *factor)) .unwrap_or(UnitId::Millisecond); Some(Shown::One(unit)) } @@ -312,34 +285,22 @@ impl Units { fn show(&self, value: &Value, css: &Css) -> Result { let quantity = match value { Value::Percent { ratio, signed } => { - return Ok(CalcValue::Percent { - value: text(ratio * Decimal::ONE_HUNDRED), - signed: *signed, - }); + return Ok(CalcValue::Percent { value: text(ratio * Decimal::ONE_HUNDRED), signed: *signed }); } Value::Date(date) => return Ok(CalcValue::Date { date: *date }), Value::Quantity(quantity) => quantity, }; if quantity.dim.is_none() { - return Ok(CalcValue::Number { - value: text(quantity.amount), - unit: None, - }); + return Ok(CalcValue::Number { value: text(quantity.amount), unit: None }); } - let fits = |shown: &Shown| { - self.factor(*shown, css) - .is_some_and(|(_, _, dim)| dim == quantity.dim) - }; + let fits = |shown: &Shown| self.factor(*shown, css).is_some_and(|(_, _, dim)| dim == quantity.dim); let shown = quantity .unit .filter(fits) .or_else(|| self.natural(quantity)) .ok_or(CalcError::Unsupported)?; if quantity.dim.has_temperature() { - return Ok(CalcValue::Number { - value: text(quantity.amount), - unit: Some(shown.calc_unit()), - }); + return Ok(CalcValue::Number { value: text(quantity.amount), unit: Some(shown.calc_unit()) }); } let (above, below, _) = self.factor(shown, css).ok_or(CalcError::Unsupported)?; let value = quantity @@ -354,20 +315,11 @@ impl Units { { return Ok(span); } - Ok(CalcValue::Number { - value: text(value), - unit: Some(shown.calc_unit()), - }) + Ok(CalcValue::Number { value: text(value), unit: Some(shown.calc_unit()) }) } /// `45 jours en sem` is `6 sem 3 j`: the whole weeks, and what is left in whole days. - fn span( - &self, - amount: Decimal, - value: Decimal, - factor: Decimal, - unit: UnitId, - ) -> Option { + fn span(&self, amount: Decimal, value: Decimal, factor: Decimal, unit: UnitId) -> Option { let smaller = match unit { UnitId::Week => UnitId::Day, UnitId::Day => UnitId::Hour, @@ -382,16 +334,7 @@ impl Units { let (small, _) = self.factors.get(&smaller)?; let rest = (amount - whole * factor).checked_div(*small)?; rest.fract().is_zero().then(|| CalcValue::Span { - parts: vec![ - SpanPart { - value: text(whole), - unit, - }, - SpanPart { - value: text(rest), - unit: smaller, - }, - ], + parts: vec![SpanPart { value: text(whole), unit }, SpanPart { value: text(rest), unit: smaller }], }) } } @@ -400,32 +343,18 @@ fn spans_of(tokens: &[Token], kinds: &[Option]) -> Vec { tokens .iter() .zip(kinds) - .filter_map(|(token, kind)| { - kind.map(|kind| CalcSpan { - start: token.start, - end: token.end, - kind, - }) - }) + .filter_map(|(token, kind)| kind.map(|kind| CalcSpan { start: token.start, end: token.end, kind })) .collect() } /// The span of a comment written after an expression, from its `//` to the end. fn trailing_comment(line: &str) -> Option { let at = line.find("//")?; - Some(CalcSpan { - start: utf16(&line[..at]), - end: utf16(line), - kind: TokenKind::Comment, - }) + Some(CalcSpan { start: utf16(&line[..at]), end: utf16(line), kind: TokenKind::Comment }) } fn row(line: CalcLine, spans: Vec) -> CalcRow { - CalcRow { - line, - spans, - converting: None, - } + CalcRow { line, spans, converting: None } } /// What the sheet knows so far, line after line. @@ -442,11 +371,7 @@ struct Walk { } /// `255 en hex`, `5300 en sci`: a plain number written as the line asked. -fn notated( - value: &Value, - shown: CalcValue, - notation: Option, -) -> Result { +fn notated(value: &Value, shown: CalcValue, notation: Option) -> Result { let (Some(notation), Value::Quantity(quantity)) = (notation, value) else { return Ok(shown); }; @@ -456,11 +381,7 @@ fn notated( Ok(match notation { Notation::Base(radix) => { let (negative, digits) = maths::digits(quantity.amount, radix)?; - CalcValue::Base { - digits, - radix, - negative, - } + CalcValue::Base { digits, radix, negative } } Notation::Scientific => { let (mantissa, exponent) = maths::scientific(tidy(quantity.amount)); @@ -474,9 +395,7 @@ fn notated( negative, } } - Notation::Multiplier => CalcValue::Multiplier { - value: text(quantity.amount), - }, + Notation::Multiplier => CalcValue::Multiplier { value: text(quantity.amount) }, Notation::Decimal => shown, }) } @@ -486,9 +405,7 @@ fn label_end(tokens: &[Token]) -> Option { if !matches!(tokens.first()?.tok, Tok::Word(_)) { return None; } - let colon = tokens - .iter() - .position(|token| token.tok == Tok::Other(':'))?; + let colon = tokens.iter().position(|token| token.tok == Tok::Other(':'))?; tokens[..colon] .iter() .all(|token| token.tok != Tok::Symbol('=')) @@ -517,52 +434,22 @@ fn head<'t>(tokens: &'t [Token], spans: &mut Vec) -> Result, None => tokens, }; match tokens { - [ - Token { - tok: Tok::Word(word), - start, - end, - .. - }, - Token { - tok: Tok::Symbol('='), - .. - }, - .., - ] => { + [Token { tok: Tok::Word(word), start, end, .. }, Token { tok: Tok::Symbol('='), .. }, ..] => { if words::reserved(word) { - spans.push(CalcSpan { - start: *start, - end: *end, - kind: TokenKind::Error, - }); + spans.push(CalcSpan { start: *start, end: *end, kind: TokenKind::Error }); let error = CalcError::Reserved { word: word.clone() }; return Err(row(CalcLine::Error { error }, std::mem::take(spans))); } - Ok(Head { - tokens, - name: Some(word.clone()), - body: &tokens[2..], - }) + Ok(Head { tokens, name: Some(word.clone()), body: &tokens[2..] }) } - _ => Ok(Head { - tokens, - name: None, - body: tokens, - }), + _ => Ok(Head { tokens, name: None, body: tokens }), } } impl Walk { fn line(&mut self, index: u32, line: &str) -> CalcRow { let trimmed = line.trim(); - let whole = |kind| { - vec![CalcSpan { - start: 0, - end: utf16(line), - kind, - }] - }; + let whole = |kind| vec![CalcSpan { start: 0, end: utf16(line), kind }]; if trimmed.is_empty() { self.block.clear(); return row(CalcLine::Blank, Vec::new()); @@ -602,17 +489,9 @@ impl Walk { spans.push(CalcSpan { start: tokens[0].start, end: tokens[0].end, - kind: if setting.is_some() { - TokenKind::Keyword - } else { - TokenKind::Name - }, - }); - spans.push(CalcSpan { - start: tokens[1].start, - end: tokens[1].end, - kind: TokenKind::Operator, + kind: if setting.is_some() { TokenKind::Keyword } else { TokenKind::Name }, }); + spans.push(CalcSpan { start: tokens[1].start, end: tokens[1].end, kind: TokenKind::Operator }); } spans.extend(spans_of(body, &parser.kinds)); spans.extend(trailing_comment(line)); @@ -644,13 +523,8 @@ impl Walk { Err(error) => { let sentence = name.is_none() && used.is_empty() - && !tokens - .iter() - .any(|token| matches!(token.tok, Tok::Number(_) | Tok::Date(_))) - && matches!( - error, - CalcError::Unreadable { .. } | CalcError::UnknownName { .. } - ); + && !tokens.iter().any(|token| matches!(token.tok, Tok::Number(_) | Tok::Date(_))) + && matches!(error, CalcError::Unreadable { .. } | CalcError::UnknownName { .. }); if sentence { spans.retain(|span| span.kind == TokenKind::Comment); CalcLine::Text @@ -659,11 +533,7 @@ impl Walk { } } }; - CalcRow { - line, - spans, - converting, - } + CalcRow { line, spans, converting } } /// `ppi = 326`, `em = 20 px`: the sheet's setting from this line down. A size in pixels @@ -672,15 +542,11 @@ impl Walk { let (inch, ppi) = self.css.factor(UnitId::Pixel).ok_or(CalcError::Overflow)?; let pixels = match value { Value::Quantity(quantity) if quantity.dim.is_none() => quantity.amount, - Value::Quantity(quantity) - if quantity.dim == Dim::LENGTH && setting != CalcWord::Ppi => - { - quantity - .amount - .checked_mul(ppi) - .and_then(|product| product.checked_div(inch)) - .ok_or(CalcError::Overflow)? - } + Value::Quantity(quantity) if quantity.dim == Dim::LENGTH && setting != CalcWord::Ppi => quantity + .amount + .checked_mul(ppi) + .and_then(|product| product.checked_div(inch)) + .ok_or(CalcError::Overflow)?, other => { return Err(CalcError::Mismatch { expected: Dimension::Number, @@ -727,17 +593,8 @@ impl Walk { ) -> CalcLine { let dimension = value.dimension(); // `ppi = 326` sets the sheet: no name, nothing for `total` or `préc` to read. - if name - .as_deref() - .is_some_and(|name| words::setting(name).is_some()) - { - return CalcLine::Value { - value: shown, - name, - aggregate, - dimension, - places, - }; + if name.as_deref().is_some_and(|name| words::setting(name).is_some()) { + return CalcLine::Value { value: shown, name, aggregate, dimension, places }; } if let Some(name) = &name { self.current.insert(name.clone(), self.definitions.len()); @@ -753,13 +610,7 @@ impl Walk { if !aggregate && let Value::Quantity(quantity) = value { self.block.push(quantity); } - CalcLine::Value { - value: shown, - name, - aggregate, - dimension, - places, - } + CalcLine::Value { value: shown, name, aggregate, dimension, places } } } @@ -785,10 +636,7 @@ pub fn evaluate(sheet: &str, today: NaiveDate) -> CalcSheet { }) .collect(); - CalcSheet { - rows, - variables: walk.definitions, - } + CalcSheet { rows, variables: walk.definitions } } /// The last lines that gave something, the way a card shows the end of a sheet. @@ -799,12 +647,7 @@ pub fn card_lines(sheet: &str, today: NaiveDate) -> Vec { .into_iter() .zip(&lines) .filter_map(|(row, line)| match row.line { - CalcLine::Value { - value, - aggregate, - places, - .. - } => Some(CalcCardLine { + CalcLine::Value { value, aggregate, places, .. } => Some(CalcCardLine { expression: lexer::without_comment(line).trim().to_string(), value, aggregate, @@ -848,10 +691,7 @@ mod tests { fn value_text(value: &CalcValue) -> String { match value { CalcValue::Number { value, unit: None } => value.clone(), - CalcValue::Number { - value, - unit: Some(unit), - } => format!("{value} {}", unit_text(*unit)), + CalcValue::Number { value, unit: Some(unit) } => format!("{value} {}", unit_text(*unit)), CalcValue::Percent { value, signed } => { format!("{}{value} %", if *signed { "change " } else { "" }) } @@ -861,30 +701,19 @@ mod tests { .map(|part| format!("{} {:?}", part.value, part.unit)) .collect::>() .join(" "), - CalcValue::Base { - digits, - radix, - negative, - } => format!("{}{digits} base {radix}", if *negative { "-" } else { "" }), + CalcValue::Base { digits, radix, negative } => { + format!("{}{digits} base {radix}", if *negative { "-" } else { "" }) + } CalcValue::Scientific { mantissa, exponent } => format!("{mantissa}e{exponent}"), - CalcValue::Fraction { - numerator, - denominator, - negative, - } => format!( - "{}{numerator}/{denominator}", - if *negative { "-" } else { "" } - ), + CalcValue::Fraction { numerator, denominator, negative } => { + format!("{}{numerator}/{denominator}", if *negative { "-" } else { "" }) + } CalcValue::Multiplier { value } => format!("×{value}"), } } fn lines(sheet: &str) -> Vec { - evaluate(sheet, today()) - .rows - .iter() - .map(|row| written(&row.line)) - .collect() + evaluate(sheet, today()).rows.iter().map(|row| written(&row.line)).collect() } fn last(sheet: &str) -> String { @@ -930,11 +759,7 @@ mod tests { #[test] fn a_chain_of_powers_is_read_from_the_right() { - check(&[ - ("2 ^ 3 ^ 2", "512"), - ("2 ^ 2 ^ 2 ^ 2", "65536"), - ("2 ^ -1 ^ 2", "2"), - ]); + check(&[("2 ^ 3 ^ 2", "512"), ("2 ^ 2 ^ 2 ^ 2", "65536"), ("2 ^ -1 ^ 2", "2")]); assert_eq!(evaluate(&"2 ^ ".repeat(50_000), today()).rows.len(), 1); } @@ -958,13 +783,7 @@ mod tests { #[test] fn a_base_or_an_exponent_writes_a_number_too() { - check(&[ - ("0xFF", "255"), - ("0b1010", "10"), - ("0o377", "255"), - ("5,3e+3", "5300"), - ("2e-2", "0.02"), - ]); + check(&[("0xFF", "255"), ("0b1010", "10"), ("0o377", "255"), ("5,3e+3", "5300"), ("2e-2", "0.02")]); } // --- Operators. @@ -1018,10 +837,7 @@ mod tests { #[test] fn a_division_by_zero_is_an_error_of_its_own() { - check(&[ - ("1 / 0", "error: DivisionByZero"), - ("5 mod 0", "error: DivisionByZero"), - ]); + check(&[("1 / 0", "error: DivisionByZero"), ("5 mod 0", "error: DivisionByZero")]); } // --- Words around the figures. @@ -1033,10 +849,7 @@ mod tests { #[test] fn words_leading_up_to_a_result_and_quoted_text_are_read_past() { - check(&[ - ("275 € pour le \"Modèle 227\"", "275 Euro"), - ("999 € (pour l'iPhone)", "999 Euro"), - ]); + check(&[("275 € pour le \"Modèle 227\"", "275 Euro"), ("999 € (pour l'iPhone)", "999 Euro")]); } #[test] @@ -1051,10 +864,7 @@ mod tests { #[test] fn a_comment_line_and_a_heading_compute_nothing() { - assert_eq!( - lines("// note\n# Budget\n"), - ["comment", "# Budget", "blank"] - ); + assert_eq!(lines("// note\n# Budget\n"), ["comment", "# Budget", "blank"]); } #[test] @@ -1074,10 +884,7 @@ mod tests { #[test] fn a_name_used_before_it_is_given_is_unknown() { - assert_eq!( - lines("taux * 2\ntaux = 3"), - ["error: UnknownName { name: \"taux\" }", "3"] - ); + assert_eq!(lines("taux * 2\ntaux = 3"), ["error: UnknownName { name: \"taux\" }", "3"]); } #[test] @@ -1087,18 +894,12 @@ mod tests { #[test] fn a_name_defined_above_hides_a_value_word_from_its_line_down() { - assert_eq!( - lines("1\n2\ntotal\ntotal = 7\ntotal + 1"), - ["1", "2", "3", "7", "8"] - ); + assert_eq!(lines("1\n2\ntotal\ntotal = 7\ntotal + 1"), ["1", "2", "3", "7", "8"]); } #[test] fn previous_is_the_last_result_above() { - assert_eq!( - lines("10\nphrase sans chiffre\npréc * 2\nprev + 1"), - ["10", "text", "20", "21"] - ); + assert_eq!(lines("10\nphrase sans chiffre\npréc * 2\nprev + 1"), ["10", "text", "20", "21"]); check(&[("préc", "error: NoPrevious")]); } @@ -1111,10 +912,7 @@ mod tests { .iter() .map(|variable| (variable.name.as_str(), variable.line, variable.uses.clone())) .collect(); - assert_eq!( - found, - [("a", 0, vec![1]), ("b", 1, vec![3]), ("a", 2, vec![3])] - ); + assert_eq!(found, [("a", 0, vec![1]), ("b", 1, vec![3]), ("a", 2, vec![3])]); assert_eq!(value_text(&sheet.variables[1].value), "4"); } @@ -1124,9 +922,7 @@ mod tests { fn total_and_mean_read_the_quantities_above_in_their_block() { assert_eq!( lines("10 €\n20 €\ntotal\nmoyenne\n\n5 €\ntotal"), - [ - "10 Euro", "20 Euro", "30 Euro", "15 Euro", "blank", "5 Euro", "5 Euro" - ] + ["10 Euro", "20 Euro", "30 Euro", "15 Euro", "blank", "5 Euro", "5 Euro"] ); } @@ -1148,15 +944,7 @@ mod tests { let aggregates: Vec<_> = sheet .rows .iter() - .map(|row| { - matches!( - row.line, - CalcLine::Value { - aggregate: true, - .. - } - ) - }) + .map(|row| matches!(row.line, CalcLine::Value { aggregate: true, .. })) .collect(); assert_eq!(aggregates, [false, false, true, true]); assert_eq!(written(&sheet.rows[3].line), "3"); @@ -1176,10 +964,7 @@ mod tests { #[test] fn quantities_written_side_by_side_add_up() { - check(&[ - ("3 h 20 min en min", "200 Minute"), - ("1 m 20 cm", "1.2 Metre"), - ]); + check(&[("3 h 20 min en min", "200 Minute"), ("1 m 20 cm", "1.2 Metre")]); } #[test] @@ -1214,10 +999,7 @@ mod tests { #[test] fn euros_and_dollars_are_never_converted_into_each_other() { - check(&[ - ("100 € en $", "error: Currency"), - ("100 $ en €", "error: Currency"), - ]); + check(&[("100 € en $", "error: Currency"), ("100 $ en €", "error: Currency")]); } #[test] @@ -1262,16 +1044,7 @@ mod tests { lines( "3 in en px\nppi = 326\n1 in en px\n2 em en px\nem = 20 px\n2 em en px\nrem = 18\n1 rem en px" ), - [ - "288 Pixel", - "326", - "326 Pixel", - "32 Pixel", - "20 Pixel", - "40 Pixel", - "18 Pixel", - "18 Pixel" - ] + ["288 Pixel", "326", "326 Pixel", "32 Pixel", "20 Pixel", "40 Pixel", "18 Pixel", "18 Pixel"] ); } @@ -1304,10 +1077,7 @@ mod tests { #[test] fn in_is_an_inch_after_a_number_and_a_conversion_before_a_notation() { - check(&[ - ("2 in en cm", "5.08 Centimetre"), - ("255 in hex", "FF base 16"), - ]); + check(&[("2 in en cm", "5.08 Centimetre"), ("255 in hex", "FF base 16")]); } // --- Functions and constants. @@ -1367,13 +1137,7 @@ mod tests { let sheet = evaluate("1 / 3 à 2 décimales\npréc * 3", today()); assert_eq!(written(&sheet.rows[0].line), "0.33"); - assert!(matches!( - sheet.rows[0].line, - CalcLine::Value { - places: Some(2), - .. - } - )); + assert!(matches!(sheet.rows[0].line, CalcLine::Value { places: Some(2), .. })); assert_eq!(written(&sheet.rows[1].line), "0.99"); } @@ -1461,10 +1225,7 @@ mod tests { #[test] fn a_proportion_solves_for_its_unknown() { - check(&[ - ("6 est à 60 ce que 8 est à combien", "80"), - ("6 is to 60 as 8 is to what", "80"), - ]); + check(&[("6 est à 60 ce que 8 est à combien", "80"), ("6 is to 60 as 8 is to what", "80")]); } // --- Finance. @@ -1486,9 +1247,7 @@ mod tests { ("valeur actuelle de 1 210 € dans 2 ans à 10 %", "1000 Euro"), ]); assert!(last("mensualité de 10 000 € sur 1 an à 12 %").starts_with("888.48")); - assert!( - last("rendement annuel sur 100 € investis 200 € récupérés en 1 an").starts_with("100") - ); + assert!(last("rendement annuel sur 100 € investis 200 € récupérés en 1 an").starts_with("100")); } #[test] @@ -1592,17 +1351,10 @@ mod tests { #[test] fn a_label_and_a_setting_are_coloured_apart_from_names() { let kinds = |line: &str| -> Vec { - evaluate(line, today()).rows[0] - .spans - .iter() - .map(|span| span.kind) - .collect() + evaluate(line, today()).rows[0].spans.iter().map(|span| span.kind).collect() }; - assert_eq!( - kinds("Prix : 3")[..2], - [TokenKind::Comment, TokenKind::Number] - ); + assert_eq!(kinds("Prix : 3")[..2], [TokenKind::Comment, TokenKind::Number]); assert_eq!(kinds("ppi = 300")[0], TokenKind::Keyword); assert_eq!(kinds("Une phrase"), []); assert_eq!(kinds("en = 5")[0], TokenKind::Error); @@ -1656,14 +1408,8 @@ mod tests { fn a_card_line_carries_its_aggregate_and_its_places() { let shown = card_lines("1\n2\ntotal\n1 / 3 à 2 décimales", today()); - let found: Vec<_> = shown - .iter() - .map(|line| (line.aggregate, line.places)) - .collect(); - assert_eq!( - found, - [(false, None), (false, None), (true, None), (false, Some(2))] - ); + let found: Vec<_> = shown.iter().map(|line| (line.aggregate, line.places)).collect(); + assert_eq!(found, [(false, None), (false, None), (true, None), (false, Some(2))]); } #[test] @@ -1752,14 +1498,10 @@ mod tests { #[test] fn a_form_of_several_words_wins_over_a_name_of_one() { assert!( - last("mensualité = 100 €\nmensualité de 10 000 € sur 6 ans à 6 %") - .starts_with("165.72887893") + last("mensualité = 100 €\nmensualité de 10 000 € sur 6 ans à 6 %").starts_with("165.72887893") ); assert_eq!(last("mensualité = 100 €\nmensualité + 1 €"), "101 Euro"); - assert!( - last("total = $2\ntotal cost of $10,000 over 6 years at 6%") - .starts_with("11932.479283") - ); + assert!(last("total = $2\ntotal cost of $10,000 over 6 years at 6%").starts_with("11932.479283")); assert_eq!(last("racine = 5\nracine carrée(16) + racine"), "9"); } @@ -1769,10 +1511,7 @@ mod tests { assert!(last(&format!("{named}capital après durée à taux")).starts_with("1225.04")); assert!(last(&format!("{named}capital pendant durée à taux")).starts_with("1225.04")); - assert!( - last("principal = $1,000\nterm = 3 years\nprincipal after term @ 7%") - .starts_with("1225.04") - ); + assert!(last("principal = $1,000\nterm = 3 years\nprincipal after term @ 7%").starts_with("1225.04")); assert_eq!(last("prix = 275 €\nprix for the \"Model 227\""), "275 Euro"); } @@ -1840,11 +1579,7 @@ mod tests { #[test] fn a_scale_is_read_in_its_case_and_a_scale_word_in_any() { - check(&[ - ("1 Mille milliards", "1000000000000"), - ("5 K", "5 Kelvin"), - ("5 k", "5000"), - ]); + check(&[("1 Mille milliards", "1000000000000"), ("5 K", "5 Kelvin"), ("5 k", "5000")]); } #[test] @@ -1867,18 +1602,12 @@ mod tests { #[test] fn a_remark_in_parentheses_may_hold_punctuation_or_a_quote() { - check(&[ - ("999 € (pour l'iPhone !)", "999 Euro"), - ("999 € (\"iPhone\")", "999 Euro"), - ]); + check(&[("999 € (pour l'iPhone !)", "999 Euro"), ("999 € (\"iPhone\")", "999 Euro")]); } #[test] fn a_percentage_rounds_as_a_percentage_and_a_date_does_not_round() { - check(&[ - ("33,333 % à 1 décimale", "33.3 %"), - ("aujourd'hui arrondi", "error: Unsupported"), - ]); + check(&[("33,333 % à 1 décimale", "33.3 %"), ("aujourd'hui arrondi", "error: Unsupported")]); } #[test] @@ -1886,10 +1615,7 @@ mod tests { check(&[ ("40 to 90 is what x", "×2.25"), ("5 is to 10 as what is to 80", "40"), - ( - "6 est à 60 ce que combien est à combien", - "error: Unreadable { at: 39 }", - ), + ("6 est à 60 ce que combien est à combien", "error: Unreadable { at: 39 }"), ("6 est à 60 8 est à combien", "error: Unreadable { at: 11 }"), ("6 est à 60 ce que 8", "error: Unreadable { at: 19 }"), ]); @@ -1903,10 +1629,7 @@ mod tests { ("255 en base 3", "error: Unsupported"), ("0,25 en %", "25 %"), ("20 % en %", "20 %"), - ( - "3 km en %", - "error: NotConvertible { from: Length, to: None }", - ), + ("3 km en %", "error: NotConvertible { from: Length, to: None }"), ]); } @@ -1934,18 +1657,9 @@ mod tests { #[test] fn a_finance_line_says_what_it_could_not_read() { check(&[ - ( - "1 000 € après 3 ans à 7 % composés bizarrement", - "error: Unreadable { at: 35 }", - ), - ( - "valeur actuelle de 1 000 € 20 ans à 10 %", - "error: Unreadable { at: 27 }", - ), - ( - "rendement annuel sur 100 € investis 200 € récupérés en 0 an", - "error: DivisionByZero", - ), + ("1 000 € après 3 ans à 7 % composés bizarrement", "error: Unreadable { at: 35 }"), + ("valeur actuelle de 1 000 € 20 ans à 10 %", "error: Unreadable { at: 27 }"), + ("rendement annuel sur 100 € investis 200 € récupérés en 0 an", "error: DivisionByZero"), ]); assert!(last("1 000 € après 3 kg à 7 %").starts_with("error: Mismatch { expected: Time")); } diff --git a/crates/engine/src/notes/calc/eval.rs b/crates/engine/src/notes/calc/eval.rs index 44c7ef55c..175d05d8c 100644 --- a/crates/engine/src/notes/calc/eval.rs +++ b/crates/engine/src/notes/calc/eval.rs @@ -25,10 +25,7 @@ impl Shown { pub(super) fn calc_unit(self) -> CalcUnit { match self { Self::One(unit) => CalcUnit { unit, per: None }, - Self::Per(unit, per) => CalcUnit { - unit, - per: Some(per), - }, + Self::Per(unit, per) => CalcUnit { unit, per: Some(per) }, } } } @@ -41,10 +38,7 @@ pub(super) struct Factor { } impl Factor { - const ONE: Self = Self { - above: Decimal::ONE, - below: Decimal::ONE, - }; + const ONE: Self = Self { above: Decimal::ONE, below: Decimal::ONE }; fn apply(self, number: Decimal) -> Result { number @@ -93,12 +87,7 @@ impl Value { } fn number(amount: Decimal) -> Self { - Self::Quantity(Quantity { - amount, - dim: Dim::NONE, - unit: None, - spans: false, - }) + Self::Quantity(Quantity { amount, dim: Dim::NONE, unit: None, spans: false }) } } @@ -275,11 +264,7 @@ impl<'a> Parser<'a> { } fn skip_quoted(&mut self) { - while self - .tokens - .get(self.at) - .is_some_and(|token| token.tok == Tok::Quoted) - { + while self.tokens.get(self.at).is_some_and(|token| token.tok == Tok::Quoted) { self.kinds[self.at] = Some(TokenKind::Comment); self.at += 1; } @@ -290,17 +275,12 @@ impl<'a> Parser<'a> { fn remark_end(&self) -> Option { self.peek_symbol(&['('])?; let inside = self.at + 1; - let close = inside - + self.tokens[inside..] - .iter() - .position(|token| token.tok == Tok::Symbol(')'))?; - let words = self.tokens[inside..close] - .iter() - .all(|token| match &token.tok { - Tok::Word(word) => !self.context.variables.contains_key(word), - Tok::Other(_) | Tok::Quoted => true, - _ => false, - }); + let close = inside + self.tokens[inside..].iter().position(|token| token.tok == Tok::Symbol(')'))?; + let words = self.tokens[inside..close].iter().all(|token| match &token.tok { + Tok::Word(word) => !self.context.variables.contains_key(word), + Tok::Other(_) | Tok::Quoted => true, + _ => false, + }); (close > inside && words).then_some(close + 1) } @@ -374,9 +354,7 @@ impl<'a> Parser<'a> { } fn notation_at(&self, index: usize) -> bool { - self.tokens - .get(index) - .is_some_and(|token| token.tok == Tok::Symbol('%')) + self.tokens.get(index).is_some_and(|token| token.tok == Tok::Symbol('%')) || NOTATIONS .iter() .map(|(word, _)| *word) @@ -388,10 +366,7 @@ impl<'a> Parser<'a> { fn factor_of(&self, unit: &UnitDef) -> Factor { match self.context.css.factor(unit.id) { Some((above, below)) => Factor { above, below }, - None => Factor { - above: unit.factor, - below: Decimal::ONE, - }, + None => Factor { above: unit.factor, below: Decimal::ONE }, } } @@ -405,10 +380,7 @@ impl<'a> Parser<'a> { fn unit_at(&self, index: usize) -> Option<&'a UnitDef> { let text = self.text_at(index)?; - self.context - .symbols - .get(text.as_str()) - .map(|&found| &self.context.units[found]) + self.context.symbols.get(text.as_str()).map(|&found| &self.context.units[found]) } /// A unit, or one over another written without a space: `€/h`, `Mo/s`. Its factor comes @@ -427,11 +399,7 @@ impl<'a> Parser<'a> { self.take(TokenKind::Unit); self.take(TokenKind::Unit); let factor = self.factor_of(first).over(self.factor_of(second))?; - return Some(( - Shown::Per(first.id, second.id), - first.dim.over(second.dim), - factor, - )); + return Some((Shown::Per(first.id, second.id), first.dim.over(second.dim), factor)); } Some((Shown::One(first.id), first.dim, self.factor_of(first))) } @@ -450,8 +418,7 @@ impl<'a> Parser<'a> { value = share_of(value, &whole, share).map_err(|error| self.blame(error))?; } else if self.eat(CalcWord::IsTo) { value = self.proportion(value)?; - } else if self.duration_after(CalcWord::After) || self.duration_after(CalcWord::During) - { + } else if self.duration_after(CalcWord::After) || self.duration_after(CalcWord::During) { value = self.compound(value)?; } else if self.eat(CalcWord::Invested) { // `500 € investis 1 500 € récupérés` is ×3. @@ -505,22 +472,15 @@ impl<'a> Parser<'a> { }; let step = self.nearest()?; if direction.is_some() || step.is_some() { - let (direction, step) = ( - direction.unwrap_or(Rounding::Nearest), - step.unwrap_or(Decimal::ONE), - ); - let rounded = self.in_its_unit(value.clone(), |amount| { - maths::round_to(amount, step, direction) - }); + let (direction, step) = (direction.unwrap_or(Rounding::Nearest), step.unwrap_or(Decimal::ONE)); + let rounded = self.in_its_unit(value.clone(), |amount| maths::round_to(amount, step, direction)); return rounded.map(Some).map_err(|error| self.blame(error)); } let Some(places) = self.places() else { return Ok(None); }; self.places = Some(places); - Ok(Some(self.in_its_unit(value.clone(), |amount| { - Ok(maths::round_places(amount, places)) - })?)) + Ok(Some(self.in_its_unit(value.clone(), |amount| Ok(maths::round_places(amount, places)))?)) } /// `au 10 près`, `au millier près`, `to nearest 10`: the step to round to. @@ -552,8 +512,7 @@ impl<'a> Parser<'a> { let opener = [CalcWord::At, CalcWord::Convert, CalcWord::To] .into_iter() .find_map(|word| self.sees(word))?; - let Some(Tok::Number(places)) = self.tokens.get(self.at + opener).map(|token| &token.tok) - else { + let Some(Tok::Number(places)) = self.tokens.get(self.at + opener).map(|token| &token.tok) else { return None; }; let places = places.to_u32().filter(|_| places.fract().is_zero())?; @@ -571,20 +530,15 @@ impl<'a> Parser<'a> { } /// Rounded in the unit it is shown in: `1,236 km à 2 décimales` is 1,24 km, not 1 236 m. - fn in_its_unit( - &self, - value: Value, - round: impl Fn(Decimal) -> Result, - ) -> Answer { + fn in_its_unit(&self, value: Value, round: impl Fn(Decimal) -> Result) -> Answer { match value { Value::Quantity(quantity) => { let Factor { above, below } = match quantity.unit { _ if quantity.dim.has_temperature() => Factor::ONE, Some(Shown::One(unit)) => self.unit_factor(unit), - Some(Shown::Per(top, bottom)) => self - .unit_factor(top) - .over(self.unit_factor(bottom)) - .ok_or_else(overflow)?, + Some(Shown::Per(top, bottom)) => { + self.unit_factor(top).over(self.unit_factor(bottom)).ok_or_else(overflow)? + } None => Factor::ONE, }; let shown = quantity @@ -600,10 +554,7 @@ impl<'a> Parser<'a> { } Value::Percent { ratio, signed } => { let percent = round(ratio * Decimal::ONE_HUNDRED)?; - Ok(Value::Percent { - ratio: percent / Decimal::ONE_HUNDRED, - signed, - }) + Ok(Value::Percent { ratio: percent / Decimal::ONE_HUNDRED, signed }) } Value::Date(_) => Err(CalcError::Unsupported), } @@ -649,9 +600,7 @@ impl<'a> Parser<'a> { true }); if percent { - return change(from, to) - .map(Some) - .map_err(|error| self.blame(error)); + return change(from, to).map(Some).map_err(|error| self.blame(error)); } if self.eat(CalcWord::WhatTimes) { let times = divide(to.clone(), from.clone()).map_err(|error| self.blame(error))?; @@ -667,19 +616,11 @@ impl<'a> Parser<'a> { if !self.eat(CalcWord::Like) { return Err(self.unreadable()); } - let third = if self.eat(CalcWord::What) { - None - } else { - Some(self.additive()?) - }; + let third = if self.eat(CalcWord::What) { None } else { Some(self.additive()?) }; if !self.eat(CalcWord::IsTo) { return Err(self.unreadable()); } - let fourth = if self.eat(CalcWord::What) { - None - } else { - Some(self.additive()?) - }; + let fourth = if self.eat(CalcWord::What) { None } else { Some(self.additive()?) }; let found = match (third, fourth) { // The ratio first, so the unknown keeps the unit of the value it scales. (Some(third), None) => divide(third, first).and_then(|ratio| multiply(ratio, second)), @@ -693,10 +634,9 @@ impl<'a> Parser<'a> { fn written(&mut self, value: Value, notation: Notation) -> Answer { // `50 % en fraction` is 1/2: a percentage written as the number it is. let value = match (value, notation) { - ( - Value::Percent { ratio, .. }, - Notation::Fraction | Notation::Multiplier | Notation::Decimal, - ) => Value::number(ratio), + (Value::Percent { ratio, .. }, Notation::Fraction | Notation::Multiplier | Notation::Decimal) => { + Value::number(ratio) + } (value, _) => value, }; let amount = plain(&value).map_err(|error| self.blame(error))?; @@ -760,14 +700,10 @@ impl<'a> Parser<'a> { self.take(TokenKind::Unit); return match value { Value::Percent { .. } => Ok(value), - Value::Quantity(quantity) if quantity.dim.is_none() => Ok(Value::Percent { - ratio: quantity.amount, - signed: false, - }), - other => Err(self.blame(CalcError::NotConvertible { - from: other.dimension(), - to: None, - })), + Value::Quantity(quantity) if quantity.dim.is_none() => { + Ok(Value::Percent { ratio: quantity.amount, signed: false }) + } + other => Err(self.blame(CalcError::NotConvertible { from: other.dimension(), to: None })), }; } let Some((shown, dim, _)) = self.read_unit() else { @@ -858,11 +794,7 @@ impl<'a> Parser<'a> { fn product(&mut self) -> Option { if let Some(symbol) = self.peek_symbol(&['×', '*', '/', '÷']) { self.take(TokenKind::Operator); - return Some(if matches!(symbol, '×' | '*') { - Product::Times - } else { - Product::Over - }); + return Some(if matches!(symbol, '×' | '*') { Product::Times } else { Product::Over }); } if self.eat_as(CalcWord::Times, TokenKind::Operator) { Some(Product::Times) @@ -900,12 +832,8 @@ impl<'a> Parser<'a> { return Err(self.unreadable()); } let right = self.power()?; - left = if solving { - solve(ratio, share, right) - } else { - applied(ratio, share, right) - } - .map_err(|error| self.blame(error))?; + left = if solving { solve(ratio, share, right) } else { applied(ratio, share, right) } + .map_err(|error| self.blame(error))?; } else if !self.no_over && self.eat(CalcWord::Over) { let right = self.power()?; left = ratio(&left, &right).map_err(|error| self.blame(error))?; @@ -946,11 +874,7 @@ impl<'a> Parser<'a> { if let Some(symbol) = self.peek_symbol(&['-', '−', '+']) { self.take(TokenKind::Operator); let value = self.unary()?; - return if symbol == '+' { - Ok(value) - } else { - negate(value) - }; + return if symbol == '+' { Ok(value) } else { negate(value) }; } self.primary() } @@ -997,16 +921,11 @@ impl<'a> Parser<'a> { for _ in 0..taken { self.take(TokenKind::Number); } - number = number - .checked_mul(Decimal::from(scale)) - .ok_or_else(overflow)?; + number = number.checked_mul(Decimal::from(scale)).ok_or_else(overflow)?; } if self.peek_symbol(&['%']).is_some() { self.take(TokenKind::Unit); - return Ok(Value::Percent { - ratio: number / Decimal::ONE_HUNDRED, - signed: false, - }); + return Ok(Value::Percent { ratio: number / Decimal::ONE_HUNDRED, signed: false }); } // `255 in hex`, `0,35 in %`: `in` before what a number is written as converts it, inches aside. if self.sees(CalcWord::Convert) == Some(1) && self.notation_at(self.at + 1) { @@ -1015,31 +934,18 @@ impl<'a> Parser<'a> { let Some((shown, dim, factor)) = self.read_unit() else { return Ok(Value::number(number)); }; - let mut amount = if dim.has_temperature() { - number - } else { - factor.apply(number)? - }; + let mut amount = if dim.has_temperature() { number } else { factor.apply(number)? }; while let Some(Tok::Number(next)) = self.peek().cloned() && !dim.has_temperature() - && self - .unit_at(self.at + 1) - .is_some_and(|unit| unit.dim == dim) + && self.unit_at(self.at + 1).is_some_and(|unit| unit.dim == dim) { self.take(TokenKind::Number); let Some((_, _, factor)) = self.read_unit() else { break; }; - amount = amount - .checked_add(factor.apply(next)?) - .ok_or_else(overflow)?; + amount = amount.checked_add(factor.apply(next)?).ok_or_else(overflow)?; } - Ok(Value::Quantity(Quantity { - amount, - dim, - unit: Some(shown), - spans: false, - })) + Ok(Value::Quantity(Quantity { amount, dim, unit: Some(shown), spans: false })) } /// `$1,000`, `€500`: a currency written before its amount, as English does. @@ -1056,9 +962,7 @@ impl<'a> Parser<'a> { for _ in 0..taken { self.take(TokenKind::Number); } - number = number - .checked_mul(Decimal::from(scale)) - .ok_or_else(overflow)?; + number = number.checked_mul(Decimal::from(scale)).ok_or_else(overflow)?; } Ok(Value::Quantity(Quantity { amount: self.factor_of(unit).apply(number)?, @@ -1099,21 +1003,11 @@ impl<'a> Parser<'a> { } let shifted = |days: i64, today: NaiveDate| { let shift = Days::new(days.unsigned_abs()); - if days < 0 { - today.checked_sub_days(shift) - } else { - today.checked_add_days(shift) - } + if days < 0 { today.checked_sub_days(shift) } else { today.checked_add_days(shift) } }; - for (day, days) in [ - (CalcWord::Today, 0), - (CalcWord::Tomorrow, 1), - (CalcWord::Yesterday, -1), - ] { + for (day, days) in [(CalcWord::Today, 0), (CalcWord::Tomorrow, 1), (CalcWord::Yesterday, -1)] { if self.eat(day) { - return shifted(days, self.context.today) - .map(Value::Date) - .ok_or_else(overflow); + return shifted(days, self.context.today).map(Value::Date).ok_or_else(overflow); } } for (block, mean) in [(CalcWord::Total, false), (CalcWord::Mean, true)] { @@ -1122,9 +1016,7 @@ impl<'a> Parser<'a> { return aggregate(self.context.block, mean); } } - let phi = "1.6180339887498948482045868344" - .parse() - .unwrap_or(Decimal::ONE); + let phi = "1.6180339887498948482045868344".parse().unwrap_or(Decimal::ONE); for (constant, value) in [ (CalcWord::Pi, Decimal::PI), (CalcWord::E, Decimal::E), @@ -1161,9 +1053,7 @@ impl<'a> Parser<'a> { if words::reserved(word) { return Err(CalcError::Unreadable { at }); } - Err(CalcError::UnknownName { - name: word.to_string(), - }) + Err(CalcError::UnknownName { name: word.to_string() }) } } @@ -1195,11 +1085,7 @@ fn add(left: Value, right: Value, plus: bool) -> Answer { if a.dim != b.dim { return Err(mismatch(&Value::Quantity(a), &Value::Quantity(b))); } - let right = if a.dim.has_temperature() { - in_degrees_of(&b, &a) - } else { - b.amount - }; + let right = if a.dim.has_temperature() { in_degrees_of(&b, &a) } else { b.amount }; Ok(Value::Quantity(Quantity { amount: a.amount.checked_add(signed(right)).ok_or_else(overflow)?, unit: a.unit.or(b.unit), @@ -1210,15 +1096,11 @@ fn add(left: Value, right: Value, plus: bool) -> Answer { // `250 + 20 %` is 300: a percentage added to a quantity is a share of it. (Value::Quantity(a), Value::Percent { ratio, .. }) => { let factor = Decimal::ONE + signed(ratio); - Ok(Value::Quantity(Quantity { - amount: a.amount.checked_mul(factor).ok_or_else(overflow)?, - ..a - })) + Ok(Value::Quantity(Quantity { amount: a.amount.checked_mul(factor).ok_or_else(overflow)?, ..a })) + } + (Value::Percent { ratio: a, .. }, Value::Percent { ratio: b, .. }) => { + Ok(Value::Percent { ratio: a + signed(b), signed: false }) } - (Value::Percent { ratio: a, .. }, Value::Percent { ratio: b, .. }) => Ok(Value::Percent { - ratio: a + signed(b), - signed: false, - }), (Value::Date(date), Value::Quantity(shift)) if shift.dim == Dim::TIME => { shift_date(date, &shift, plus) } @@ -1252,11 +1134,7 @@ fn shift_date(date: NaiveDate, shift: &Quantity, plus: bool) -> Answer { let moved = match (count, steps >= 0) { (true, ahead) => { let months = Months::new(u32::try_from(size).map_err(|_| overflow())?); - if ahead { - date.checked_add_months(months) - } else { - date.checked_sub_months(months) - } + if ahead { date.checked_add_months(months) } else { date.checked_sub_months(months) } } (false, true) => date.checked_add_days(Days::new(size)), (false, false) => date.checked_sub_days(Days::new(size)), @@ -1316,8 +1194,7 @@ fn shown_for(dim: Dim, among: &[&Quantity]) -> Option { fn multiply(left: Value, right: Value) -> Answer { match (left, right) { (Value::Quantity(a), Value::Quantity(b)) => { - if (a.dim.has_temperature() && !b.dim.is_none()) - || (b.dim.has_temperature() && !a.dim.is_none()) + if (a.dim.has_temperature() && !b.dim.is_none()) || (b.dim.has_temperature() && !a.dim.is_none()) { return Err(CalcError::Unsupported); } @@ -1330,14 +1207,12 @@ fn multiply(left: Value, right: Value) -> Answer { })) } (Value::Quantity(a), Value::Percent { ratio, .. }) - | (Value::Percent { ratio, .. }, Value::Quantity(a)) => Ok(Value::Quantity(Quantity { - amount: a.amount.checked_mul(ratio).ok_or_else(overflow)?, - ..a - })), - (Value::Percent { ratio: a, .. }, Value::Percent { ratio: b, .. }) => Ok(Value::Percent { - ratio: a.checked_mul(b).ok_or_else(overflow)?, - signed: false, - }), + | (Value::Percent { ratio, .. }, Value::Quantity(a)) => { + Ok(Value::Quantity(Quantity { amount: a.amount.checked_mul(ratio).ok_or_else(overflow)?, ..a })) + } + (Value::Percent { ratio: a, .. }, Value::Percent { ratio: b, .. }) => { + Ok(Value::Percent { ratio: a.checked_mul(b).ok_or_else(overflow)?, signed: false }) + } (left, right) => Err(mismatch(&left, &right)), } } @@ -1366,20 +1241,12 @@ fn divide(left: Value, right: Value) -> Answer { } else { shown_for(dim, &[&a, &b]) }; - Ok(Value::Quantity(Quantity { - amount: by(a.amount, b.amount)?, - dim, - unit, - spans: false, - })) + Ok(Value::Quantity(Quantity { amount: by(a.amount, b.amount)?, dim, unit, spans: false })) } - (Value::Quantity(a), Value::Percent { ratio, .. }) => Ok(Value::Quantity(Quantity { - amount: by(a.amount, ratio)?, - ..a - })), - (Value::Percent { ratio: a, .. }, Value::Percent { ratio: b, .. }) => { - Ok(Value::number(by(a, b)?)) + (Value::Quantity(a), Value::Percent { ratio, .. }) => { + Ok(Value::Quantity(Quantity { amount: by(a.amount, ratio)?, ..a })) } + (Value::Percent { ratio: a, .. }, Value::Percent { ratio: b, .. }) => Ok(Value::number(by(a, b)?)), (left, right) => Err(mismatch(&left, &right)), } } @@ -1391,47 +1258,28 @@ impl Parser<'_> { let degree = match self.peek().cloned() { Some(Tok::Number(number)) if matches!(function, Function::Root | Function::Log) - && self - .tokens - .get(self.at + 1) - .is_some_and(|token| token.tok == Tok::Symbol('(')) => + && self.tokens.get(self.at + 1).is_some_and(|token| token.tok == Tok::Symbol('(')) => { self.take(TokenKind::Number); Some(number) } _ => None, }; - let argument = if self.peek_symbol(&['(']).is_some() { - self.primary()? - } else { - self.power()? - }; + let argument = if self.peek_symbol(&['(']).is_some() { self.primary()? } else { self.power()? }; let number = |value: &Value| plain(value); let result = match function { Function::Root => { let degree = degree.unwrap_or(Decimal::TWO); - number(&argument) - .and_then(|x| maths::root_of(x, degree)) - .map(Value::number) + number(&argument).and_then(|x| maths::root_of(x, degree)).map(Value::number) } - Function::Cbrt => number(&argument) - .and_then(|x| maths::root(x, 3)) - .map(Value::number), - Function::Log => number(&argument) - .and_then(|x| maths::log(x, degree)) - .map(Value::number), + Function::Cbrt => number(&argument).and_then(|x| maths::root(x, 3)).map(Value::number), + Function::Log => number(&argument).and_then(|x| maths::log(x, degree)).map(Value::number), Function::Ln => number(&argument).and_then(maths::ln).map(Value::number), Function::Abs => match argument { Value::Quantity(quantity) if !quantity.dim.has_temperature() => { - Ok(Value::Quantity(Quantity { - amount: quantity.amount.abs(), - ..quantity - })) + Ok(Value::Quantity(Quantity { amount: quantity.amount.abs(), ..quantity })) } - Value::Percent { ratio, signed } => Ok(Value::Percent { - ratio: ratio.abs(), - signed, - }), + Value::Percent { ratio, signed } => Ok(Value::Percent { ratio: ratio.abs(), signed }), _ => Err(CalcError::Unsupported), }, Function::Round | Function::Ceil | Function::Floor => { @@ -1440,9 +1288,7 @@ impl Parser<'_> { Function::Floor => Rounding::Down, _ => Rounding::Nearest, }; - self.in_its_unit(argument, |amount| { - maths::round_to(amount, Decimal::ONE, direction) - }) + self.in_its_unit(argument, |amount| maths::round_to(amount, Decimal::ONE, direction)) } Function::Written(notation) => return self.written(argument, notation), }; @@ -1462,22 +1308,14 @@ impl Parser<'_> { let next = self.additive()?; let order = match (&found, &next) { (Value::Quantity(a), Value::Quantity(b)) if a.dim == b.dim => { - let b_amount = if a.dim.has_temperature() { - in_degrees_of(b, a) - } else { - b.amount - }; + let b_amount = if a.dim.has_temperature() { in_degrees_of(b, a) } else { b.amount }; a.amount.cmp(&b_amount) } (Value::Percent { ratio: a, .. }, Value::Percent { ratio: b, .. }) => a.cmp(b), (Value::Date(a), Value::Date(b)) => a.cmp(b), _ => return Err(self.blame(mismatch(&found, &next))), }; - let keep_next = if largest { - order.is_lt() - } else { - order.is_gt() - }; + let keep_next = if largest { order.is_lt() } else { order.is_gt() }; if keep_next { found = next; } @@ -1526,10 +1364,9 @@ impl Parser<'_> { /// `3 ans`, `36 mois`: a duration in years. fn years(&mut self) -> Result { match self.principal()? { - Value::Quantity(quantity) if quantity.dim == Dim::TIME => quantity - .amount - .checked_div(Decimal::from(YEAR_SECONDS)) - .ok_or_else(overflow), + Value::Quantity(quantity) if quantity.dim == Dim::TIME => { + quantity.amount.checked_div(Decimal::from(YEAR_SECONDS)).ok_or_else(overflow) + } other => Err(self.blame(CalcError::Mismatch { expected: Dimension::Time, found: other.dimension(), @@ -1555,12 +1392,9 @@ impl Parser<'_> { if !self.eat(CalcWord::Compounded) { return Ok(Decimal::ONE); } - for (word, count) in [ - (CalcWord::Monthly, 12), - (CalcWord::Quarterly, 4), - (CalcWord::Yearly, 1), - (CalcWord::Daily, 365), - ] { + for (word, count) in + [(CalcWord::Monthly, 12), (CalcWord::Quarterly, 4), (CalcWord::Yearly, 1), (CalcWord::Daily, 365)] + { if self.eat(word) { return Ok(Decimal::from(count)); } @@ -1585,19 +1419,14 @@ impl Parser<'_> { return Err(self.unreadable()); } let grown = self.compound(principal.clone())?; - return add(grown, principal, false) - .map(Some) - .map_err(|error| self.blame(error)); + return add(grown, principal, false).map(Some).map_err(|error| self.blame(error)); } if self.eat(CalcWord::AnnualReturn) { return self.annual_return().map(Some); } if self.eat(CalcWord::PresentValue) { let future = self.principal()?; - if !(self.eat(CalcWord::Within) - || self.eat(CalcWord::After) - || self.eat(CalcWord::During)) - { + if !(self.eat(CalcWord::Within) || self.eat(CalcWord::After) || self.eat(CalcWord::During)) { return Err(self.unreadable()); } let years = self.years()?; @@ -1630,8 +1459,7 @@ impl Parser<'_> { if !self.eat(CalcWord::Returned) { return Err(self.unreadable()); } - if !(self.eat(CalcWord::Convert) || self.eat(CalcWord::After) || self.eat(CalcWord::During)) - { + if !(self.eat(CalcWord::Convert) || self.eat(CalcWord::After) || self.eat(CalcWord::During)) { return Err(self.unreadable()); } let years = self.years()?; @@ -1639,10 +1467,7 @@ impl Parser<'_> { let yearly = times .and_then(|times| maths::yearly(times, years)) .map_err(|error| self.blame(error))?; - Ok(Value::Percent { - ratio: yearly, - signed: false, - }) + Ok(Value::Percent { ratio: yearly, signed: false }) } /// `mensualité de 10 000 € sur 6 ans à 6 %` is 165,73 €; its total, its interest. @@ -1654,8 +1479,7 @@ impl Parser<'_> { let years = self.years()?; let rate = self.rate()?; let months = years * Decimal::from(12); - let payment = - maths::payment(rate / Decimal::from(12), months).map_err(|error| self.blame(error))?; + let payment = maths::payment(rate / Decimal::from(12), months).map_err(|error| self.blame(error))?; let factor = match part { Loan::Monthly => payment, Loan::Total => payment * months, @@ -1711,11 +1535,7 @@ fn modulo(left: Value, right: Value) -> Answer { if !rest.is_zero() && rest.is_sign_negative() != b.amount.is_sign_negative() { rest += b.amount; } - Ok(Value::Quantity(Quantity { - amount: rest, - spans: false, - ..a - })) + Ok(Value::Quantity(Quantity { amount: rest, spans: false, ..a })) } (left, right) => Err(mismatch(&left, &right)), } @@ -1729,10 +1549,7 @@ fn excluding(left: Value, right: Value) -> Answer { if divisor.is_zero() { return Err(CalcError::DivisionByZero); } - Ok(Value::Quantity(Quantity { - amount: a.amount.checked_div(divisor).ok_or_else(overflow)?, - ..a - })) + Ok(Value::Quantity(Quantity { amount: a.amount.checked_div(divisor).ok_or_else(overflow)?, ..a })) } (left, right) => Err(mismatch(&left, &right)), } @@ -1745,15 +1562,9 @@ fn ratio(left: &Value, right: &Value) -> Answer { if b.amount.is_zero() { return Err(CalcError::DivisionByZero); } - let (part, whole) = if a.dim.has_temperature() { - (a.amount, in_degrees_of(b, a)) - } else { - (a.amount, b.amount) - }; - Ok(Value::Percent { - ratio: part.checked_div(whole).ok_or_else(overflow)?, - signed: false, - }) + let (part, whole) = + if a.dim.has_temperature() { (a.amount, in_degrees_of(b, a)) } else { (a.amount, b.amount) }; + Ok(Value::Percent { ratio: part.checked_div(whole).ok_or_else(overflow)?, signed: false }) } _ => Err(mismatch(left, right)), } @@ -1766,13 +1577,8 @@ fn change(from: &Value, to: &Value) -> Answer { if a.amount.is_zero() { return Err(CalcError::DivisionByZero); } - let ratio = (b.amount - a.amount) - .checked_div(a.amount) - .ok_or_else(overflow)?; - Ok(Value::Percent { - ratio, - signed: true, - }) + let ratio = (b.amount - a.amount).checked_div(a.amount).ok_or_else(overflow)?; + Ok(Value::Percent { ratio, signed: true }) } _ => Err(mismatch(from, to)), } @@ -1794,11 +1600,7 @@ fn power(base: Value, exponent: Value) -> Answer { if !base.dim.is_none() { return Err(CalcError::Unsupported); } - let count = exponent - .amount - .to_i64() - .ok_or_else(overflow)? - .unsigned_abs(); + let count = exponent.amount.to_i64().ok_or_else(overflow)?.unsigned_abs(); let mut result = Decimal::ONE; for _ in 0..count { result = result.checked_mul(base.amount).ok_or_else(overflow)?; @@ -1814,14 +1616,8 @@ fn power(base: Value, exponent: Value) -> Answer { fn negate(value: Value) -> Answer { match value { - Value::Quantity(quantity) => Ok(Value::Quantity(Quantity { - amount: -quantity.amount, - ..quantity - })), - Value::Percent { ratio, signed } => Ok(Value::Percent { - ratio: -ratio, - signed, - }), + Value::Quantity(quantity) => Ok(Value::Quantity(Quantity { amount: -quantity.amount, ..quantity })), + Value::Percent { ratio, signed } => Ok(Value::Percent { ratio: -ratio, signed }), Value::Date(_) => Err(CalcError::Unsupported), } } @@ -1829,35 +1625,24 @@ fn negate(value: Value) -> Answer { /// ⚠️ Euros are never turned into dollars: no rate is fetched, the sheet works offline. fn convert(value: Value, shown: Shown, dim: Dim) -> Answer { let Value::Quantity(quantity) = value else { - return Err(CalcError::NotConvertible { - from: value.dimension(), - to: Some(shown.calc_unit()), - }); + return Err(CalcError::NotConvertible { from: value.dimension(), to: Some(shown.calc_unit()) }); }; if quantity.dim != dim { return Err(if quantity.dim.is_currency() && dim.is_currency() { CalcError::Currency } else { - CalcError::NotConvertible { - from: quantity.dim.dimension(), - to: Some(shown.calc_unit()), - } + CalcError::NotConvertible { from: quantity.dim.dimension(), to: Some(shown.calc_unit()) } }); } let amount = match (quantity.dim.has_temperature(), quantity.unit, shown) { - (true, Some(Shown::One(from)), Shown::One(to)) => { - from_celsius(to_celsius(quantity.amount, from), to) - } + (true, Some(Shown::One(from)), Shown::One(to)) => from_celsius(to_celsius(quantity.amount, from), to), _ => quantity.amount, }; Ok(Value::Quantity(Quantity { amount, dim, unit: Some(shown), - spans: matches!( - shown, - Shown::One(UnitId::Week | UnitId::Day | UnitId::Hour | UnitId::Minute) - ), + spans: matches!(shown, Shown::One(UnitId::Week | UnitId::Day | UnitId::Hour | UnitId::Minute)), })) } @@ -1869,28 +1654,12 @@ fn aggregate(block: &[Quantity], mean: bool) -> Answer { let mut sum = Decimal::ZERO; for quantity in block { if quantity.dim != first.dim { - return Err(mismatch( - &Value::Quantity(first.clone()), - &Value::Quantity(quantity.clone()), - )); + return Err(mismatch(&Value::Quantity(first.clone()), &Value::Quantity(quantity.clone()))); } - let amount = if first.dim.has_temperature() { - in_degrees_of(quantity, first) - } else { - quantity.amount - }; + let amount = + if first.dim.has_temperature() { in_degrees_of(quantity, first) } else { quantity.amount }; sum = sum.checked_add(amount).ok_or_else(overflow)?; } - let amount = if mean { - sum.checked_div(Decimal::from(block.len())) - .ok_or_else(overflow)? - } else { - sum - }; - Ok(Value::Quantity(Quantity { - amount, - dim: first.dim, - unit: first.unit, - spans: false, - })) + let amount = if mean { sum.checked_div(Decimal::from(block.len())).ok_or_else(overflow)? } else { sum }; + Ok(Value::Quantity(Quantity { amount, dim: first.dim, unit: first.unit, spans: false })) } diff --git a/crates/engine/src/notes/calc/lexer.rs b/crates/engine/src/notes/calc/lexer.rs index 410d92478..c604bb8a2 100644 --- a/crates/engine/src/notes/calc/lexer.rs +++ b/crates/engine/src/notes/calc/lexer.rs @@ -27,9 +27,8 @@ pub(super) struct Token { pub(super) spaced: bool, } -const SYMBOLS: &[char] = &[ - '+', '-', '−', '×', '*', '/', '÷', '^', '(', ')', '=', '%', '€', '$', '&', '|', '<', '>', '@', -]; +const SYMBOLS: &[char] = + &['+', '-', '−', '×', '*', '/', '÷', '^', '(', ')', '=', '%', '€', '$', '&', '|', '<', '>', '@']; fn is_word_start(character: char) -> bool { character.is_alphabetic() || character == '_' || character == '°' @@ -60,11 +59,7 @@ fn date_at(characters: &[char], at: usize) -> Option<(NaiveDate, usize)> { { let length = 10; if ends(length) { - let date = NaiveDate::from_ymd_opt( - year.parse().ok()?, - month.parse().ok()?, - day.parse().ok()?, - )?; + let date = NaiveDate::from_ymd_opt(year.parse().ok()?, month.parse().ok()?, day.parse().ok()?)?; return Some((date, length)); } } @@ -80,11 +75,7 @@ fn date_at(characters: &[char], at: usize) -> Option<(NaiveDate, usize)> { { let length = day.len() + month.len() + 2 + 4; if ends(length) { - let date = NaiveDate::from_ymd_opt( - year.parse().ok()?, - month.parse().ok()?, - day.parse().ok()?, - )?; + let date = NaiveDate::from_ymd_opt(year.parse().ok()?, month.parse().ok()?, day.parse().ok()?)?; return Some((date, length)); } } @@ -94,14 +85,8 @@ fn date_at(characters: &[char], at: usize) -> Option<(NaiveDate, usize)> { /// Three digits after a space, the next not a digit: `5 300`, and `1 578,13 €` as the front /// writes it, its space a no-break one. fn group_at(characters: &[char], at: usize) -> bool { - characters - .get(at) - .is_some_and(|c| matches!(c, ' ' | '\u{a0}' | '\u{202f}')) - && (1..=3).all(|offset| { - characters - .get(at + offset) - .is_some_and(char::is_ascii_digit) - }) + characters.get(at).is_some_and(|c| matches!(c, ' ' | '\u{a0}' | '\u{202f}')) + && (1..=3).all(|offset| characters.get(at + offset).is_some_and(char::is_ascii_digit)) && !characters.get(at + 4).is_some_and(char::is_ascii_digit) } @@ -116,15 +101,8 @@ fn based_at(characters: &[char], at: usize) -> Option<(Decimal, usize)> { 'o' | 'O' => 8, _ => return None, }; - let digits: String = characters[at + 2..] - .iter() - .take_while(|c| c.is_digit(radix)) - .collect(); - if digits.is_empty() - || characters - .get(at + 2 + digits.len()) - .is_some_and(|c| c.is_alphanumeric()) - { + let digits: String = characters[at + 2..].iter().take_while(|c| c.is_digit(radix)).collect(); + if digits.is_empty() || characters.get(at + 2 + digits.len()).is_some_and(|c| c.is_alphanumeric()) { return None; } let value = i128::from_str_radix(&digits, radix).ok()?; @@ -167,18 +145,14 @@ fn comma_groups(characters: &[char], end: usize, after_currency: bool) -> Option let mut probe = end; let mut groups = 0; while characters.get(probe) == Some(&',') - && (1..=3).all(|offset| { - characters - .get(probe + offset) - .is_some_and(char::is_ascii_digit) - }) + && (1..=3).all(|offset| characters.get(probe + offset).is_some_and(char::is_ascii_digit)) && !characters.get(probe + 4).is_some_and(char::is_ascii_digit) { probe += 4; groups += 1; } - let point = characters.get(probe) == Some(&'.') - && characters.get(probe + 1).is_some_and(char::is_ascii_digit); + let point = + characters.get(probe) == Some(&'.') && characters.get(probe + 1).is_some_and(char::is_ascii_digit); (groups > 0 && (after_currency || groups > 1 || point)).then_some(probe) } @@ -195,11 +169,7 @@ fn number_at(characters: &[char], at: usize, after_currency: bool) -> Option<(De if end == at { return None; } - let english = if end - at <= 3 { - comma_groups(characters, end, after_currency) - } else { - None - }; + let english = if end - at <= 3 { comma_groups(characters, end, after_currency) } else { None }; if let Some(grouped) = english { end = grouped; } else if end - at <= 3 { @@ -207,11 +177,7 @@ fn number_at(characters: &[char], at: usize, after_currency: bool) -> Option<(De end += 4; } } - let marks: &[char] = if english.is_some() { - &['.'] - } else { - &['.', ','] - }; + let marks: &[char] = if english.is_some() { &['.'] } else { &['.', ','] }; if characters.get(end).is_some_and(|mark| marks.contains(mark)) && characters.get(end + 1).is_some_and(char::is_ascii_digit) { @@ -238,9 +204,7 @@ fn word_at(characters: &[char], at: usize) -> usize { let mut end = at + 1; while let Some(&character) = characters.get(end) { let inner_apostrophe = matches!(character, '\'' | '’') - && characters - .get(end + 1) - .is_some_and(|next| next.is_alphabetic()); + && characters.get(end + 1).is_some_and(|next| next.is_alphabetic()); if is_word_part(character) || inner_apostrophe { end += 1; } else { @@ -299,10 +263,7 @@ pub(super) fn tokens(line: &str) -> Vec { (Tok::Number(number), length) } else if is_word_start(character) { let length = word_at(&characters, at); - ( - Tok::Word(characters[at..at + length].iter().collect()), - length, - ) + (Tok::Word(characters[at..at + length].iter().collect()), length) } else if SYMBOLS.contains(&character) { (Tok::Symbol(character), 1) } else if let Some(length) = quoted_at(&characters, at) { @@ -310,12 +271,7 @@ pub(super) fn tokens(line: &str) -> Vec { } else { (Tok::Other(character), 1) }; - tokens.push(Token { - tok, - start: offsets[at], - end: offsets[at + length], - spaced, - }); + tokens.push(Token { tok, start: offsets[at], end: offsets[at + length], spaced }); spaced = false; at += length; } diff --git a/crates/engine/src/notes/calc/maths.rs b/crates/engine/src/notes/calc/maths.rs index 3275ec5f5..af5fc4e25 100644 --- a/crates/engine/src/notes/calc/maths.rs +++ b/crates/engine/src/notes/calc/maths.rs @@ -19,19 +19,13 @@ fn overflow() -> CalcError { } /// To a multiple of `step`: `37 au 10 près` is 40. -pub(super) fn round_to( - amount: Decimal, - step: Decimal, - rounding: Rounding, -) -> Result { +pub(super) fn round_to(amount: Decimal, step: Decimal, rounding: Rounding) -> Result { if step.is_zero() { return Err(CalcError::DivisionByZero); } let steps = amount.checked_div(step.abs()).ok_or_else(overflow)?; let whole = match rounding { - Rounding::Nearest => { - steps.round_dp_with_strategy(0, RoundingStrategy::MidpointAwayFromZero) - } + Rounding::Nearest => steps.round_dp_with_strategy(0, RoundingStrategy::MidpointAwayFromZero), Rounding::Up => steps.ceil(), Rounding::Down => steps.floor(), }; @@ -62,11 +56,7 @@ fn power(base: Decimal, exponent: u32) -> Option { /// sheet writes and short of the last figure an approximation gets wrong. fn exact_root(x: Decimal, approximate: Decimal, degree: u32) -> Decimal { let candidate = approximate.round_dp(12).normalize(); - if power(candidate, degree) == Some(x) { - candidate - } else { - approximate - } + if power(candidate, degree) == Some(x) { candidate } else { approximate } } /// `racine 2 (8)` is the square root of 8: an even root of a negative number is refused. @@ -84,10 +74,7 @@ pub(super) fn root(x: Decimal, degree: u32) -> Result { let mut guess = if degree == 2 { size.sqrt().ok_or_else(overflow)? } else { - let estimate = size - .to_f64() - .ok_or_else(overflow)? - .powf(1.0 / f64::from(degree)); + let estimate = size.to_f64().ok_or_else(overflow)?.powf(1.0 / f64::from(degree)); Decimal::try_from(estimate).map_err(|_| overflow())? }; // Newton's steps take the estimate to every figure a decimal holds. @@ -98,9 +85,7 @@ pub(super) fn root(x: Decimal, degree: u32) -> Result { break; } let quotient = size.checked_div(below).ok_or_else(overflow)?; - guess = ((n - Decimal::ONE) * guess + quotient) - .checked_div(n) - .ok_or_else(overflow)?; + guess = ((n - Decimal::ONE) * guess + quotient).checked_div(n).ok_or_else(overflow)?; } let found = exact_root(size, guess, degree); Ok(if x.is_sign_negative() { -found } else { found }) @@ -121,21 +106,14 @@ pub(super) fn root_of(x: Decimal, degree: Decimal) -> Result if x.is_zero() { return Ok(x); } - let size = power_of( - x.abs(), - Decimal::ONE.checked_div(degree).ok_or_else(overflow)?, - )?; + let size = power_of(x.abs(), Decimal::ONE.checked_div(degree).ok_or_else(overflow)?)?; Ok(if x.is_sign_negative() { -size } else { size }) } /// A whole result a decimal logarithm only comes near: `ln(e)` is 1. fn whole_if_near(value: Decimal) -> Decimal { let whole = value.round(); - if (value - whole).abs() < Decimal::new(1, 20) { - whole - } else { - value - } + if (value - whole).abs() < Decimal::new(1, 20) { whole } else { value } } pub(super) fn ln(x: Decimal) -> Result { @@ -192,12 +170,7 @@ pub(super) enum Bits { pub(super) fn bits(left: Decimal, right: Decimal, operation: Bits) -> Result { let (a, b) = (whole(left)?, whole(right)?); - let shift = || { - u32::try_from(b) - .ok() - .filter(|count| *count < 127) - .ok_or_else(overflow) - }; + let shift = || u32::try_from(b).ok().filter(|count| *count < 127).ok_or_else(overflow); let value = match operation { Bits::And => a & b, Bits::Or => a | b, @@ -304,12 +277,8 @@ pub(super) fn fraction(value: Decimal) -> (bool, u128, u128) { for _ in 0..64 { let whole = rest.trunc(); let Some(step) = whole.to_u128() else { break }; - let numerator = step - .checked_mul(last.0) - .and_then(|product| product.checked_add(before.0)); - let denominator = step - .checked_mul(last.1) - .and_then(|product| product.checked_add(before.1)); + let numerator = step.checked_mul(last.0).and_then(|product| product.checked_add(before.0)); + let denominator = step.checked_mul(last.1).and_then(|product| product.checked_add(before.1)); let (Some(numerator), Some(denominator)) = (numerator, denominator) else { break; }; @@ -330,10 +299,7 @@ pub(super) fn fraction(value: Decimal) -> (bool, u128, u128) { return (negative, numerator, denominator); } let left = rest - whole; - let Some(next) = (!left.is_zero()) - .then(|| Decimal::ONE.checked_div(left)) - .flatten() - else { + let Some(next) = (!left.is_zero()).then(|| Decimal::ONE.checked_div(left)).flatten() else { break; }; rest = next; @@ -348,8 +314,7 @@ pub(super) fn scientific(value: Decimal) -> (String, i32) { return ("0".into(), 0); } let figures = value.mantissa().unsigned_abs().to_string(); - let exponent = - i32::try_from(figures.len()).unwrap_or(0) - 1 - i32::try_from(value.scale()).unwrap_or(0); + let exponent = i32::try_from(figures.len()).unwrap_or(0) - 1 - i32::try_from(value.scale()).unwrap_or(0); let rest = figures[1..].trim_end_matches('0'); let sign = if value.is_sign_negative() { "-" } else { "" }; let mantissa = if rest.is_empty() { diff --git a/crates/engine/src/notes/calc/summary.rs b/crates/engine/src/notes/calc/summary.rs index a63940e87..3afd361ff 100644 --- a/crates/engine/src/notes/calc/summary.rs +++ b/crates/engine/src/notes/calc/summary.rs @@ -27,10 +27,7 @@ pub fn summary(sheet: &CalcSheet, lines: &[u32]) -> CalcSummary { .iter() .filter_map(|line| sheet.rows.get(usize::try_from(*line).ok()?)) .filter_map(|row| match &row.line { - CalcLine::Value { - value: CalcValue::Number { value, unit }, - .. - } => Some((value.as_str(), *unit)), + CalcLine::Value { value: CalcValue::Number { value, unit }, .. } => Some((value.as_str(), *unit)), _ => None, }) .collect(); @@ -76,37 +73,22 @@ mod tests { fn figures(sum: &str, mean: &str, unit: Option) -> CalcSummary { let unit = unit.map(|unit| CalcUnit { unit, per: None }); CalcSummary::Figures { - sum: CalcValue::Number { - value: sum.into(), - unit, - }, - mean: CalcValue::Number { - value: mean.into(), - unit, - }, + sum: CalcValue::Number { value: sum.into(), unit }, + mean: CalcValue::Number { value: mean.into(), unit }, } } #[test] fn the_lines_chosen_add_up_and_average_exactly_in_their_unit() { - assert_eq!( - summed("0,1 €\n0,2 €\n5 €", &[0, 1]), - figures("0.3", "0.15", Some(UnitId::Euro)) - ); - assert_eq!( - summed("1\n2\n4", &[0, 1, 2]), - figures("7", "2.333333333333333333333333", None) - ); + assert_eq!(summed("0,1 €\n0,2 €\n5 €", &[0, 1]), figures("0.3", "0.15", Some(UnitId::Euro))); + assert_eq!(summed("1\n2\n4", &[0, 1, 2]), figures("7", "2.333333333333333333333333", None)); } #[test] fn a_line_that_gave_no_number_is_left_out() { let sheet = "3\ndes mots\n1 / 0\n20 %\naujourd'hui\n\n5"; - assert_eq!( - summed(sheet, &[0, 1, 2, 3, 4, 5, 6, 99]), - figures("8", "4", None) - ); + assert_eq!(summed(sheet, &[0, 1, 2, 3, 4, 5, 6, 99]), figures("8", "4", None)); } #[test] @@ -126,10 +108,7 @@ mod tests { fn a_sum_past_what_a_decimal_holds_overflows() { let huge = "79228162514264337593543950335"; - assert_eq!( - summed(&format!("{huge}\n{huge}"), &[0, 1]), - CalcSummary::Overflow - ); + assert_eq!(summed(&format!("{huge}\n{huge}"), &[0, 1]), CalcSummary::Overflow); } /// The sums and means the front's footer was checked against (`golden/calc-format`). @@ -157,10 +136,7 @@ mod tests { assert_eq!( got, - CalcValue::Number { - value: case["output"].as_str().expect("an output").into(), - unit: None - }, + CalcValue::Number { value: case["output"].as_str().expect("an output").into(), unit: None }, "{footer} of {input:?}" ); checked += 1; diff --git a/crates/engine/src/notes/calc/units.rs b/crates/engine/src/notes/calc/units.rs index c368ff2f8..9d479305e 100644 --- a/crates/engine/src/notes/calc/units.rs +++ b/crates/engine/src/notes/calc/units.rs @@ -218,309 +218,69 @@ use UnitId as U; /// they are the English `to` and a month. const UNITS: &[(UnitId, Dim, Size, &[&str])] = &[ (U::Nanometre, Dim::LENGTH, Exact("0.000000001"), &["nm"]), - ( - U::Micrometre, - Dim::LENGTH, - Exact("0.000001"), - &["µm", "μm", "um"], - ), + (U::Micrometre, Dim::LENGTH, Exact("0.000001"), &["µm", "μm", "um"]), (U::Millimetre, Dim::LENGTH, Exact("0.001"), &["mm"]), (U::Centimetre, Dim::LENGTH, Exact("0.01"), &["cm"]), - ( - U::Metre, - Dim::LENGTH, - Exact("1"), - &["m", "mètre", "mètres", "metre", "metres", "meter", "meters"], - ), + (U::Metre, Dim::LENGTH, Exact("1"), &["m", "mètre", "mètres", "metre", "metres", "meter", "meters"]), (U::Kilometre, Dim::LENGTH, Exact("1000"), &["km"]), - ( - U::Inch, - Dim::LENGTH, - Exact("0.0254"), - &["in", "po", "pouce", "pouces", "inch", "inches"], - ), - ( - U::Foot, - Dim::LENGTH, - Exact("0.3048"), - &["ft", "pied", "pieds", "foot", "feet"], - ), - ( - U::Yard, - Dim::LENGTH, - Exact("0.9144"), - &["yd", "yard", "yards"], - ), - ( - U::Mile, - Dim::LENGTH, - Exact("1609.344"), - &["mi", "mile", "miles"], - ), + (U::Inch, Dim::LENGTH, Exact("0.0254"), &["in", "po", "pouce", "pouces", "inch", "inches"]), + (U::Foot, Dim::LENGTH, Exact("0.3048"), &["ft", "pied", "pieds", "foot", "feet"]), + (U::Yard, Dim::LENGTH, Exact("0.9144"), &["yd", "yard", "yards"]), + (U::Mile, Dim::LENGTH, Exact("1609.344"), &["mi", "mile", "miles"]), (U::Pixel, Dim::LENGTH, Over("0.0254", "96"), &["px"]), (U::Point, Dim::LENGTH, Over("0.0254", "72"), &["pt"]), (U::Em, Dim::LENGTH, Over("0.4064", "96"), &["em"]), (U::Rem, Dim::LENGTH, Over("0.4064", "96"), &["rem"]), (U::Milligram, Dim::MASS, Exact("0.000001"), &["mg"]), - ( - U::Gram, - Dim::MASS, - Exact("0.001"), - &["g", "gramme", "grammes", "gram", "grams"], - ), + (U::Gram, Dim::MASS, Exact("0.001"), &["g", "gramme", "grammes", "gram", "grams"]), (U::Kilogram, Dim::MASS, Exact("1"), &["kg"]), - ( - U::Tonne, - Dim::MASS, - Exact("1000"), - &["t", "tonne", "tonnes"], - ), - ( - U::Pound, - Dim::MASS, - Exact("0.45359237"), - &["lb", "lbs", "livre", "livres", "pound", "pounds"], - ), - ( - U::Ounce, - Dim::MASS, - Exact("0.028349523125"), - &["oz", "once", "onces", "ounce", "ounces"], - ), + (U::Tonne, Dim::MASS, Exact("1000"), &["t", "tonne", "tonnes"]), + (U::Pound, Dim::MASS, Exact("0.45359237"), &["lb", "lbs", "livre", "livres", "pound", "pounds"]), + (U::Ounce, Dim::MASS, Exact("0.028349523125"), &["oz", "once", "onces", "ounce", "ounces"]), (U::Nanosecond, Dim::TIME, Exact("0.000000001"), &["ns"]), - ( - U::Microsecond, - Dim::TIME, - Exact("0.000001"), - &["µs", "μs", "us"], - ), + (U::Microsecond, Dim::TIME, Exact("0.000001"), &["µs", "μs", "us"]), (U::Millisecond, Dim::TIME, Exact("0.001"), &["ms"]), - ( - U::Second, - Dim::TIME, - Exact("1"), - &["s", "sec", "seconde", "secondes", "second", "seconds"], - ), - ( - U::Minute, - Dim::TIME, - Exact("60"), - &["min", "mn", "minute", "minutes"], - ), - ( - U::Hour, - Dim::TIME, - Exact("3600"), - &["h", "heure", "heures", "hour", "hours"], - ), - ( - U::Day, - Dim::TIME, - Exact("86400"), - &["j", "jour", "jours", "d", "day", "days"], - ), - ( - U::Week, - Dim::TIME, - Exact("604800"), - &["sem", "semaine", "semaines", "wk", "week", "weeks"], - ), + (U::Second, Dim::TIME, Exact("1"), &["s", "sec", "seconde", "secondes", "second", "seconds"]), + (U::Minute, Dim::TIME, Exact("60"), &["min", "mn", "minute", "minutes"]), + (U::Hour, Dim::TIME, Exact("3600"), &["h", "heure", "heures", "hour", "hours"]), + (U::Day, Dim::TIME, Exact("86400"), &["j", "jour", "jours", "d", "day", "days"]), + (U::Week, Dim::TIME, Exact("604800"), &["sem", "semaine", "semaines", "wk", "week", "weeks"]), // The mean month and year of the Gregorian calendar; a date moves by calendar months. - ( - U::Month, - Dim::TIME, - Exact("2629746"), - &["mois", "month", "months", "mo"], - ), - ( - U::Year, - Dim::TIME, - Exact("31556952"), - &["an", "ans", "année", "années", "y", "yr", "year", "years"], - ), - ( - U::Bit, - Dim::DATA, - Data(SizeUnit::Bit), - &["b", "bit", "bits"], - ), - ( - U::Kilobit, - Dim::DATA, - Data(SizeUnit::Kilobit), - &["Kb", "kbit", "Kbit"], - ), - ( - U::Megabit, - Dim::DATA, - Data(SizeUnit::Megabit), - &["Mb", "Mbit", "mbit"], - ), - ( - U::Gigabit, - Dim::DATA, - Data(SizeUnit::Gigabit), - &["Gb", "Gbit", "gbit"], - ), - ( - U::Terabit, - Dim::DATA, - Data(SizeUnit::Terabit), - &["Tb", "Tbit", "tbit"], - ), - ( - U::Petabit, - Dim::DATA, - Exact("1000000000000000"), - &["Pb", "Pbit", "pbit"], - ), - ( - U::Byte, - Dim::DATA, - Data(SizeUnit::Byte), - &["o", "B", "octet", "octets", "byte", "bytes"], - ), - ( - U::Kilobyte, - Dim::DATA, - Data(SizeUnit::Kilobyte), - &["Ko", "ko", "kB", "KB"], - ), - ( - U::Megabyte, - Dim::DATA, - Data(SizeUnit::Megabyte), - &["Mo", "MB"], - ), - ( - U::Gigabyte, - Dim::DATA, - Data(SizeUnit::Gigabyte), - &["Go", "go", "GB", "gb"], - ), - ( - U::Terabyte, - Dim::DATA, - Data(SizeUnit::Terabyte), - &["To", "TB", "tb"], - ), - ( - U::Petabyte, - Dim::DATA, - Data(SizeUnit::Petabyte), - &["Po", "PB"], - ), - ( - U::Exabyte, - Dim::DATA, - Exact("8000000000000000000"), - &["Eo", "EB"], - ), - ( - U::Zettabyte, - Dim::DATA, - Exact("8000000000000000000000"), - &["Zo", "ZB"], - ), - ( - U::Yottabyte, - Dim::DATA, - Exact("8000000000000000000000000"), - &["Yo", "YB"], - ), - ( - U::Kibibyte, - Dim::DATA, - Data(SizeUnit::Kibibyte), - &["Kio", "kio", "KiB", "kiB"], - ), - ( - U::Mebibyte, - Dim::DATA, - Data(SizeUnit::Mebibyte), - &["Mio", "mio", "MiB"], - ), - ( - U::Gibibyte, - Dim::DATA, - Data(SizeUnit::Gibibyte), - &["Gio", "gio", "GiB"], - ), - ( - U::Tebibyte, - Dim::DATA, - Data(SizeUnit::Tebibyte), - &["Tio", "tio", "TiB"], - ), - ( - U::Pebibyte, - Dim::DATA, - Data(SizeUnit::Pebibyte), - &["Pio", "pio", "PiB"], - ), - ( - U::Exbibyte, - Dim::DATA, - Exact("9223372036854775808"), - &["Eio", "EiB"], - ), - ( - U::Zebibyte, - Dim::DATA, - Exact("9444732965739290427392"), - &["Zio", "ZiB"], - ), - ( - U::Yobibyte, - Dim::DATA, - Exact("9671406556917033397649408"), - &["Yio", "YiB"], - ), - ( - U::Celsius, - Dim::TEMPERATURE, - Exact("1"), - &["°C", "°c", "celsius"], - ), - ( - U::Fahrenheit, - Dim::TEMPERATURE, - Exact("1"), - &["°F", "°f", "fahrenheit"], - ), - ( - U::Kelvin, - Dim::TEMPERATURE, - Exact("1"), - &["K", "kelvin", "kelvins"], - ), + (U::Month, Dim::TIME, Exact("2629746"), &["mois", "month", "months", "mo"]), + (U::Year, Dim::TIME, Exact("31556952"), &["an", "ans", "année", "années", "y", "yr", "year", "years"]), + (U::Bit, Dim::DATA, Data(SizeUnit::Bit), &["b", "bit", "bits"]), + (U::Kilobit, Dim::DATA, Data(SizeUnit::Kilobit), &["Kb", "kbit", "Kbit"]), + (U::Megabit, Dim::DATA, Data(SizeUnit::Megabit), &["Mb", "Mbit", "mbit"]), + (U::Gigabit, Dim::DATA, Data(SizeUnit::Gigabit), &["Gb", "Gbit", "gbit"]), + (U::Terabit, Dim::DATA, Data(SizeUnit::Terabit), &["Tb", "Tbit", "tbit"]), + (U::Petabit, Dim::DATA, Exact("1000000000000000"), &["Pb", "Pbit", "pbit"]), + (U::Byte, Dim::DATA, Data(SizeUnit::Byte), &["o", "B", "octet", "octets", "byte", "bytes"]), + (U::Kilobyte, Dim::DATA, Data(SizeUnit::Kilobyte), &["Ko", "ko", "kB", "KB"]), + (U::Megabyte, Dim::DATA, Data(SizeUnit::Megabyte), &["Mo", "MB"]), + (U::Gigabyte, Dim::DATA, Data(SizeUnit::Gigabyte), &["Go", "go", "GB", "gb"]), + (U::Terabyte, Dim::DATA, Data(SizeUnit::Terabyte), &["To", "TB", "tb"]), + (U::Petabyte, Dim::DATA, Data(SizeUnit::Petabyte), &["Po", "PB"]), + (U::Exabyte, Dim::DATA, Exact("8000000000000000000"), &["Eo", "EB"]), + (U::Zettabyte, Dim::DATA, Exact("8000000000000000000000"), &["Zo", "ZB"]), + (U::Yottabyte, Dim::DATA, Exact("8000000000000000000000000"), &["Yo", "YB"]), + (U::Kibibyte, Dim::DATA, Data(SizeUnit::Kibibyte), &["Kio", "kio", "KiB", "kiB"]), + (U::Mebibyte, Dim::DATA, Data(SizeUnit::Mebibyte), &["Mio", "mio", "MiB"]), + (U::Gibibyte, Dim::DATA, Data(SizeUnit::Gibibyte), &["Gio", "gio", "GiB"]), + (U::Tebibyte, Dim::DATA, Data(SizeUnit::Tebibyte), &["Tio", "tio", "TiB"]), + (U::Pebibyte, Dim::DATA, Data(SizeUnit::Pebibyte), &["Pio", "pio", "PiB"]), + (U::Exbibyte, Dim::DATA, Exact("9223372036854775808"), &["Eio", "EiB"]), + (U::Zebibyte, Dim::DATA, Exact("9444732965739290427392"), &["Zio", "ZiB"]), + (U::Yobibyte, Dim::DATA, Exact("9671406556917033397649408"), &["Yio", "YiB"]), + (U::Celsius, Dim::TEMPERATURE, Exact("1"), &["°C", "°c", "celsius"]), + (U::Fahrenheit, Dim::TEMPERATURE, Exact("1"), &["°F", "°f", "fahrenheit"]), + (U::Kelvin, Dim::TEMPERATURE, Exact("1"), &["K", "kelvin", "kelvins"]), (U::Hertz, Dim::FREQUENCY, Exact("1"), &["Hz", "hz", "hertz"]), (U::Kilohertz, Dim::FREQUENCY, Exact("1000"), &["kHz", "khz"]), (U::Megahertz, Dim::FREQUENCY, Exact("1000000"), &["MHz"]), - ( - U::Gigahertz, - Dim::FREQUENCY, - Exact("1000000000"), - &["GHz", "ghz"], - ), - ( - U::Terahertz, - Dim::FREQUENCY, - Exact("1000000000000"), - &["THz", "thz"], - ), - ( - U::Euro, - Dim::EURO, - Exact("1"), - &["€", "euro", "euros", "EUR"], - ), - ( - U::Dollar, - Dim::DOLLAR, - Exact("1"), - &["$", "dollar", "dollars", "USD"], - ), + (U::Gigahertz, Dim::FREQUENCY, Exact("1000000000"), &["GHz", "ghz"]), + (U::Terahertz, Dim::FREQUENCY, Exact("1000000000000"), &["THz", "thz"]), + (U::Euro, Dim::EURO, Exact("1"), &["€", "euro", "euros", "EUR"]), + (U::Dollar, Dim::DOLLAR, Exact("1"), &["$", "dollar", "dollars", "USD"]), ]; pub fn table() -> Vec { @@ -553,10 +313,7 @@ pub struct UnitEntry { pub fn catalogue() -> Vec { UNITS .iter() - .map(|&(id, dim, _, _)| UnitEntry { - id, - dimension: dim.dimension(), - }) + .map(|&(id, dim, _, _)| UnitEntry { id, dimension: dim.dimension() }) .collect() } @@ -571,11 +328,7 @@ pub struct Css { impl Default for Css { fn default() -> Self { - Self { - ppi: Decimal::from(96), - em: Decimal::from(16), - rem: Decimal::from(16), - } + Self { ppi: Decimal::from(96), em: Decimal::from(16), rem: Decimal::from(16) } } } @@ -645,19 +398,13 @@ mod tests { #[test] fn the_catalogue_offers_each_unit_once_with_what_it_measures() { let catalogue = catalogue(); - let mut ids: Vec<_> = catalogue - .iter() - .map(|entry| format!("{:?}", entry.id)) - .collect(); + let mut ids: Vec<_> = catalogue.iter().map(|entry| format!("{:?}", entry.id)).collect(); ids.sort(); ids.dedup(); assert_eq!(ids.len(), catalogue.len()); assert_eq!(catalogue.len(), table().len()); - let euro = catalogue - .iter() - .find(|entry| entry.id == UnitId::Euro) - .expect("euros"); + let euro = catalogue.iter().find(|entry| entry.id == UnitId::Euro).expect("euros"); assert_eq!(euro.dimension, Dimension::Euro); } } diff --git a/crates/engine/src/notes/calc/words.rs b/crates/engine/src/notes/calc/words.rs index f274717c6..e3beb9e2e 100644 --- a/crates/engine/src/notes/calc/words.rs +++ b/crates/engine/src/notes/calc/words.rs @@ -133,10 +133,7 @@ pub struct Spellings { } impl CalcWord { - #[allow( - clippy::too_many_lines, - reason = "one line per concept: the table is the point" - )] + #[allow(clippy::too_many_lines, reason = "one line per concept: the table is the point")] pub const fn spellings(self) -> Spellings { use WordClass::{Setting, Syntax, Value}; let (class, fr, en): (WordClass, &[&str], &[&str]) = match self { @@ -149,16 +146,8 @@ impl CalcWord { Self::Excluding => (Syntax, &["hors", "ex"], &["excluding", "excl", "ex"]), Self::Plus => (Syntax, &["plus", "avec"], &["plus", "with"]), Self::And => (Syntax, &["et"], &["and"]), - Self::Minus => ( - Syntax, - &["moins", "sans"], - &["minus", "without", "subtract"], - ), - Self::Times => ( - Syntax, - &["fois", "multiplié par", "mul"], - &["times", "multiplied by", "mul"], - ), + Self::Minus => (Syntax, &["moins", "sans"], &["minus", "without", "subtract"]), + Self::Times => (Syntax, &["fois", "multiplié par", "mul"], &["times", "multiplied by", "mul"]), Self::Divide => (Syntax, &["divisé par"], &["divided by", "divide by"]), Self::Modulo => (Syntax, &["mod", "modulo"], &["mod", "modulo"]), Self::Total => (Value, &["total", "somme"], &["total", "sum"]), @@ -171,22 +160,14 @@ impl CalcWord { Self::Mega => (Value, &["M"], &["M"]), Self::Giga => (Value, &["Md"], &["bn"]), Self::Tera => (Value, &["T"], &["T", "tn"]), - Self::Thousand => ( - Value, - &["mille", "millier", "milliers"], - &["thousand", "thousands"], - ), + Self::Thousand => (Value, &["mille", "millier", "milliers"], &["thousand", "thousands"]), Self::Million => (Value, &["million", "millions"], &["million", "millions"]), Self::Billion => (Value, &["milliard", "milliards"], &["billion", "billions"]), Self::Trillion => (Value, &["mille milliards"], &["trillion", "trillions"]), Self::Ten => (Value, &["dizaine", "dizaines"], &["ten", "tens"]), Self::Hundred => (Value, &["centaine", "centaines"], &["hundred", "hundreds"]), Self::Xor => (Syntax, &["xor"], &["xor"]), - Self::Decimals => ( - Syntax, - &["décimales", "décimale"], - &["dp", "decimals", "decimal"], - ), + Self::Decimals => (Syntax, &["décimales", "décimale"], &["dp", "decimals", "decimal"]), Self::Digits => (Syntax, &["chiffres", "chiffre"], &["digits", "digit"]), Self::Rounded => (Syntax, &["arrondi"], &["rounded"]), Self::RoundedUp => (Syntax, &["arrondi supérieur"], &["rounded up"]), @@ -228,23 +209,13 @@ impl CalcWord { Self::PercentOff => (Syntax, &["de moins sur", "de moins que"], &["off"]), Self::What => (Syntax, &["combien"], &["what"]), Self::Is => (Syntax, &["font", "fait"], &["is"]), - Self::WhatPercent => ( - Syntax, - &["c'est combien de %", "combien de %"], - &["is what %"], - ), - Self::WhatTimes => ( - Syntax, - &["c'est combien de fois", "combien de fois"], - &["is what x", "is what times"], - ), + Self::WhatPercent => (Syntax, &["c'est combien de %", "combien de %"], &["is what %"]), + Self::WhatTimes => { + (Syntax, &["c'est combien de fois", "combien de fois"], &["is what x", "is what times"]) + } // Values, not syntax: `x` and `a` are names a sheet gives often. Self::Fraction => (Value, &["fraction"], &["fraction"]), - Self::Multiple => ( - Value, - &["multiple", "multiplicateur"], - &["multiplier", "multiple", "x"], - ), + Self::Multiple => (Value, &["multiple", "multiplicateur"], &["multiplier", "multiple", "x"]), Self::AsDecimal => (Value, &["décimal"], &["decimal", "dec"]), Self::Article => (Value, &[], &["a"]), Self::IsTo => (Syntax, &["est à"], &["is to"]), @@ -252,20 +223,14 @@ impl CalcWord { Self::After => (Syntax, &["après"], &["after"]), Self::During => (Syntax, &["pendant"], &["for"]), Self::Within => (Syntax, &["dans"], &[]), - Self::Compounded => ( - Syntax, - &["composés", "composé", "composées", "composée"], - &["compounding", "compounded"], - ), + Self::Compounded => { + (Syntax, &["composés", "composé", "composées", "composée"], &["compounding", "compounded"]) + } Self::Monthly => (Syntax, &["mensuellement"], &["monthly"]), Self::Quarterly => (Syntax, &["trimestriellement"], &["quarterly"]), Self::Yearly => (Syntax, &["annuellement"], &["annually", "yearly"]), Self::Daily => (Syntax, &["quotidiennement"], &["daily"]), - Self::InterestOn => ( - Syntax, - &["intérêts sur", "intérêts de"], - &["interest on", "interest of"], - ), + Self::InterestOn => (Syntax, &["intérêts sur", "intérêts de"], &["interest on", "interest of"]), Self::Invested => (Syntax, &["investis", "investi"], &["invested"]), Self::Returned => (Syntax, &["récupérés", "récupéré"], &["returned"]), Self::AnnualReturn => ( @@ -277,12 +242,7 @@ impl CalcWord { Self::Repayment => ( Syntax, &["mensualité de", "mensualité sur"], - &[ - "monthly repayment on", - "monthly repayment of", - "monthly payment on", - "monthly payment of", - ], + &["monthly repayment on", "monthly repayment of", "monthly payment on", "monthly payment of"], ), Self::TotalRepayment => ( Syntax, @@ -404,12 +364,7 @@ pub fn catalogue() -> Vec { .iter() .map(|&word| { let spellings = word.spellings(); - WordEntry { - word, - class: spellings.class, - fr: spellings.fr.to_vec(), - en: spellings.en.to_vec(), - } + WordEntry { word, class: spellings.class, fr: spellings.fr.to_vec(), en: spellings.en.to_vec() } }) .collect() } @@ -427,21 +382,13 @@ mod tests { for word in CalcWord::ALL { for spelling in word.every_spelling() { let line = tokens(spelling); - assert_eq!( - spelled(word, &line, 0), - Some(line.len()), - "{spelling} is not read as {word}" - ); + assert_eq!(spelled(word, &line, 0), Some(line.len()), "{spelling} is not read as {word}"); if word.exact() { continue; } let mut letters = spelling.chars(); - let capital: String = letters - .next() - .into_iter() - .flat_map(char::to_uppercase) - .chain(letters) - .collect(); + let capital: String = + letters.next().into_iter().flat_map(char::to_uppercase).chain(letters).collect(); assert!(spelled(word, &tokens(&capital), 0).is_some()); } } @@ -457,10 +404,8 @@ mod tests { concepts.entry(spelling).or_default().insert(word); } } - let shared: BTreeMap<&str, BTreeSet> = concepts - .into_iter() - .filter(|(_, words)| words.len() > 1) - .collect(); + let shared: BTreeMap<&str, BTreeSet> = + concepts.into_iter().filter(|(_, words)| words.len() > 1).collect(); let declared: BTreeMap<&str, BTreeSet> = SHARED .iter() .map(|(spelling, words)| (*spelling, words.iter().copied().collect())) @@ -482,10 +427,8 @@ mod tests { #[test] fn a_word_that_is_also_a_unit_is_told_apart_by_where_it_stands() { - let symbols: BTreeSet<&str> = units::table() - .iter() - .flat_map(|unit| unit.symbols.iter().copied()) - .collect(); + let symbols: BTreeSet<&str> = + units::table().iter().flat_map(|unit| unit.symbols.iter().copied()).collect(); let both: BTreeSet<&str> = CalcWord::ALL .iter() .flat_map(|word| word.every_spelling()) diff --git a/crates/engine/src/notes/checklist.rs b/crates/engine/src/notes/checklist.rs index cdce44e02..a80697a64 100644 --- a/crates/engine/src/notes/checklist.rs +++ b/crates/engine/src/notes/checklist.rs @@ -16,10 +16,7 @@ pub fn normalize_items(items: &[ChecklistItem]) -> Vec { .iter() .filter_map(|item| { let text = item.text.trim(); - (!text.is_empty()).then(|| ChecklistItem { - text: text.to_string(), - done: item.done, - }) + (!text.is_empty()).then(|| ChecklistItem { text: text.to_string(), done: item.done }) }) .collect() } @@ -38,10 +35,7 @@ mod tests { use super::*; fn item(text: &str, done: bool) -> ChecklistItem { - ChecklistItem { - text: text.into(), - done, - } + ChecklistItem { text: text.into(), done } } #[test] @@ -62,10 +56,7 @@ mod tests { fn two_identical_items_are_two_items_in_their_order() { let items = normalize_items(&[item("b", false), item("a", false), item("b", false)]); - assert_eq!( - items, - [item("b", false), item("a", false), item("b", false)] - ); + assert_eq!(items, [item("b", false), item("a", false), item("b", false)]); } #[test] diff --git a/crates/engine/src/notes/convert.rs b/crates/engine/src/notes/convert.rs index f05ec5553..09aff9be0 100644 --- a/crates/engine/src/notes/convert.rs +++ b/crates/engine/src/notes/convert.rs @@ -36,12 +36,9 @@ pub fn convert(note: &Note, into: NoteKind) -> NoteBody { (_, NoteKind::Checklist | NoteKind::Drawing) => String::new(), (NoteKind::Drawing, _) => drawing::words(¬e.content), (NoteKind::Checklist, NoteKind::Note) => checklist::to_markdown(¬e.items), - (NoteKind::Checklist, _) => note - .items - .iter() - .map(|item| item.text.as_str()) - .collect::>() - .join("\n"), + (NoteKind::Checklist, _) => { + note.items.iter().map(|item| item.text.as_str()).collect::>().join("\n") + } _ => note.content.clone(), }; let items = match (note.kind, into) { @@ -50,18 +47,9 @@ pub fn convert(note: &Note, into: NoteKind) -> NoteBody { (_, NoteKind::Checklist) => items_of(¬e.content), _ => Vec::new(), }; - let language = if into.has_language() { - language::from_content(&content) - } else { - Language::default() - }; + let language = if into.has_language() { language::from_content(&content) } else { Language::default() }; - NoteBody { - kind: into, - language, - content, - items, - } + NoteBody { kind: into, language, content, items } } /// One item per line that is not blank: a list's marker dropped, a task's box read as done. @@ -71,10 +59,7 @@ pub fn items_of(text: &str) -> Vec { .map(|line| { let line = without_marker(line.trim()); let (done, text) = without_box(line); - ChecklistItem { - text: text.to_string(), - done, - } + ChecklistItem { text: text.to_string(), done } }) .collect(); @@ -129,27 +114,15 @@ mod tests { const PYTHON: &str = "#!/usr/bin/env python\nprint(1)"; fn item(text: &str, done: bool) -> ChecklistItem { - ChecklistItem { - text: text.into(), - done, - } + ChecklistItem { text: text.into(), done } } fn note(kind: NoteKind, content: &str) -> Note { - Note { - kind, - content: content.into(), - ..fixtures::note() - } + Note { kind, content: content.into(), ..fixtures::note() } } fn checklist(items: Vec) -> Note { - Note { - kind: NoteKind::Checklist, - content: String::new(), - items, - ..fixtures::note() - } + Note { kind: NoteKind::Checklist, content: String::new(), items, ..fixtures::note() } } fn scene(texts: &[&str]) -> String { @@ -181,38 +154,22 @@ mod tests { (NoteKind::Calc, Language::Txt), (NoteKind::Checklist, Language::Txt), ] { - assert_eq!( - convert(¬e(NoteKind::Note, PYTHON), into).language, - language, - "{into}" - ); + assert_eq!(convert(¬e(NoteKind::Note, PYTHON), into).language, language, "{into}"); } } #[test] fn a_text_becomes_one_item_per_line_that_is_not_blank() { - let body = convert( - ¬e(NoteKind::Note, "- [ ] write\n\n - [x] ship \n plain"), - NoteKind::Checklist, - ); + let body = + convert(¬e(NoteKind::Note, "- [ ] write\n\n - [x] ship \n plain"), NoteKind::Checklist); assert_eq!(body.content, ""); - assert_eq!( - body.items, - [ - item("write", false), - item("ship", true), - item("plain", false) - ] - ); + assert_eq!(body.items, [item("write", false), item("ship", true), item("plain", false)]); } #[test] fn a_todo_list_becomes_a_task_list_in_a_note() { - let body = convert( - &checklist(vec![item("write", true), item("ship", false)]), - NoteKind::Note, - ); + let body = convert(&checklist(vec![item("write", true), item("ship", false)]), NoteKind::Note); assert_eq!(body.content, "- [x] write\n- [ ] ship"); assert!(body.items.is_empty()); @@ -221,10 +178,7 @@ mod tests { #[test] fn a_todo_list_becomes_its_texts_one_a_line_elsewhere() { for into in [NoteKind::Snippet, NoteKind::Calc] { - let body = convert( - &checklist(vec![item("2 + 2", true), item("3 * 3", false)]), - into, - ); + let body = convert(&checklist(vec![item("2 + 2", true), item("3 * 3", false)]), into); assert_eq!(body.content, "2 + 2\n3 * 3", "{into}"); assert!(body.items.is_empty()); @@ -263,10 +217,7 @@ mod tests { #[test] fn nothing_written_becomes_a_drawing() { - let sources = [ - note(NoteKind::Snippet, PYTHON), - checklist(vec![item("a", false)]), - ]; + let sources = [note(NoteKind::Snippet, PYTHON), checklist(vec![item("a", false)])]; for source in sources { let body = convert(&source, NoteKind::Drawing); @@ -303,15 +254,7 @@ mod tests { fn a_task_box_is_read_as_the_item_s_state() { let items = items_of("[ ] a\n[x] b\n[X] c\n- [x] d"); - assert_eq!( - items, - [ - item("a", false), - item("b", true), - item("c", true), - item("d", true) - ] - ); + assert_eq!(items, [item("a", false), item("b", true), item("c", true), item("d", true)]); } #[test] @@ -319,10 +262,7 @@ mod tests { let items = items_of("-a\n2024 report\n1.5 kg\n[x]done\n(1) first"); let texts: Vec<_> = items.iter().map(|item| item.text.as_str()).collect(); - assert_eq!( - texts, - ["-a", "2024 report", "1.5 kg", "[x]done", "(1) first"] - ); + assert_eq!(texts, ["-a", "2024 report", "1.5 kg", "[x]done", "(1) first"]); assert!(items.iter().all(|item| !item.done)); } diff --git a/crates/engine/src/notes/drawing.rs b/crates/engine/src/notes/drawing.rs index 4935ffbc3..fee21e442 100644 --- a/crates/engine/src/notes/drawing.rs +++ b/crates/engine/src/notes/drawing.rs @@ -67,9 +67,7 @@ fn png(field: &'static str, uri: &str) -> Result, ValidationError> { if (payload.len() / 4 * 3).saturating_sub(padding) > PICTURE_MAX_BYTES { return Err(ValidationError::new(field, "too large")); } - let bytes = BASE64 - .decode(payload) - .map_err(|_| ValidationError::new(field, "not base64"))?; + let bytes = BASE64.decode(payload).map_err(|_| ValidationError::new(field, "not base64"))?; if !bytes.starts_with(SIGNATURE) { return Err(ValidationError::new(field, "not a PNG")); } @@ -132,10 +130,7 @@ mod tests { } fn pictures(thumbnail: &str, picture: &str) -> DrawingPictures { - DrawingPictures { - thumbnail: thumbnail.into(), - picture: picture.into(), - } + DrawingPictures { thumbnail: thumbnail.into(), picture: picture.into() } } fn refused_field(pictures: &DrawingPictures) -> &'static str { @@ -143,10 +138,7 @@ mod tests { } fn reference(id: &str, title: &str) -> DrawingRef { - DrawingRef { - id: id.into(), - title: title.into(), - } + DrawingRef { id: id.into(), title: title.into() } } #[test] @@ -156,13 +148,7 @@ mod tests { let decoded = pictures(&uri_of(&small), &uri_of(&large)).decoded(); - assert_eq!( - decoded, - Ok(Some(Pictures { - thumbnail: small, - picture: large - })) - ); + assert_eq!(decoded, Ok(Some(Pictures { thumbnail: small, picture: large }))); } #[test] @@ -189,26 +175,14 @@ mod tests { "data:image/png;base64,***".to_string(), uri_of(b"GIF89a, not a PNG"), ] { - assert_eq!( - refused_field(&pictures(&bad, &good)), - "pictures.thumbnail", - "{bad}" - ); - assert_eq!( - refused_field(&pictures(&good, &bad)), - "pictures.picture", - "{bad}" - ); + assert_eq!(refused_field(&pictures(&bad, &good)), "pictures.thumbnail", "{bad}"); + assert_eq!(refused_field(&pictures(&good, &bad)), "pictures.picture", "{bad}"); } } #[test] fn a_picture_up_to_the_limit_is_kept() { - for size in [ - PICTURE_MAX_BYTES - 2, - PICTURE_MAX_BYTES - 1, - PICTURE_MAX_BYTES, - ] { + for size in [PICTURE_MAX_BYTES - 2, PICTURE_MAX_BYTES - 1, PICTURE_MAX_BYTES] { let largest = png_of(size); let decoded = pictures(&uri_of(&png_of(16)), &uri_of(&largest)).decoded(); @@ -223,10 +197,7 @@ mod tests { let refused = pictures(&uri_of(&png_of(16)), &past).decoded().unwrap_err(); - assert_eq!( - refused, - ValidationError::new("pictures.picture", "too large") - ); + assert_eq!(refused, ValidationError::new("pictures.picture", "too large")); } #[test] @@ -235,10 +206,7 @@ mod tests { let refused = pictures(&past, &uri_of(&png_of(16))).decoded().unwrap_err(); - assert_eq!( - refused, - ValidationError::new("pictures.thumbnail", "too large") - ); + assert_eq!(refused, ValidationError::new("pictures.thumbnail", "too large")); } #[test] diff --git a/crates/engine/src/notes/duplicate.rs b/crates/engine/src/notes/duplicate.rs index f0ec6463c..669b5bb78 100644 --- a/crates/engine/src/notes/duplicate.rs +++ b/crates/engine/src/notes/duplicate.rs @@ -30,11 +30,7 @@ pub(crate) fn duplicate( continue; } - let twin = Attachment { - id: Uuid::new_v4().to_string(), - note_id: copy.id.clone(), - ..attachment - }; + let twin = Attachment { id: Uuid::new_v4().to_string(), note_id: copy.id.clone(), ..attachment }; std::fs::copy(&source, directory.join(twin.stored_name())).context(twin.stored_name())?; carried.push(twin); } @@ -70,12 +66,8 @@ mod tests { /// A pinned note filed with a field value, and a library that writes its files to disk. fn shelf(kind: NoteKind) -> Shelf { let scratch = tempfile::tempdir().unwrap(); - let mut library = open_in_memory() - .unwrap() - .with_directory(scratch.path().to_path_buf()); - let space_id = crate::spaces::store::create(&mut library, "Work") - .unwrap() - .id; + let mut library = open_in_memory().unwrap().with_directory(scratch.path().to_path_buf()); + let space_id = crate::spaces::store::create(&mut library, "Work").unwrap().id; let original = Note { space_id, kind, @@ -85,11 +77,7 @@ mod tests { ..note() }; store::insert_imported(&mut library, &original).unwrap(); - Shelf { - _scratch: scratch, - library, - original, - } + Shelf { _scratch: scratch, library, original } } fn attach(shelf: &mut Shelf, id: &str, with_file: bool) -> Attachment { @@ -134,10 +122,7 @@ mod tests { ..shelf.original.clone() } ); - assert_eq!( - store::get(&mut shelf.library, "n-1").unwrap(), - shelf.original - ); + assert_eq!(store::get(&mut shelf.library, "n-1").unwrap(), shelf.original); } #[test] @@ -152,16 +137,8 @@ mod tests { assert_ne!(carried[0].id, "a-1"); assert_eq!(carried[0].file_name, "a-1.txt"); let directory = attachments::files::directory(&shelf.library); - assert_eq!( - std::fs::read(directory.join(carried[0].stored_name())).unwrap(), - b"a-1" - ); - assert_eq!( - attachments::store::list(&mut shelf.library, "n-1") - .unwrap() - .len(), - 1 - ); + assert_eq!(std::fs::read(directory.join(carried[0].stored_name())).unwrap(), b"a-1"); + assert_eq!(attachments::store::list(&mut shelf.library, "n-1").unwrap().len(), 1); } /// As an export leaves it: the original has no bytes to give either. @@ -181,10 +158,7 @@ mod tests { #[test] fn a_copy_of_a_drawing_carries_its_pictures() { let mut shelf = shelf(NoteKind::Drawing); - let taken = Pictures { - thumbnail: b"small".to_vec(), - picture: b"large".to_vec(), - }; + let taken = Pictures { thumbnail: b"small".to_vec(), picture: b"large".to_vec() }; let (db, vault) = shelf.library.split(); pictures::save(db, vault, "n-1", &taken).unwrap(); @@ -210,10 +184,7 @@ mod tests { #[test] fn a_copy_of_a_todo_list_keeps_its_items() { let mut shelf = shelf(NoteKind::Checklist); - let items = vec![crate::notes::checklist::ChecklistItem { - text: "Publish".into(), - done: true, - }]; + let items = vec![crate::notes::checklist::ChecklistItem { text: "Publish".into(), done: true }]; let patch = crate::notes::model::NotePatch { items: Some(items.clone()), ..crate::notes::model::NotePatch::default() @@ -222,9 +193,6 @@ mod tests { let copy = duplicate(&mut shelf.library, "n-1", "Copy".into(), later()).unwrap(); - assert_eq!( - store::get(&mut shelf.library, ©.id).unwrap().items, - items - ); + assert_eq!(store::get(&mut shelf.library, ©.id).unwrap().items, items); } } diff --git a/crates/engine/src/notes/kind.rs b/crates/engine/src/notes/kind.rs index 39d0bc27e..0706a00c6 100644 --- a/crates/engine/src/notes/kind.rs +++ b/crates/engine/src/notes/kind.rs @@ -45,9 +45,6 @@ mod tests { fn each_kind_keeps_its_stored_spelling_in_the_rail_s_order() { let spellings = NoteKind::ALL.map(NoteKind::as_str); - assert_eq!( - spellings, - ["snippet", "note", "checklist", "calc", "drawing"] - ); + assert_eq!(spellings, ["snippet", "note", "checklist", "calc", "drawing"]); } } diff --git a/crates/engine/src/notes/language.rs b/crates/engine/src/notes/language.rs index 9b4e76819..629436e58 100644 --- a/crates/engine/src/notes/language.rs +++ b/crates/engine/src/notes/language.rs @@ -156,19 +156,13 @@ closed_enum! { /// The front end's choice if it made one, `txt` meaning it made none. pub fn for_draft(draft: &NoteDraft) -> Language { - if draft.language == Language::default() { - from_content(&draft.content) - } else { - draft.language - } + if draft.language == Language::default() { from_content(&draft.content) } else { draft.language } } /// A snippet's first content, when nothing was chosen: creation sees no content if the title /// came first, the paste after. The refusals keep detection from becoming a correction. pub fn after_patch(before: &Note, patch: &NotePatch) -> Option { - if patch.language.is_some() - || before.language != Language::default() - || !before.content.trim().is_empty() + if patch.language.is_some() || before.language != Language::default() || !before.content.trim().is_empty() { return None; } @@ -202,11 +196,7 @@ struct Sample<'a> { impl<'a> Sample<'a> { fn of(content: &'a str) -> Self { let trimmed = content.trim(); - Self { - trimmed, - lower: trimmed.to_lowercase(), - lines: trimmed.lines().map(str::trim).collect(), - } + Self { trimmed, lower: trimmed.to_lowercase(), lines: trimmed.lines().map(str::trim).collect() } } fn has(&self, needle: &str) -> bool { @@ -366,10 +356,7 @@ fn score_json(sample: &Sample<'_>) -> u32 { let wrapped = (content.starts_with('{') && content.ends_with('}')) || (content.starts_with('[') && content.ends_with(']')); - worth( - SIGNATURE, - wrapped && (content.contains('"') || content.starts_with('[')), - ) + worth(SIGNATURE, wrapped && (content.contains('"') || content.starts_with('['))) } /// A signature, which keeps it ahead of the markup score its `<` also earns. @@ -388,9 +375,7 @@ fn score_xml(sample: &Sample<'_>) -> u32 { /// Its tags are a signature: they must outweigh the markup shape XML earns on the same text. fn score_html(sample: &Sample<'_>) -> u32 { - const TAGS: [&str; 8] = [ - "", "", ") -> u32 { ]; worth(STRONG, starts_with_any(&sample.lower, &STATEMENTS)) - + worth( - WEAK, - sample.lower.contains(" from ") || sample.lower.contains(" where "), - ) + + worth(WEAK, sample.lower.contains(" from ") || sample.lower.contains(" where ")) } /// An operation or a fragment is a signature; a schema's `type User {` is TypeScript's shape @@ -424,8 +406,7 @@ fn score_graphql(sample: &Sample<'_>) -> u32 { let operation = sample.has("{") && sample.any_line(|line| { ["query", "mutation", "subscription"].iter().any(|keyword| { - line.strip_prefix(keyword) - .is_some_and(|rest| rest.starts_with([' ', '{', '('])) + line.strip_prefix(keyword).is_some_and(|rest| rest.starts_with([' ', '{', '('])) }) }); let fragment = sample.has("... on ") @@ -437,9 +418,7 @@ fn score_graphql(sample: &Sample<'_>) -> u32 { else { return false; }; - name.ends_with('{') - && !name.contains('=') - && name.chars().next().is_some_and(char::is_uppercase) + name.ends_with('{') && !name.contains('=') && name.chars().next().is_some_and(char::is_uppercase) }); worth(SIGNATURE, operation || fragment) @@ -449,10 +428,7 @@ fn score_graphql(sample: &Sample<'_>) -> u32 { /// A section and an assignment: `[…]` alone could be an array on its own line. fn score_toml(sample: &Sample<'_>) -> u32 { - worth( - SIGNATURE, - sample.any_line(is_toml_section) && sample.any_line(is_assignment), - ) + worth(SIGNATURE, sample.any_line(is_toml_section) && sample.any_line(is_assignment)) } fn is_toml_section(line: &str) -> bool { @@ -478,28 +454,16 @@ fn is_identifier_char(c: char) -> bool { /// `class` needs its trailing colon: without it, this is TypeScript's. fn score_python(sample: &Sample<'_>) -> u32 { worth(SIGNATURE, sample.has("__name__")) - + worth( - STRONG, - sample.line_starts_with_any(&["def ", "async def ", "elif "]), - ) - + worth( - STRONG, - sample.any_line(|line| line.starts_with("class ") && line.ends_with(':')), - ) - + worth( - STRONG, - sample.any_line(|line| line.starts_with("from ") && line.contains(" import ")), - ) + + worth(STRONG, sample.line_starts_with_any(&["def ", "async def ", "elif "])) + + worth(STRONG, sample.any_line(|line| line.starts_with("class ") && line.ends_with(':'))) + + worth(STRONG, sample.any_line(|line| line.starts_with("from ") && line.contains(" import "))) + worth(WEAK, sample.has("self.")) } /// `fmt.Print` and `package main` are Go's alone; `import (` is its grouped form. fn score_go(sample: &Sample<'_>) -> u32 { worth(SIGNATURE, sample.has("fmt.Print")) - + worth( - STRONG, - sample.line_starts_with_any(&["func ", "package main", "import ("]), - ) + + worth(STRONG, sample.line_starts_with_any(&["func ", "package main", "import ("])) + worth(WEAK, sample.has(":=") || sample.has("err != nil")) } @@ -514,10 +478,7 @@ fn score_rust(sample: &Sample<'_>) -> u32 { starts_with_any(line, &["fn ", "async fn ", "impl "]) }), ) - + worth( - STRONG, - sample.any_line(|line| line.starts_with("use ") && line.contains("::")), - ) + + worth(STRONG, sample.any_line(|line| line.starts_with("use ") && line.contains("::"))) + worth( WEAK, sample.any_line(|line| { @@ -525,37 +486,24 @@ fn score_rust(sample: &Sample<'_>) -> u32 { starts_with_any(line, &["struct ", "trait ", "enum "]) }), ) - + worth( - WEAK, - sample.has("&str") || sample.has("Vec<") || sample.has("Option<"), - ) + + worth(WEAK, sample.has("&str") || sample.has("Vec<") || sample.has("Option<")) } /// `public class` is left to neither this nor C#: both write it. fn score_java(sample: &Sample<'_>) -> u32 { - worth( - SIGNATURE, - sample.has("System.out.print") || sample.has("public static void main"), - ) + worth( - STRONG, - sample.any_line(|line| line.starts_with("import java")), - ) + worth(SIGNATURE, sample.has("System.out.print") || sample.has("public static void main")) + + worth(STRONG, sample.any_line(|line| line.starts_with("import java"))) } fn score_csharp(sample: &Sample<'_>) -> u32 { worth(SIGNATURE, sample.has("Console.Write")) - + worth( - STRONG, - sample.line_starts_with_any(&["using System", "namespace "]), - ) + + worth(STRONG, sample.line_starts_with_any(&["using System", "namespace "])) } /// `#include` is the one marker nothing else here writes. fn score_c(sample: &Sample<'_>) -> u32 { - worth( - SIGNATURE, - sample.any_line(|line| line.starts_with("#include")), - ) + worth(STRONG, sample.has("int main(") && sample.has("printf(")) + worth(SIGNATURE, sample.any_line(|line| line.starts_with("#include"))) + + worth(STRONG, sample.has("int main(") && sample.has("printf(")) } /// Its own markers only, never JavaScript's: inheriting them would tie the two on every file. @@ -576,20 +524,10 @@ fn score_typescript(sample: &Sample<'_>) -> u32 { /// `=>` is the greediest marker in this file — C++, Kotlin, Swift, Scala, Dart and anything /// with a lambda write it — so it is worth the least. fn score_javascript(sample: &Sample<'_>) -> u32 { - const KEYWORDS: [&str; 7] = [ - "function ", - "const ", - "let ", - "var ", - "export ", - "import ", - "class ", - ]; + const KEYWORDS: [&str; 7] = ["function ", "const ", "let ", "var ", "export ", "import ", "class "]; - worth( - SIGNATURE, - sample.has("console.log") || sample.has("require("), - ) + worth(WEAK, sample.has("=>")) + worth(SIGNATURE, sample.has("console.log") || sample.has("require(")) + + worth(WEAK, sample.has("=>")) + worth(WEAK, sample.line_starts_with_any(&KEYWORDS)) } @@ -607,9 +545,10 @@ fn score_css(sample: &Sample<'_>) -> u32 { }); let has_selector = sample.any_line(|line| { line.ends_with('{') - && line.chars().next().is_some_and(|c| { - c.is_ascii_alphabetic() || matches!(c, '.' | '#' | '@' | ':' | '*') - }) + && line + .chars() + .next() + .is_some_and(|c| c.is_ascii_alphabetic() || matches!(c, '.' | '#' | '@' | ':' | '*')) }); let stylesheet_only = sample.has("--") || ["px;", "rem;", "%;", "px ", "em;", "vh;", "vw;", "fr;"] @@ -622,14 +561,7 @@ fn score_css(sample: &Sample<'_>) -> u32 { /// Its own markers only, never CSS's, which it earns as well: a stylesheet with no variable, /// mixin or nesting is CSS, whatever file it came from. fn score_scss(sample: &Sample<'_>) -> u32 { - const AT_RULES: [&str; 6] = [ - "@mixin ", - "@include ", - "@use ", - "@forward ", - "@extend ", - "@each ", - ]; + const AT_RULES: [&str; 6] = ["@mixin ", "@include ", "@use ", "@forward ", "@extend ", "@each "]; let variable = sample.any_line(|line| { line.strip_prefix('$').is_some_and(|rest| { @@ -642,10 +574,7 @@ fn score_scss(sample: &Sample<'_>) -> u32 { // tie with CSS's own score would answer `txt`. let nested = sample.line_starts_with_any(&["&:", "&.", "&-", "& "]); - worth( - SIGNATURE, - variable || nested || sample.line_starts_with_any(&AT_RULES), - ) + worth(SIGNATURE, variable || nested || sample.line_starts_with_any(&AT_RULES)) } fn score_yaml(sample: &Sample<'_>) -> u32 { @@ -666,9 +595,7 @@ fn is_mapping(line: &str) -> bool { return false; }; - !key.is_empty() - && key.chars().all(is_identifier_char) - && (value.is_empty() || value.starts_with(' ')) + !key.is_empty() && key.chars().all(is_identifier_char) && (value.is_empty() || value.starts_with(' ')) } fn score_markdown(sample: &Sample<'_>) -> u32 { @@ -681,15 +608,11 @@ fn score_markdown(sample: &Sample<'_>) -> u32 { /// Deliberately thin: a wide list would catch prose. fn score_shell(sample: &Sample<'_>) -> u32 { - const COMMANDS: [&str; 10] = [ - "echo ", "cd ", "ls ", "cat ", "grep ", "sudo ", "npm ", "git ", "docker ", "curl ", - ]; + const COMMANDS: [&str; 10] = + ["echo ", "cd ", "ls ", "cat ", "grep ", "sudo ", "npm ", "git ", "docker ", "curl "]; worth(STRONG, sample.line_starts_with_any(&COMMANDS)) - + worth( - WEAK, - sample.any_line(|line| line.starts_with('$') || line.starts_with("./")), - ) + + worth(WEAK, sample.any_line(|line| line.starts_with('$') || line.starts_with("./"))) + worth(WEAK, sample.has(" | ") || sample.has(" && ")) } @@ -707,58 +630,40 @@ fn score_powershell(sample: &Sample<'_>) -> u32 { ]; worth(STRONG, CMDLETS.iter().any(|cmdlet| sample.has(cmdlet))) - + worth( - WEAK, - sample.any_line(|line| line.starts_with('$') && line.contains(" = ")), - ) + + worth(WEAK, sample.any_line(|line| line.starts_with('$') && line.contains(" = "))) + worth(WEAK, sample.has("@{")) } /// `fun` and `val` begin a line in Kotlin alone: Swift writes `func`, Scala is not offered. fn score_kotlin(sample: &Sample<'_>) -> u32 { worth(SIGNATURE, sample.has("fun main(")) - + worth( - STRONG, - sample.line_starts_with_any(&["fun ", "val ", "data class ", "object "]), - ) + + worth(STRONG, sample.line_starts_with_any(&["fun ", "val ", "data class ", "object "])) + worth(WEAK, sample.has("?.") && sample.has("val ")) } /// A line that is only `end` is Ruby's or Elixir's: worth little, and the same to both. fn score_ruby(sample: &Sample<'_>) -> u32 { - worth( - SIGNATURE, - sample.line_starts_with_any(&["require '", "require \""]), - ) + worth( - STRONG, - sample.line_starts_with_any(&["puts ", "attr_accessor "]), - ) + worth(STRONG, sample.has(" do |")) + worth(SIGNATURE, sample.line_starts_with_any(&["require '", "require \""])) + + worth(STRONG, sample.line_starts_with_any(&["puts ", "attr_accessor "])) + + worth(STRONG, sample.has(" do |")) + worth(WEAK, sample.any_line(|line| line == "end")) } fn score_swift(sample: &Sample<'_>) -> u32 { - worth( - SIGNATURE, - sample.line_starts_with_any(&["import Foundation", "import SwiftUI", "import UIKit"]), - ) + worth(STRONG, sample.has("guard let ") || sample.has("if let ")) + worth(SIGNATURE, sample.line_starts_with_any(&["import Foundation", "import SwiftUI", "import UIKit"])) + + worth(STRONG, sample.has("guard let ") || sample.has("if let ")) + worth(WEAK, sample.has("func ") && sample.has(" -> ")) } fn score_dart(sample: &Sample<'_>) -> u32 { - worth( - SIGNATURE, - sample.line_starts_with_any(&["import 'package:", "import \"package:"]), - ) + worth( - STRONG, - sample.line_starts_with_any(&["Future main(", "void main() {"]), - ) + worth(WEAK, sample.line_starts_with_any(&["final "])) + worth(SIGNATURE, sample.line_starts_with_any(&["import 'package:", "import \"package:"])) + + worth(STRONG, sample.line_starts_with_any(&["Future main(", "void main() {"])) + + worth(WEAK, sample.line_starts_with_any(&["final "])) } fn score_elixir(sample: &Sample<'_>) -> u32 { - worth( - SIGNATURE, - sample.line_starts_with_any(&["defmodule "]) || sample.has("|>"), - ) + worth(STRONG, sample.has("IO.puts") || sample.has("IO.inspect")) + worth(SIGNATURE, sample.line_starts_with_any(&["defmodule "]) || sample.has("|>")) + + worth(STRONG, sample.has("IO.puts") || sample.has("IO.inspect")) + worth(WEAK, sample.any_line(|line| line == "end")) } @@ -780,9 +685,7 @@ fn from_shebang(first_line: &str) -> Language { let mut words = first_line.trim_start_matches("#!").split_whitespace(); let program = words.next().unwrap_or_default(); let program = if program.ends_with("/env") { - words - .find(|word| !word.starts_with('-')) - .unwrap_or_default() + words.find(|word| !word.starts_with('-')).unwrap_or_default() } else { program }; @@ -830,23 +733,14 @@ fn score_cpp(sample: &Sample<'_>) -> u32 { signed( header || MARKERS.iter().any(|marker| sample.has(marker)), worth(STRONG, header) - + worth( - STRONG, - sample.line_starts_with_any(&["public:", "private:", "protected:"]), - ), + + worth(STRONG, sample.line_starts_with_any(&["public:", "private:", "protected:"])), ) } /// Markup in a script, with what React alone writes in it. fn jsx_markup(sample: &Sample<'_>) -> bool { - const ATTRIBUTES: [&str; 6] = [ - "className=", - "onClick={", - "onChange={", - "onSubmit={", - "useState(", - "useEffect(", - ]; + const ATTRIBUTES: [&str; 6] = + ["className=", "onClick={", "onChange={", "onSubmit={", "useState(", "useEffect("]; (sample.has("/>") || sample.has(") -> bool { /// The markup is worth what HTML's tags are, on top: a component outscores the page. fn score_jsx(sample: &Sample<'_>) -> u32 { - signed( - jsx_markup(sample), - STRONG + worth(STRONG, script_keyword(sample)), - ) + signed(jsx_markup(sample), STRONG + worth(STRONG, script_keyword(sample))) } /// JSX plus TypeScript's own score, so a typed component outscores both, and nothing without /// a type. fn score_tsx(sample: &Sample<'_>) -> u32 { let typed = score_typescript(sample); - signed( - jsx_markup(sample) && typed > 0, - STRONG + typed + worth(STRONG, script_keyword(sample)), - ) + signed(jsx_markup(sample) && typed > 0, STRONG + typed + worth(STRONG, script_keyword(sample))) } fn score_vue(sample: &Sample<'_>) -> u32 { - const DIRECTIVES: [&str; 7] = [ - "v-if=", - "v-for=", - "v-model=", - "v-bind:", - "v-on:", - "v-else", - "