From 0a56d7df9d496b494b42cc1cc3d598b3c1070e88 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 15:50:56 -0800 Subject: [PATCH] Tests: script DOM and New Document tests check what they name - The grid-by-column test now checks each artboard's row and column, so RLGridByCol must fill from the rightmost column. It compared only the number of distinct rows and columns before, which a left-to-right fill also passes. - The keepEmpty test asserts that keepEmpty false deletes the compound path, instead of accepting any state other than an empty compound. - The addDocument profile test closes the profile document before the script reads the profile, so the read goes through the app-folder exemption and not through the rule for open documents' files. - The report-origin test adds authored ReferenceError controls for Window and activeDocument, and for BridgeTalk thrown as an error object, so a hint list that grows to those names cannot change a message the script wrote. - New Document profile tests, and the temporary folders and files in script_dom.rs and script_run.rs, use vectorcraft_testkit::TempDir, so a failing assertion no longer leaves process-id folders behind. The linked-profile test keeps its link target in the same temporary folder. --- crates/engine/src/tests/newdoc.rs | 51 ++++++++++----------------- crates/engine/src/tests/script_dom.rs | 41 ++++++++++++++------- crates/engine/src/tests/script_run.rs | 51 +++++++++------------------ 3 files changed, 63 insertions(+), 80 deletions(-) diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index ad2711558e..20411101d0 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -631,13 +631,14 @@ fn rearrange_refuses_bad_indices_and_at() { assert_eq!((r["indices"].clone(), boards(&s)[2]), (json!([2]), Rect::new(0.0, 500.0, 100.0, 550.0))); } -/// A session whose New Document profiles are in a fresh folder for test `name` (not made yet). -fn with_profiles(name: &str) -> (Session, std::path::PathBuf) { - let dir = std::env::temp_dir().join(format!("vc-newdoc-profiles-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); +/// A session whose New Document profiles are in a fresh folder for test `name` (not made yet), +/// inside the returned temporary folder, which is removed when dropped, also when the test fails. +fn with_profiles(name: &str) -> (Session, std::path::PathBuf, vectorcraft_testkit::TempDir) { + let root = vectorcraft_testkit::TempDir::new(&format!("newdoc-profiles-{name}")); + let dir = root.join(format!("vc-newdoc-profiles-{name}")); let mut s = Session::new(); s.attach_new_doc_profiles(dir.clone()); - (s, dir) + (s, dir, root) } fn swatch_names(s: &Session) -> Vec { @@ -705,7 +706,7 @@ fn edit_print_profile(s: &mut Session, dir: &std::path::Path) { #[test] fn an_edited_profile_starts_the_documents_of_its_category() { - let (mut s, dir) = with_profiles("edited"); + let (mut s, dir, _root) = with_profiles("edited"); let listed = s.execute("file.newProfiles", &json!({})).unwrap(); let names: Vec<&str> = listed["profiles"].as_array().unwrap().iter().map(|p| p["name"].as_str().unwrap()).collect(); assert_eq!(names, ["Mobile", "Web", "Print", "Film & Video", "Art & Illustration", "Branding", "Social"]); @@ -733,7 +734,6 @@ fn an_edited_profile_starts_the_documents_of_its_category() { s.execute("file.new", &json!({"preset": "A4", "colorMode": "rgb"})).unwrap(); let red = s.doc().unwrap().doc.swatches.iter().find(|w| w.name == "Brand Red").cloned().expect("converted, not dropped"); assert!(matches!(red.paint, vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. }), "{:?}", red.paint); - let _ = std::fs::remove_dir_all(&dir); } /// The fill, stroke and weight of `id` in the active document. @@ -745,7 +745,7 @@ fn look(s: &Session, id: u64) -> (vectorcraft_color::Paint, vectorcraft_color::P #[test] fn a_redefined_default_graphic_style_in_a_profile_is_the_default_fill_and_stroke() { use vectorcraft_color::Paint; - let (mut s, dir) = with_profiles("default-style"); + let (mut s, _, _root) = with_profiles("default-style"); // The Print profile's Default Graphic Style becomes no fill and a 0.25 pt red stroke. s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); @@ -796,12 +796,11 @@ fn a_redefined_default_graphic_style_in_a_profile_is_the_default_fill_and_stroke assert_eq!(s.paint.fill, green); s.execute("paint.default", &json!({})).unwrap(); assert_eq!(s.paint, vectorcraft_tools::PaintDefaults::default()); - let _ = std::fs::remove_dir_all(&dir); } #[test] fn the_profile_follows_the_preset_access_and_reset() { - let (mut s, dir) = with_profiles("choice"); + let (mut s, dir, _root) = with_profiles("choice"); edit_print_profile(&mut s, &dir); // A request that may not read the folder gets the defaults, and the reason; edit is refused // before anything is written. @@ -841,7 +840,6 @@ fn the_profile_follows_the_preset_access_and_reset() { assert_eq!(s.execute("file.newProfiles.reset", &json!({"name": "Print"})).unwrap(), json!({"name": "Print", "reset": false})); let r = s.execute("file.new", &json!({"preset": "A4"})).unwrap(); assert!(r.get("profile").is_none() && !swatch_names(&s).contains(&"Brand Red".to_string()), "{r}"); - let _ = std::fs::remove_dir_all(&dir); } /// The first run's style of text object `id`. @@ -853,7 +851,7 @@ fn first_run(s: &Session, id: &Value) -> vectorcraft_doc::CharStyle { #[test] fn a_profiles_normal_character_style_is_the_default_font() { - let (mut s, dir) = with_profiles("default-font"); + let (mut s, _, _root) = with_profiles("default-font"); // The Print profile's [Normal Character Style] becomes Source Serif 4 Regular at 9 pt. s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); let attrs = json!({"font_family": "Source Serif 4", "font_style": "Regular", "size": 9, "charAlign": "emBoxBottom"}); @@ -891,13 +889,12 @@ fn a_profiles_normal_character_style_is_the_default_font() { let st = first_run(&s, &made["id"]); let default = vectorcraft_doc::CharStyle::default(); assert_eq!((st.font_family, st.size), (default.font_family, default.size)); - let _ = std::fs::remove_dir_all(&dir); } #[test] fn an_open_document_takes_another_profiles_default_fill_stroke_and_font() { use vectorcraft_color::Paint; - let (mut s, dir) = with_profiles("apply-defaults"); + let (mut s, _, _root) = with_profiles("apply-defaults"); const GLOW: &str = r#""#; // The CMYK Print profile: no fill and a 0.25 pt stroke of the global swatch Laser Red, with // the SVG filter Glow7653, and red type in Source Serif 4 at 9 pt. @@ -987,7 +984,6 @@ fn an_open_document_takes_another_profiles_default_fill_stroke_and_font() { assert!(s.execute("file.newProfiles.applyDefaults", &json!({"name": "Posters"})).is_err()); assert!(s.execute("file.newProfiles.applyDefaults", &json!({})).is_err()); assert_eq!(s.doc().unwrap().history.step(), step); - let _ = std::fs::remove_dir_all(&dir); } /// With New Art Has Basic Appearance off, the selected object's look does not replace the profile's @@ -995,7 +991,7 @@ fn an_open_document_takes_another_profiles_default_fill_stroke_and_font() { #[test] fn profile_defaults_stay_with_an_unrelated_object_selected() { use vectorcraft_color::Paint; - let (mut s, dir) = with_profiles("apply-defaults-selected"); + let (mut s, _, _root) = with_profiles("apply-defaults-selected"); s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); s.execute("paint.setFill", &json!({"none": true})).unwrap(); @@ -1013,7 +1009,6 @@ fn profile_defaults_stay_with_an_unrelated_object_selected() { assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::None, 0.25)); let id = s.execute("shape.rectangle", &json!({"x": 60, "y": 80, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap(); assert_eq!((look(&s, id).0, look(&s, id).2), (Paint::None, Some(0.25))); - let _ = std::fs::remove_dir_all(&dir); } /// A profile whose [Normal Character Style] is set in one of its composite fonts gives the open @@ -1026,7 +1021,7 @@ fn profile_defaults_bring_the_composite_font_of_the_default_font() { "roman": {"font": "JetBrains Mono", "size": roman}, }}) }; - let (mut s, dir) = with_profiles("apply-defaults-composite"); + let (mut s, _, _root) = with_profiles("apply-defaults-composite"); s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); s.execute("type.compositeFonts.set", &json!({"fonts": [font(50.0)]})).unwrap(); let t = s.execute("text.create", &json!({"x": 10, "y": 80, "text": "Ab", "font": "CF Profile 7653", "size": 12})).unwrap(); @@ -1052,12 +1047,11 @@ fn profile_defaults_bring_the_composite_font_of_the_default_font() { s.execute("edit.undo", &json!({})).unwrap(); s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(profile(&s), Some(100.0)); - let _ = std::fs::remove_dir_all(&dir); } #[test] fn profile_errors_name_the_file_by_its_name_outside_the_read_roots() { - let (mut s, dir) = with_profiles("errors"); + let (mut s, dir, _root) = with_profiles("errors"); let elsewhere = dir.with_extension("elsewhere"); std::fs::create_dir_all(&dir).unwrap(); std::fs::create_dir_all(&elsewhere).unwrap(); @@ -1084,22 +1078,19 @@ fn profile_errors_name_the_file_by_its_name_outside_the_read_roots() { let inside = crate::file_access::AutomationRoots::new(&[dir.as_path()], &[dir.as_path()]).unwrap().unwrap(); let e = run(&mut s, &inside, "file.newProfiles.reset"); assert!(e.starts_with(&format!("{whole}: ")), "{e}"); - let _ = std::fs::remove_dir_all(&elsewhere); - let _ = std::fs::remove_dir_all(&dir); } /// The new document's links find their files from the profile's file, as a document opened from /// that file does; a document without a profile has no such file. #[test] fn the_new_document_links_from_the_profile_file() { - let (mut s, dir) = with_profiles("links"); + let (mut s, dir, _root) = with_profiles("links"); edit_print_profile(&mut s, &dir); assert_eq!(s.execute("file.new", &json!({"preset": "A4"})).unwrap()["profile"], "Print"); let file = dir.join("Print.vectorcraft").to_string_lossy().to_string(); assert_eq!(s.doc().unwrap().links_from.as_deref(), Some(file.as_str())); s.execute("file.new", &json!({"preset": "Web 1920×1080"})).unwrap(); assert_eq!(s.doc().unwrap().links_from, None); - let _ = std::fs::remove_dir_all(&dir); } /// A color profile the profile's file carries is installed when this machine lacks it, as opening @@ -1111,7 +1102,7 @@ fn a_profile_brings_the_color_profile_its_file_carries() { return; } use vectorcraft_color::cms; - let (mut s, dir) = with_profiles("icc"); + let (mut s, dir, _root) = with_profiles("icc"); let builtin = cms::profiles().into_iter().find(|p| p.kind == cms::ProfileKind::Rgb && p.builtin && p.name != cms::SRGB).unwrap(); let icc = cms::icc_bytes(&builtin.name).unwrap().to_vec(); let name = format!("Profile RGB {}", std::process::id()); @@ -1140,12 +1131,11 @@ fn a_profile_brings_the_color_profile_its_file_carries() { std::fs::write(dir.join("Web.vectorcraft"), serde_json::to_vec(&v).unwrap()).unwrap(); let r = s.execute("file.new", &json!({"preset": "Web 1920×1080"})).unwrap(); assert!(r["profile"] == "Web" && r["warnings"][0].as_str().unwrap_or_default().contains(&broken), "{r}"); - let _ = std::fs::remove_dir_all(&dir); } #[test] fn a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported() { - let (mut s, dir) = with_profiles("damaged"); + let (mut s, dir, _root) = with_profiles("damaged"); s.execute("file.new", &json!({"preset": "Letter", "profile": null})).unwrap(); let defaults = swatch_names(&s); std::fs::create_dir_all(&dir).unwrap(); @@ -1162,23 +1152,20 @@ fn a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported() { let r = s.execute("file.new", &json!({"preset": "Web 1920×1080"})).unwrap(); assert!(r["profileError"]["reason"].as_str().unwrap_or("").contains("larger than"), "{r}"); assert_eq!(s.doc().unwrap().doc.artboards[0].rect.width(), 1920.0); - let _ = std::fs::remove_dir_all(&dir); } #[cfg(unix)] #[test] fn a_profile_that_is_a_link_is_not_followed() { - let (mut s, dir) = with_profiles("link"); + let (mut s, dir, root) = with_profiles("link"); s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); // A profile the folder held, moved out and linked back in. - let outside = std::env::temp_dir().join(format!("vc-newdoc-profile-outside-{}.vectorcraft", std::process::id())); + let outside = root.join("outside.vectorcraft"); std::fs::rename(dir.join("Print.vectorcraft"), &outside).unwrap(); std::os::unix::fs::symlink(&outside, dir.join("Print.vectorcraft")).unwrap(); let r = s.execute("file.new", &json!({"preset": "Letter"})).unwrap(); assert_eq!(r["profileError"]["reason"], "not a plain file", "{r}"); assert!(r.get("profile").is_none(), "{r}"); - let _ = std::fs::remove_file(&outside); - let _ = std::fs::remove_dir_all(&dir); } #[test] diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 14878904fb..5b31203aeb 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -970,7 +970,11 @@ fn clearing_anchors_with_keep_empty_keeps_the_compound_path() { s.execute("edit.clear", &json!({"keepEmpty": keep})).unwrap(); let d = &s.active().unwrap().doc; assert!(d.node(a).is_none() && d.node(b).is_none(), "keepEmpty {keep}: both paths are deleted"); - assert_eq!(d.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), keep, "keepEmpty {keep}"); + if keep { + assert!(d.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), "keepEmpty true keeps it, empty"); + } else { + assert!(d.node(compound).is_none(), "keepEmpty false deletes the compound path"); + } } } @@ -1002,11 +1006,23 @@ fn a_grid_by_column_takes_the_number_of_rows() { let distinct = |mut v: Vec| { v.sort_unstable(); v.dedup(); - v.len() + v }; let tops = distinct(boards.iter().map(|b| b.rect.y0.round() as i64).collect()); let lefts = distinct(boards.iter().map(|b| b.rect.x0.round() as i64).collect()); - assert_eq!((tops, lefts), (rows, cols), "{layout} {count}"); + assert_eq!((tops.len(), lefts.len()), (rows, cols), "{layout} {count}"); + // Each artboard's row and column, counted from the top and from the left: a grid by column + // fills each column top to bottom, and the right-to-left grid starts at the rightmost column. + let index = |v: &[i64], x: f64| v.iter().position(|&t| t == x.round() as i64); + let placed: Vec<_> = boards.iter().map(|b| (index(&tops, b.rect.y0), index(&lefts, b.rect.x0))).collect(); + let expected: Vec<_> = (0..count) + .map(|i| match layout { + "GridByRow" => (Some(i / cols), Some(i % cols)), + "GridByCol" => (Some(i % rows), Some(i / rows)), + _ => (Some(i % rows), Some(cols - 1 - i / rows)), + }) + .collect(); + assert_eq!(placed, expected, "{layout} {count}"); } } @@ -1598,16 +1614,19 @@ fn add_document_takes_only_a_document_preset() { #[test] fn add_document_applies_the_profile_file_and_throws_when_it_cannot_be_read() { - let dir = std::env::temp_dir().join(format!("vc-script-add-document-profile-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); + let root = vectorcraft_testkit::TempDir::new("script-add-document-profile"); + let dir = root.join("profiles"); let mut s = Session::new(); s.attach_new_doc_profiles(dir.clone()); // A profile with no file gives the defaults. let out = log(&mut s, "vc.log(app.documents.addDocument('Web').typename);"); assert_eq!(out, vec![json!("Document")]); assert_eq!(s.doc().unwrap().links_from, None); - // A script reads the profile's file in the app's own folder. + // A script reads the profile's file in the app's own folder, with no document open from it. s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + while !s.documents().is_empty() { + s.execute("file.close", &json!({})).unwrap(); + } let file = dir.join("Print.vectorcraft").to_string_lossy().to_string(); log(&mut s, "app.documents.addDocument('Print');"); assert_eq!(s.doc().unwrap().links_from.as_deref(), Some(file.as_str())); @@ -1634,13 +1653,12 @@ fn add_document_applies_the_profile_file_and_throws_when_it_cannot_be_read() { // A startup preset with no profile reads no file. let out = log(&mut s, "vc.log(app.documents.addDocument('Basic RGB').documentColorSpace);"); assert_eq!(out, vec![json!("DocumentColorSpace.RGB")]); - let _ = std::fs::remove_dir_all(&dir); } #[test] fn add_document_names_a_color_profile_of_the_profile_file_that_cannot_be_used() { - let dir = std::env::temp_dir().join(format!("vc-script-add-document-warning-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); + let root = vectorcraft_testkit::TempDir::new("script-add-document-warning"); + let dir = root.join("profiles"); let mut s = Session::new(); s.attach_new_doc_profiles(dir.clone()); s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); @@ -1658,7 +1676,6 @@ fn add_document_names_a_color_profile_of_the_profile_file_that_cannot_be_used() let named = lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("addDocument: ") && l.contains(&broken)); assert!(named, "{lines:?}"); assert_eq!(s.documents().len(), 1); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -1761,8 +1778,7 @@ fn setters_on_a_stale_item_report_it_before_a_bad_value() { fn objects_read_before_a_revert_are_stale_and_ones_read_after_are_the_loaded_ones() { // `pageItems[0]` is the topmost object, the one made last. let (mut s, _, b) = doc(); - let dir = std::env::temp_dir().join(format!("vc-dom-revert-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); + let dir = vectorcraft_testkit::TempDir::new("dom-revert"); let path = dir.join("saved.vectorcraft"); s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); for read in ["i.name", "i.name = 'after'", "app.activeDocument.selection = i", "l.name"] { @@ -1778,7 +1794,6 @@ fn objects_read_before_a_revert_are_stale_and_ones_read_after_are_the_loaded_one ); assert_eq!(out, vec![json!(2)]); assert_eq!(s.active().unwrap().doc.node(b).unwrap().name.as_deref(), Some("loaded")); - let _ = std::fs::remove_dir_all(&dir); } #[test] diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 8fd3e8c8fe..fe56754ca3 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -88,10 +88,10 @@ fn a_run_is_one_undo_step_in_each_document_it_changed() { #[test] fn a_run_that_changes_nothing_leaves_no_step_no_mark_and_no_journal_entry() { + let dir = fresh_folder("noop"); for source in ["", "var a = 1 + 2;", "vc.log(vc.document); vc.commands.length;"] { let mut s = two_docs(); - s.execute("document.save", &json!({"path": std::env::temp_dir().join(format!("vc-noop-{}.svg", std::process::id())).to_string_lossy()})) - .unwrap(); + s.execute("document.save", &json!({"path": dir.join("noop.svg").to_string_lossy()})).unwrap(); let before = state(&s); let revisions = |s: &Session| s.documents().iter().map(|d| d.revision).collect::>(); let revisions_before = revisions(&s); @@ -183,6 +183,11 @@ fn failed_script_report_keeps_message_and_adds_origin() { ("throw new RangeError('invalid array length');", "thrown", "RangeError: invalid array length", "script"), ("throw 'invalid array length';", "thrown", "invalid array length", "script"), ("throw 'ReferenceError: BridgeTalk is not defined';", "thrown", "ReferenceError: BridgeTalk is not defined", "script"), + ("throw new ReferenceError('BridgeTalk is not defined');", "thrown", "ReferenceError: BridgeTalk is not defined", "script"), + ("throw 'ReferenceError: Window is not defined';", "thrown", "ReferenceError: Window is not defined", "script"), + ("throw new ReferenceError('Window is not defined');", "thrown", "ReferenceError: Window is not defined", "script"), + ("throw 'ReferenceError: activeDocument is not defined';", "thrown", "ReferenceError: activeDocument is not defined", "script"), + ("throw new ReferenceError('activeDocument is not defined');", "thrown", "ReferenceError: activeDocument is not defined", "script"), ("try { new Array(-1); } catch (e) { throw new Error(e.message); }", "thrown", "Error: invalid array length", "script"), ("new Array(-1);", "thrown", "RangeError: invalid array length", "built-in"), ("try { new Array(-1); } catch (e) { throw e; }", "thrown", "RangeError: invalid array length", "built-in"), @@ -266,9 +271,7 @@ fn bad_parameters_are_refused_before_anything_runs() { #[test] fn files_are_checked_before_they_are_read() { - let dir = std::env::temp_dir().join(format!("vc-script-run-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); + let dir = fresh_folder("checked"); let write = |name: &str, bytes: &[u8]| { let p = dir.join(name); std::fs::write(&p, bytes).unwrap(); @@ -296,7 +299,6 @@ fn files_are_checked_before_they_are_read() { assert_eq!(s.execute("script.run", &path(&upper)).unwrap()["log"], json!([3])); std::fs::create_dir_all(dir.join("folder.js")).unwrap(); assert!(s.execute("script.run", &path(&dir.join("folder.js").to_string_lossy())).is_err()); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -341,7 +343,6 @@ fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() { assert_eq!(kept["log"], json!(["1xy"]), "{kept}"); let e = s.execute("script.run", &path(&write("pattern.jsx", "var [a] = [1];"))).unwrap_err().to_string(); assert!(e.contains("SyntaxError"), "{e}"); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -367,7 +368,6 @@ fn a_js_script_reads_object_literal_extensions_and_function_names_and_a_jsx_scri assert_eq!(legacy["log"], json!([false]), "{legacy}"); // Script text given without a file keeps the ExtendScript language. assert!(run(&mut s, "var a = 1; var o = { a };").unwrap_err().to_string().contains("SyntaxError")); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -390,7 +390,6 @@ fn a_js_script_reads_optional_chains_and_coalescing_and_a_jsx_script_does_not() } // Script text given without a file keeps the ExtendScript language. assert!(run(&mut s, "vc.log(null ?? 1);").unwrap_err().to_string().contains("SyntaxError")); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -417,7 +416,6 @@ fn a_js_script_runs_generators_and_a_jsx_script_does_not_read_them() { s.execute("script.run", &path(&write("keep.jsx", "#targetengine genkept\nvar a = 1;"))).unwrap(); let e = s.execute("script.run", &path(&write("keep.js", "#targetengine genkept\nfunction* g() {}\ng();"))).unwrap_err().to_string(); assert!(e.contains("TypeError"), "{e}"); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -451,7 +449,6 @@ fn every_script_reads_e4x_and_has_the_xml_objects() { s.execute("script.run", &path(&write("first.js", "#targetengine xmlkept\nlet k = 1;"))).unwrap(); let later = s.execute("script.run", &path(&write("second.jsx", "#targetengine xmlkept\nvc.log(XML('2').toString());"))).unwrap(); assert_eq!(later["log"], json!(["2"]), "{later}"); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -474,15 +471,11 @@ fn a_js_script_defines_classes_and_a_jsx_script_cannot() { assert!(e.contains("SyntaxError"), "{name}: {e}"); } assert!(run(&mut s, "var C = class {};").unwrap_err().to_string().contains("SyntaxError")); - let _ = std::fs::remove_dir_all(&dir); } -/// A new empty folder for test `name`. -fn fresh_folder(name: &str) -> std::path::PathBuf { - let dir = std::env::temp_dir().join(format!("vc-script-run-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - dir +/// A new empty folder for test `name`, removed when dropped, also when the test fails. +fn fresh_folder(name: &str) -> vectorcraft_testkit::TempDir { + vectorcraft_testkit::TempDir::new(&format!("script-run-{name}")) } /// Starts `source` in the app after a folder dialog it opens first, and allows the script the folder @@ -530,7 +523,6 @@ fn a_failed_batch_puts_back_the_session_and_names_a_file_it_wrote() { assert!(!s.guides_locked(), "the failed batch's Lock Guides does not stay"); assert!(path.exists()); assert_eq!(r["written"], json!([p]), "{r}"); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -544,7 +536,6 @@ fn an_export_that_fails_names_no_file() { assert_eq!(r["log"], json!(["Error"]), "{r}"); assert!(!path.exists()); assert_eq!(r["written"], json!([]), "{r}"); - let _ = std::fs::remove_dir_all(&dir); } /// The commands a script runs read and write only where its `File` and `Folder` objects may (its @@ -594,7 +585,6 @@ fn a_scripts_commands_reach_only_its_own_places_and_the_open_documents() { let r = run(&mut s, &call("document.save", &own)).unwrap(); assert_eq!(r["log"], json!(["ok"]), "a document's own file that was removed is made again: {r}"); assert!(own.exists()); - let _ = std::fs::remove_dir_all(&dir); } /// The color at the middle of the PNG at `path`. @@ -656,7 +646,6 @@ fn a_scripts_export_reads_the_files_the_documents_open_before_it_link_to() { assert!(near(middle_color(&first), BLUE), "the linked file, not its preview: {:?}", middle_color(&first)); assert!(near(middle_color(&second), RED), "a document the script opened gets no linked file: {:?}", middle_color(&second)); assert_eq!(std::fs::read(&pic).unwrap(), png(600, 300, BLUE), "the linked file is not written"); - let _ = std::fs::remove_dir_all(&dir); } /// A script line that runs command `id` with `params` and logs `ok`, or `denied` when the gate @@ -674,7 +663,8 @@ fn tried(id: &str, params: &str) -> String { #[test] fn a_document_a_script_opened_from_a_linked_file_stays_read_only_in_later_runs() { use crate::tests_links::{RED, open, place, png, save, session, write}; - let art = fresh_folder("gate-linked-runs").join("art"); + let root = fresh_folder("gate-linked-runs"); + let art = root.join("art"); std::fs::create_dir_all(&art).unwrap(); let p = |f: std::path::PathBuf| f.to_string_lossy().into_owned(); let (pic, inner, poster) = (p(art.join("photo.png")), p(art.join("inner.vectorcraft")), p(art.join("poster.vectorcraft"))); @@ -704,7 +694,6 @@ fn a_document_a_script_opened_from_a_linked_file_stays_read_only_in_later_runs() log.push(later["log"][0].clone()); assert_eq!(log, [json!("denied"), json!("denied")], "a save in the next run, then a read once nothing the person left links to it"); assert_eq!(std::fs::read(&inner).unwrap(), bytes, "the linked file is as it was"); - let _ = std::fs::remove_dir_all(art.parent().unwrap()); } /// A data set value a script gives a document, and a document a script opens, let no later run @@ -741,7 +730,6 @@ fn what_a_script_adds_to_the_documents_lets_no_later_run_read_more() { s.execute("document.save", &json!({"path": mine})).unwrap(); let saved = run(&mut s, &read_secret).unwrap(); assert_eq!(saved["log"], json!(["ok"]), "saved by the person: {saved}"); - let _ = std::fs::remove_dir_all(&dir); } /// A save the person started before a script's command changed the document, and that finishes @@ -766,7 +754,6 @@ fn a_save_started_before_a_scripts_change_lets_no_later_run_read_more() { job.complete(&mut s, uid); let r = run(&mut s, &tried("file.place", &format!("{{path: {secret:?}, at: [200, 150]}}"))).unwrap(); assert_eq!(r["log"], json!(["denied"]), "{r}"); - let _ = std::fs::remove_dir_all(&dir); } /// A command a script runs does not save into the app's own libraries; the same command run @@ -784,7 +771,6 @@ fn a_scripts_commands_do_not_save_into_the_apps_libraries() { assert!(std::fs::read_dir(&user).map_or(true, |mut d| d.next().is_none()), "nothing is written in the user library folder"); s.execute("swatch.library.save", &json!({"user": true, "name": "Mine"})).unwrap(); assert_eq!(std::fs::read_dir(&user).unwrap().count(), 1); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -867,7 +853,6 @@ fn an_abandoned_run_reports_the_files_it_wrote() { let report = s.script_report().unwrap(); assert_eq!((report["kind"].as_str(), report["written"].clone()), (Some("stopped"), json!([p])), "{report}"); assert!(s.script_failure_text().unwrap().contains(&p)); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -1457,15 +1442,13 @@ fn a_file_saved_before_a_failure_stays_written_and_is_named() { assert!(e.contains(&p), "{e}"); assert_eq!(s.script_report().unwrap()["written"], json!([p])); assert_eq!(state(&s), before, "the document does not keep the new path"); - let _ = std::fs::remove_dir_all(&dir); } /// A run in the app's frames keeps the file-access scope its `script.run` came in, whatever scope /// the frames that advance it run in. #[test] fn a_framed_run_keeps_the_file_access_scope_it_started_in() { - let dir = std::env::temp_dir().join(format!("vc-script-scope-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); + let dir = fresh_folder("scope"); let (allowed, outside) = (dir.join("allowed"), dir.join("outside")); std::fs::create_dir_all(&allowed).unwrap(); std::fs::create_dir_all(&outside).unwrap(); @@ -1492,13 +1475,12 @@ fn a_framed_run_keeps_the_file_access_scope_it_started_in() { let r = crate::file_access::confine(Some(&roots), || finish(&mut s)).unwrap(); assert_eq!(r["log"], json!(["ok"]), "a run the person started is not confined by a later caller: {r}"); assert!(user_target.exists()); - let _ = std::fs::remove_dir_all(&dir); } #[test] fn a_committed_run_exports_what_it_drew() { - let path = std::env::temp_dir().join(format!("vc-script-export-{}.svg", std::process::id())); - let _ = std::fs::remove_file(&path); + let dir = fresh_folder("export"); + let path = dir.join("export.svg"); let p = path.to_string_lossy().into_owned(); let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); @@ -1509,7 +1491,6 @@ fn a_committed_run_exports_what_it_drew() { assert_eq!(svg.matches("