From 07c783410c969dfadc3f87c204a0ed9988f81d2f Mon Sep 17 00:00:00 2001 From: Ansho Rei Date: Mon, 24 Aug 2026 03:35:23 +0200 Subject: [PATCH] (b74dc5a) Remove a test's fixture directory with a guard, not a trailing line Every unit test here built its board under the system temp directory, and the ones that remembered a `remove_dir_all` at the end only cleaned up when their assertions passed. Most had no such line at all. /tmp reached 18363 of these and filled the disk, which failed a link step and then a `git add` with "No space left on device": an error naming neither the tests nor what they had left behind. `util::Fixture` is a uuid-named directory whose `Drop` removes it, which is the only shape that also runs when an assertion fails, since unwinding runs destructors. It derefs to `Path` and implements `AsRef`, because the two reach different call sites: a parameter typed `&Path` is a coercion site and one bound by `impl AsRef` is not. So nothing changed at the ~160 call sites but the type, and the 85 trailing cleanup lines are gone. Five leaking prefixes, not the two the ticket names. `worklane-project-*` from `project_tree` and `worklane-bare-*` never cleaned up at all, and the four `worklane-count/blocked/stray/stamps-*` sites in `util.rs` cleaned up only on the passing path. `Fixture::child` is what covers `project_tree`, which needs the fixture to point at the project and remove the directory above it. `assert_fs::TempDir` is a dev-dependency already and was still not the answer: it names its directories `.tmpXXXXXX`, which says nothing about whose they are for the one case that matters, the one left on disk on purpose. Wrapping it to add a prefix and a printed path is more code than the guard. `WORKLANE_KEEP_FIXTURES=1` keeps them and prints each path, opt-in rather than kept-automatically-on-failure: the assertions here carry the state they are about, so a path printed on every failure would be noise on almost all of them. Read once when a fixture is made rather than at drop time, so the answer cannot change mid-test, and `Fixture::swept()` turns it off for the three tests that are about the guard itself and must not be failed by a reader's environment. Verified against a clean temp dir rather than against /tmp, which still holds the historical leak: `TMPDIR=/tmp/scratch cargo test` leaves zero directories behind, with the variable set and unset, 383 green either way. Co-Authored-By: Claude Opus 5 (1M context) --- AGENTS.md | 4 + src/handlers.rs | 5 +- src/tui.rs | 205 ++++++------------------------------------------ src/util.rs | 193 +++++++++++++++++++++++++++++++++++++++++---- 4 files changed, 206 insertions(+), 201 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c7aaf0b..6208d0e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -45,6 +45,10 @@ and this file is for what someone changing worklane's own code needs. - Tests use `assert_cmd` and `assert_fs` for CLI testing - `setup_worklane()` creates temp `.worklane/` with all four status folders pre-created, plus `campaigns/` in `cmd_campaign.rs`, which is also where the on-demand creation is tested from a board without it - `create_ticket()` writes fully-formed markdown files directly (no `--` separator for positional args in test commands) +- **Every unit-test fixture directory goes through `util::Fixture`, and nothing calls `remove_dir_all` at the end of a test.** `Fixture::new(prefix)` makes a uuid-named directory under the system temp dir and its `Drop` removes it, which is the only shape that also runs when an assertion fails — a trailing line does not, and a failing test is exactly when a fixture is most likely to be stranded. That was b74dc5a: `/tmp` reached 18363 of these and filled the disk, failing a link step and then a `git add` with "No space left on device", an error naming neither the tests nor what they left behind +- **`Fixture` derefs to `Path` and also implements `AsRef`**, because the two reach different call sites: a parameter typed `&Path` is a coercion site and one bound by `impl AsRef` is not. `Fixture::child(name)` points the fixture at a directory inside itself while still removing the parent, which is the tree `project_tree` needs. The prefix earns its place on the one path that is ever left behind, which is why this is a small guard rather than `assert_fs::TempDir` — that names its directories `.tmpXXXXXX`, which says nothing about whose they are +- **`WORKLANE_KEEP_FIXTURES=1 cargo test` keeps the fixtures and prints each path.** Opt-in rather than kept-automatically-on-failure, because the assertions here carry the state they are about: a failing board test prints the rendered rows. The flag is read once when a fixture is made rather than at drop time, so the answer cannot change mid-test, and `Fixture::swept()` turns it off for the three tests that are about the guard itself and must not be failed by a reader's environment +- **Verify a claim about leaked fixtures against a clean temp dir, not against `/tmp`.** `TMPDIR=/tmp/scratch cargo test` then count what is left in it: `/tmp` still holds the historical leak, so counting there measures the past rather than the change - In `tui.rs`, `write_member_card` is `write_tagged_card` plus a Campaign field and `write_campaign` puts a campaign on disk, creating the campaigns directory as it goes — `board_dir()` deliberately does not, so every test that does not write one is also the test that a board with no campaigns draws. `picker_rows` cuts the picker's list out of the frame by its own geometry, for the reason `overlay_title_row` exists: a card carries the same campaign label, so a search over every row finds the board rather than the list - **`cargo clippy --all-targets` is clean. Keep it clean**, and do not silence a lint that is pointing at something real. The only two `allow`s in the tree sit on the `create_ticket` fixtures in `cmd_mv.rs` and `cmd_show.rs`, each carrying the reason and what would replace it - **`cargo fmt --check` is clean too, and `rustfmt.toml` is what makes that affordable.** rustfmt is the formatter here, run it. The config is four stable width settings and nothing else: diff --git a/src/handlers.rs b/src/handlers.rs index 15856a0..3e6d3f0 100644 --- a/src/handlers.rs +++ b/src/handlers.rs @@ -1766,8 +1766,7 @@ mod tests { /// will not share a microsecond, but it is the whole point of the guard. #[test] fn a_colliding_stem_takes_the_next_name_and_keeps_the_first() { - let dir = std::env::temp_dir().join(format!("worklane-test-{}", uuid::Uuid::new_v4())); - fs::create_dir_all(&dir).unwrap(); + let dir = Fixture::new("worklane-test"); let first = write_new_comment(&dir, "20260820_143012_123456", "first").unwrap(); let second = write_new_comment(&dir, "20260820_143012_123456", "second").unwrap(); @@ -1786,7 +1785,5 @@ mod tests { let mut names = vec![second.clone(), third.clone(), first.clone()]; names.sort(); assert_eq!(names, vec![first, second, third]); - - fs::remove_dir_all(&dir).unwrap(); } } diff --git a/src/tui.rs b/src/tui.rs index 3c8a2d7..76aa919 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -3300,10 +3300,17 @@ mod tests { /// A board on disk, since everything here is about reading a real tree. /// - /// The directory stands in for a `.worklane`, so its parent is the temp directory - /// and `project_name` reads the generated name off it. - fn board_dir() -> PathBuf { - let dir = std::env::temp_dir().join(format!("worklane-tui-{}", uuid::Uuid::new_v4())); + /// The directory stands in for a `.worklane` and holds the four status directories. + /// `board_dir()` deliberately does not create the campaigns directory beside them, so + /// every test that does not write one is also the test that a board with no campaigns + /// draws. + /// + /// A [`Fixture`], so it goes when the test that made it does, whether the test passed or + /// not. It used to be a `PathBuf` and a `remove_dir_all` at the end of the tests that + /// remembered one, which is b74dc5a: the line does not run when an assertion fails, and + /// most tests here never had it. + fn board_dir() -> Fixture { + let dir = Fixture::new("worklane-tui"); for status in status_dirs() { std::fs::create_dir_all(dir.join(status)).unwrap(); } @@ -4885,7 +4892,7 @@ mod tests { } /// A board with something to find in three columns, done included. - fn searchable() -> PathBuf { + fn searchable() -> Fixture { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "Alpha first", ""); write_ticket(&dir, "backlog", "22222222-0000-4000-8000-000000000000", "Beta second", ""); @@ -5402,10 +5409,11 @@ mod tests { /// A project tree: a directory holding a `.worklane`, which is what a path argument /// is resolved to. - fn project_tree(name: &str) -> PathBuf { - let root = std::env::temp_dir() - .join(format!("worklane-project-{}", uuid::Uuid::new_v4())) - .join(name); + /// The fixture points at the project and removes the directory above it, which is what + /// `Fixture::child` is for: the path a test hands to `projects` is the project, and the + /// generated name that has to be swept up is its parent. + fn project_tree(name: &str) -> Fixture { + let root = Fixture::new("worklane-project").child(name); for status in status_dirs() { std::fs::create_dir_all(root.join(".worklane").join(status)).unwrap(); } @@ -5441,7 +5449,8 @@ mod tests { fn several_paths_are_monitored_together() { let (alpha, beta) = (project_tree("alpha"), project_tree("beta")); - let found = projects(&[alpha, beta], &std::env::temp_dir()).unwrap(); + let found = + projects(&[alpha.to_path_buf(), beta.to_path_buf()], &std::env::temp_dir()).unwrap(); let names: Vec<&str> = found.iter().map(|p| p.name.as_str()).collect(); assert_eq!(names, ["alpha", "beta"]); } @@ -5451,10 +5460,10 @@ mod tests { #[test] fn a_path_with_no_board_fails_naming_that_path() { let alpha = project_tree("alpha"); - let bare = std::env::temp_dir().join(format!("worklane-bare-{}", uuid::Uuid::new_v4())); - std::fs::create_dir_all(&bare).unwrap(); + let bare = Fixture::new("worklane-bare"); - let error = projects(&[alpha, bare.clone()], &std::env::temp_dir()).unwrap_err(); + let error = projects(&[alpha.to_path_buf(), bare.to_path_buf()], &std::env::temp_dir()) + .unwrap_err(); let printed = format!("{error:#}"); assert!( @@ -5473,7 +5482,7 @@ mod tests { let deep = root.join("src"); std::fs::create_dir_all(&deep).unwrap(); - let found = projects(&[root, deep], &std::env::temp_dir()).unwrap(); + let found = projects(&[root.to_path_buf(), deep], &std::env::temp_dir()).unwrap(); assert_eq!(found.len(), 1, "the same board was monitored twice"); } @@ -6013,7 +6022,7 @@ mod tests { /// The section goes where `relate` writes it, ahead of the metadata, rather than in /// `write_ticket`'s trailer: the block has to be on screen for a test to read the /// colour off the drawn buffer. - fn related_board() -> PathBuf { + fn related_board() -> Fixture { let dir = board_dir(); let holder = "11111111-0000-4000-8000-000000000000"; let target = "22222222-0000-4000-8000-000000000000"; @@ -6387,8 +6396,6 @@ mod tests { let title = overlay_title_row(&screen, SCREEN.width, SCREEN.height); assert!(title.contains("A long one"), "{title}"); assert!(!title.contains("pg "), "the indicator landed on the title row:\n{title}"); - - std::fs::remove_dir_all(&dir).ok(); } /// At the top of a scrollable ticket, page one. @@ -6401,7 +6408,6 @@ mod tests { let row = overlay_bottom_row(&screen, SCREEN.width, SCREEN.height); assert!(row.contains("pg 1/"), "{row}"); - std::fs::remove_dir_all(&dir).ok(); } /// The one the arithmetic is for: the clamp stops at the wrapped height less the @@ -6431,8 +6437,6 @@ mod tests { .to_string(); let (page, total) = indicator.split_once('/').expect("no separator"); assert_eq!(page, total, "the last page reads as the second to last: {indicator}"); - - std::fs::remove_dir_all(&dir).ok(); } /// A ticket that fits spends no indicator, the way an untagged card spends no row on @@ -6463,8 +6467,6 @@ mod tests { "a ticket that fits drew an indicator:\n{}", screen.join("\n") ); - - std::fs::remove_dir_all(&dir).ok(); } /// The wrapped count and the viewport both move with the terminal, so the total has @@ -6489,8 +6491,6 @@ mod tests { let wide = total(120, 40); let narrow = total(60, 20); assert_ne!(wide, narrow, "the same total on two terminal sizes"); - - std::fs::remove_dir_all(&dir).ok(); } /// An overlay too narrow for the indicator drops it whole rather than cutting it, the @@ -6562,8 +6562,6 @@ mod tests { Some(Color::Orange.into()), "the indicator took the title's colour" ); - - std::fs::remove_dir_all(&dir).ok(); } // ------------------------------------------------------------- campaigns -- @@ -6810,8 +6808,6 @@ mod tests { let rows = only_card(&dir, 120, 20); assert_eq!(rows.len(), 5, "the label row is missing: {rows:?}"); assert_eq!(rows[2], "~v1 #cli #tui", "the campaign is not on the row: {rows:?}"); - - std::fs::remove_dir_all(&dir).ok(); } /// The mark is not `#`, because the two sit on one row and the row would otherwise @@ -6833,8 +6829,6 @@ mod tests { let rows = only_card(&dir, 120, 20); assert_eq!(rows[2], format!("~{}", short_id(V1)), "{rows:?}"); - - std::fs::remove_dir_all(&dir).ok(); } /// A ticket in no campaign renders exactly as it did before campaigns reached the @@ -6848,8 +6842,6 @@ mod tests { let rows = only_card(&dir, 120, 20); assert_eq!(rows.len(), 4, "a row was spent on nothing: {rows:?}"); assert!(!rows.iter().any(|row| row.contains(CAMPAIGN_MARK)), "{rows:?}"); - - std::fs::remove_dir_all(&dir).ok(); } /// A campaign the board does not hold marks nothing, the answer `mark_blocked` gives @@ -6863,8 +6855,6 @@ mod tests { let rows = only_card(&dir, 120, 20); assert_eq!(rows.len(), 4, "{rows:?}"); assert!(!rows.iter().any(|row| row.contains("_missing_")), "{rows:?}"); - - std::fs::remove_dir_all(&dir).ok(); } /// The campaign takes the row first and the tags give way, the order a corner and a @@ -6882,8 +6872,6 @@ mod tests { let fits = only_card_at(&dir, 25); assert_eq!(fits[2], "~v1 #frontend #operations", "{fits:?}"); - - std::fs::remove_dir_all(&dir).ok(); } /// And a campaign the row will not hold goes whole, never cut: half a codename is a @@ -6899,8 +6887,6 @@ mod tests { let fits = only_card_at(&dir, 7); assert_eq!(fits[2], "~beaver", "{fits:?}"); - - std::fs::remove_dir_all(&dir).ok(); } /// The colour groups a campaign across the cards that carry it, from the same pure @@ -6926,8 +6912,6 @@ mod tests { "the campaign does not jump out: {:?}", label.style ); - - std::fs::remove_dir_all(&dir).ok(); } /// A campaign with no codename is drawn in grey rather than in the red a uuid takes @@ -6959,8 +6943,6 @@ mod tests { "a card was labelled" ); assert!(headings(&board, 100, 24).contains("backlog (1)"), "the board did not draw"); - - std::fs::remove_dir_all(&dir).ok(); } /// Selecting a campaign turns the four columns into that campaign's members grouped @@ -6984,8 +6966,6 @@ mod tests { assert_eq!(titles, vec!["In v1".to_string(), "Also in v1".to_string()], "{titles:?}"); // Every column is kept, empty ones included: a campaign's shape is the flow. assert_eq!(board.current().columns.len(), status_dirs().len()); - - std::fs::remove_dir_all(&dir).ok(); } /// The frame says which campaign the columns belong to, and how far it has got, from @@ -7016,8 +6996,6 @@ mod tests { assert!(rows[bottom].contains("[open]"), "no derived state: {:?}", rows[bottom]); // The way out, on the border of the thing it undoes. assert!(rows[bottom].contains("q board"), "no way out named: {:?}", rows[bottom]); - - std::fs::remove_dir_all(&dir).ok(); } /// The standing counts done whether the column is drawn or not: hiding done is a @@ -7047,8 +7025,6 @@ mod tests { assert!(!board.show_done, "done is hidden at startup"); let standing = board.campaign().expect("no campaign selected").standing; assert_eq!((standing.done, standing.total), (1, 2)); - - std::fs::remove_dir_all(&dir).ok(); } /// The frame takes its three rows off the columns rather than off the footer, and @@ -7070,8 +7046,6 @@ mod tests { plain.height - Chrome::CAMPAIGN_ROWS, "the frame took its rows from somewhere else" ); - - std::fs::remove_dir_all(&dir).ok(); } // ------------------------------------------------------- the frame's own prose -- @@ -7141,8 +7115,6 @@ mod tests { let wanted = format!("Line {:03}", at + 1); assert!(drawn.contains(&wanted), "no {wanted} on the frame: {drawn:?}"); } - - std::fs::remove_dir_all(&dir).ok(); } /// Up past the top card reaches the frame, and down comes back to the column it was @@ -7171,8 +7143,6 @@ mod tests { assert_eq!(board.current().focus, Focus::Cards, "down did not leave the frame"); assert_eq!(board.current().column, 1, "down landed in a different column"); assert_eq!(selected_title(&board).as_deref(), Some("Also in v1")); - - std::fs::remove_dir_all(&dir).ok(); } /// An empty column reaches it too. A column with no card to stand on must not be a @@ -7194,8 +7164,6 @@ mod tests { board.select_card(1, SCREEN); assert_eq!(board.current().column, 2, "down landed somewhere else"); - - std::fs::remove_dir_all(&dir).ok(); } /// The two keys the overlay reads a ticket with read the frame's description, clamped @@ -7222,8 +7190,6 @@ mod tests { board.scroll_page(-40, SCREEN); assert_eq!(board.current().frame_offset, 0, "the scroll ran off the top"); - - std::fs::remove_dir_all(&dir).ok(); } /// And only while it holds the selection. On the cards the keys are what they were @@ -7236,8 +7202,6 @@ mod tests { board.scroll_page(1, SCREEN); assert_eq!(board.current().frame_offset, 0, "the frame scrolled from the cards"); - - std::fs::remove_dir_all(&dir).ok(); } /// An open ticket keeps both keys whatever holds the selection behind it. It is the @@ -7272,8 +7236,6 @@ mod tests { assert!(board.offset > 0, "the open ticket lost the scroll keys"); assert_eq!(board.current().frame_offset, 0, "the frame took them from under it"); - - std::fs::remove_dir_all(&dir).ok(); } /// And the frame is out of reach from under an open ticket. Up and down step through @@ -7290,8 +7252,6 @@ mod tests { board.select_card(-1, SCREEN); assert_eq!(board.current().focus, Focus::Cards, "the frame took the selection"); assert!(board.detail.is_some(), "the overlay closed on an arrow key"); - - std::fs::remove_dir_all(&dir).ok(); } /// The frame says there is more of it than fits, in the words the overlay says it in: @@ -7319,8 +7279,6 @@ mod tests { second.contains("pg 2/"), "the indicator did not follow the scroll: {second:?}" ); - - std::fs::remove_dir_all(&dir).ok(); } /// A description that fits leaves the frame selectable and the keys inert. Making the @@ -7344,8 +7302,6 @@ mod tests { !bottom.contains("pg "), "an indicator over a description that fits: {bottom:?}" ); - - std::fs::remove_dir_all(&dir).ok(); } /// A campaign with no description is reachable and spends its rows on the placeholder. @@ -7374,8 +7330,6 @@ mod tests { board.select_card(-1, SCREEN); assert_eq!(board.current().focus, Focus::Frame, "an empty frame was unreachable"); - - std::fs::remove_dir_all(&dir).ok(); } /// The footer describes the keys that work where the selection is, which on the frame @@ -7398,8 +7352,6 @@ mod tests { ); // And the last slot still answers how to get out, which from here is `ctrl-c`. assert!(row.contains("ctrl-c quit"), "nothing says what quits from here:\n{row}"); - - std::fs::remove_dir_all(&dir).ok(); } /// No card is selected while the frame holds the selection, and none is drawn as if it @@ -7425,8 +7377,6 @@ mod tests { board.select_card(1, SCREEN); assert!(a_card_is_highlighted(&board, 120, 20), "the highlight did not come back"); - - std::fs::remove_dir_all(&dir).ok(); } /// `y` copies the id of what is selected in every state the selection can be in, and on @@ -7445,8 +7395,6 @@ mod tests { Some(short_id("11111111-0000-4000-8000-000000000000")), "back on the cards it is not the ticket's id" ); - - std::fs::remove_dir_all(&dir).ok(); } /// Left and right do nothing on the frame. It spans the width of the board, so there is @@ -7462,8 +7410,6 @@ mod tests { board.select_column(1, SCREEN); assert_eq!(board.current().focus, Focus::Frame, "a column key left the frame"); assert_eq!(board.current().column, 1, "a column key moved where down comes back to"); - - std::fs::remove_dir_all(&dir).ok(); } /// `q` gives the whole board back from the frame, as it does from the columns: the @@ -7485,8 +7431,6 @@ mod tests { let all: usize = board.current().columns.iter().map(|c| c.cards.len()).sum(); assert_eq!(all, 4, "the whole board did not come back"); - - std::fs::remove_dir_all(&dir).ok(); } /// A jump lands on a card, so it takes the selection off the frame: `/` reaching a @@ -7510,8 +7454,6 @@ mod tests { "the jump left the selection on the frame" ); assert_eq!(selected_title(&board).as_deref(), Some("Also in v1")); - - std::fs::remove_dir_all(&dir).ok(); } /// The offset is the tab's, beside the filter, since the filter is per tab: how far into @@ -7545,9 +7487,6 @@ mod tests { board.select_tab(-2, SCREEN); assert_eq!(board.current().frame_offset, at, "the tab did not keep its place"); assert_eq!(board.current().focus, Focus::Frame, "the tab did not keep its focus"); - - std::fs::remove_dir_all(&one).ok(); - std::fs::remove_dir_all(&two).ok(); } /// Changing the filter puts the frame back at the top, the answer `refresh_detail` @@ -7564,8 +7503,6 @@ mod tests { board.select_campaign(Some(BEAVER.to_string()), SCREEN); assert_eq!(board.current().frame_offset, 0, "the new campaign opened partway down"); assert_eq!(board.current().focus, Focus::Cards, "the selection stayed on the frame"); - - std::fs::remove_dir_all(&dir).ok(); } // ---------------------------------------------------- the frame's two heights -- @@ -7606,8 +7543,6 @@ mod tests { board.toggle_focused(SCREEN); assert!(!board.current().expanded, "the tab did not collapse"); assert_eq!(frame_height(&board, SCREEN), collapsed, "the rows did not come back"); - - std::fs::remove_dir_all(&dir).ok(); } /// And only from the frame. `enter` on a card is the overlay's, which is what the routing @@ -7623,8 +7558,6 @@ mod tests { board.toggle_focused(SCREEN); assert!(board.detail.is_none(), "enter did not close the ticket"); - - std::fs::remove_dir_all(&dir).ok(); } /// Half of what the frame and the columns divide, which is the screen less the tab row @@ -7644,8 +7577,6 @@ mod tests { let columns = board_area(SCREEN, board.chrome()).height; assert!(columns >= shared / 2, "the cards did not keep the odd row"); assert_eq!(frame_height(&board, SCREEN) + columns + FOOTER_ROWS, SCREEN.height); - - std::fs::remove_dir_all(&dir).ok(); } /// The share is bounded at both ends, and a sweep is what says so rather than one screen @@ -7720,8 +7651,6 @@ mod tests { rows[BOARD_ROW].height - 2, "the cards are laid out against a column of another height" ); - - std::fs::remove_dir_all(&dir).ok(); } /// The scroll keys go on doing what they do, and the indicator repages: the step and the @@ -7748,8 +7677,6 @@ mod tests { let text = frame_text_area(SCREEN, board.chrome()); let last = last_offset(&frame_prose(board.campaign().expect("no campaign")), text); assert_eq!(board.current().frame_offset, last, "the scroll ran past the description"); - - std::fs::remove_dir_all(&dir).ok(); } /// A description that did not fit the collapsed frame and does fit the expanded one @@ -7767,8 +7694,6 @@ mod tests { board.scroll_page(1, SCREEN); assert_eq!(board.current().frame_offset, 0, "prose that fits scrolled"); - - std::fs::remove_dir_all(&dir).ok(); } /// A description that fits the collapsed frame expands anyway. A key that worked on one @@ -7787,8 +7712,6 @@ mod tests { frame_height(&board, SCREEN) > Chrome::CAMPAIGN_ROWS, "the frame did not grow" ); - - std::fs::remove_dir_all(&dir).ok(); } /// `q` takes the campaign filter off from an expanded frame exactly as it does from a @@ -7809,8 +7732,6 @@ mod tests { let all: usize = board.current().columns.iter().map(|c| c.cards.len()).sum(); assert_eq!(all, 4, "the whole board did not come back"); - - std::fs::remove_dir_all(&dir).ok(); } /// Up and down leave the height where it was. The reader chose a view of the campaign; @@ -7830,8 +7751,6 @@ mod tests { board.select_card(-1, SCREEN); assert!(board.current().expanded, "up changed the height"); - - std::fs::remove_dir_all(&dir).ok(); } /// The footer says which of the two `enter` is about to do, since the key is a toggle and @@ -7850,8 +7769,6 @@ mod tests { let row = footer(&board, 120, 20); assert!(row.contains("enter collapse"), "enter still offered as expand:\n{row}"); assert!(!row.contains("enter expand"), "the row names it both ways:\n{row}"); - - std::fs::remove_dir_all(&dir).ok(); } /// Expanding and collapsing leave the reader where they were rather than at the top. The @@ -7877,8 +7794,6 @@ mod tests { board.toggle_focused(SCREEN); assert!(board.current().frame_offset > 0, "collapsing went back to the top"); - - std::fs::remove_dir_all(&dir).ok(); } /// The height is the tab's own, beside the filter it belongs to, so switching away and @@ -7908,9 +7823,6 @@ mod tests { board.select_tab(-2, SCREEN); assert!(board.current().expanded, "the tab did not keep its height"); - - std::fs::remove_dir_all(&one).ok(); - std::fs::remove_dir_all(&two).ok(); } /// And selecting another campaign opens its frame collapsed, the answer `select_campaign` @@ -7926,8 +7838,6 @@ mod tests { board.select_campaign(Some(BEAVER.to_string()), SCREEN); assert!(!board.current().expanded, "the new campaign opened at half the board"); assert_eq!(frame_height(&board, SCREEN), Chrome::CAMPAIGN_ROWS); - - std::fs::remove_dir_all(&dir).ok(); } /// A campaign that leaves the board takes the frame with it, focus and offset both: the @@ -7958,8 +7868,6 @@ mod tests { "the selection is on a frame nothing draws" ); assert_eq!(board.current().frame_offset, 0, "the offset outlived the description"); - - std::fs::remove_dir_all(&dir).ok(); } /// `q` takes off one layer at a time, in the order they were put on: the overlay, then @@ -7980,8 +7888,6 @@ mod tests { board.dismiss(SCREEN); assert!(board.should_quit, "nothing left to close and it did not quit"); - - std::fs::remove_dir_all(&dir).ok(); } /// And the overlay comes off before the campaign, so one press takes off one layer. @@ -7996,8 +7902,6 @@ mod tests { board.dismiss(SCREEN); assert!(board.detail.is_none(), "the overlay stayed open"); assert_eq!(board.current().campaign, Some(V1.to_string()), "the filter came off too"); - - std::fs::remove_dir_all(&dir).ok(); } /// Selecting a campaign closes an open ticket, the answer hiding the done column @@ -8012,8 +7916,6 @@ mod tests { board.select_campaign(Some(BEAVER.to_string()), SCREEN); assert!(board.detail.is_none(), "the overlay survived the filter"); - - std::fs::remove_dir_all(&dir).ok(); } /// The picker owns the keyboard while it is open, the rule the search prompt already @@ -8043,8 +7945,6 @@ mod tests { // reach the arm bound to `d`. board.picker_key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL), SCREEN); assert!(!board.show_done, "ctrl-d reached the done column"); - - std::fs::remove_dir_all(&dir).ok(); } /// `ctrl-c` is the one key it declines, because a terminal application always honours @@ -8058,8 +7958,6 @@ mod tests { assert!( !board.picker_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL), SCREEN) ); - - std::fs::remove_dir_all(&dir).ok(); } /// The point of the list: move to a campaign, press enter, look at it. @@ -8076,8 +7974,6 @@ mod tests { board.picker_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE), SCREEN); assert!(board.picker.is_none(), "the picker stayed open"); assert_eq!(board.current().campaign, Some(BEAVER.to_string())); - - std::fs::remove_dir_all(&dir).ok(); } /// Esc leaves the board exactly as it was, so opening the list is never a commitment. @@ -8092,8 +7988,6 @@ mod tests { assert!(board.picker.is_none(), "the picker stayed open"); assert_eq!(board.current().campaign, Some(V1.to_string()), "the filter moved"); - - std::fs::remove_dir_all(&dir).ok(); } /// It opens on the campaign already selected, so `c` on a filtered board says where @@ -8109,8 +8003,6 @@ mod tests { .picker_highlight() .expect("the highlight is on no campaign"); assert_eq!(highlighted.uuid, V1); - - std::fs::remove_dir_all(&dir).ok(); } /// A board with no campaigns says so in words rather than opening an empty box that @@ -8127,8 +8019,6 @@ mod tests { let notice = board.notice.as_ref().expect("nothing was said"); assert!(notice.text.contains("no campaigns"), "{:?}", notice.text); assert!(notice.failed, "a key that did nothing read as a key that worked"); - - std::fs::remove_dir_all(&dir).ok(); } /// The rows carry the three things a campaign is chosen by, and the description is the @@ -8150,8 +8040,6 @@ mod tests { // And the footer is the picker's while it is open, for the reason the prompt takes // it: the board's key list describes nothing that currently works. assert!(footer(&board, 100, 24).contains("enter view"), "the footer is the board's"); - - std::fs::remove_dir_all(&dir).ok(); } /// A campaign with no codename shows the id once, not twice: the row already opens @@ -8173,8 +8061,6 @@ mod tests { assert_eq!(row.matches(short_id(V1)).count(), 1, "the id is on the row twice: {row:?}"); assert!(!row.contains(CAMPAIGN_MARK), "a mark with nothing after it: {row:?}"); - - std::fs::remove_dir_all(&dir).ok(); } /// A campaign filed elsewhere has to reach the board, and the digest is what decides @@ -8196,8 +8082,6 @@ mod tests { write_campaign(&dir, V1, "First public release", "beaver", "For a public tag."); assert!(board.tick().unwrap(), "an edited campaign moved nothing"); assert_eq!(board.current().campaigns[0].codename.as_deref(), Some("beaver")); - - std::fs::remove_dir_all(&dir).ok(); } /// A selection whose campaign has left the board goes back to the whole board rather @@ -8215,8 +8099,6 @@ mod tests { assert_eq!(board.current().campaign, None, "the filter outlived its campaign"); let all: usize = board.current().columns.iter().map(|c| c.cards.len()).sum(); assert_eq!(all, 4, "the board stayed filtered to nothing"); - - std::fs::remove_dir_all(&dir).ok(); } /// One flat list ordered by title put the completed campaigns among the open ones @@ -8242,8 +8124,6 @@ mod tests { // A heading is chrome, and grey is what the guideline gives to what a reader skips. assert_eq!(picker_row_color(&board, open, 100, 24), Color::Grey.into()); - - std::fs::remove_dir_all(&dir).ok(); } /// `Standing::state` calls a campaign with no members neither open nor done. For the @@ -8276,8 +8156,6 @@ mod tests { row_with(&rows, short_id(BEAVER)) < row_at(&rows, COMPLETED_SECTION), "a campaign with no members listed as completed: {rows:?}" ); - - std::fs::remove_dir_all(&dir).ok(); } /// The completed tail is truncated to the couple most recently filed, and the line under @@ -8312,8 +8190,6 @@ mod tests { rows[hidden] ); assert_eq!(picker_row_color(&board, hidden, 100, 24), Color::Grey.into()); - - std::fs::remove_dir_all(&dir).ok(); } /// One campaign hidden is one campaign, since a line that misspells what it is counting @@ -8349,8 +8225,6 @@ mod tests { board.open_picker(); type_picker_query(&mut board, short_id(FINISHED[3].0)); assert_eq!(picked_ids(&board), vec![FINISHED[3].0.to_string()], "the id missed"); - - std::fs::remove_dir_all(&dir).ok(); } /// The summary is drawn on the row but is not what the row is chosen by: a query that @@ -8364,8 +8238,6 @@ mod tests { // Beaver's summary reads "Move the store off one disk." and its title does not. type_picker_query(&mut board, "disk"); assert_eq!(picked_ids(&board), vec![FINISHED[0].0.to_string()], "the summary matched"); - - std::fs::remove_dir_all(&dir).ok(); } /// A search reaches the whole completed tail, untruncated, which is the point of having @@ -8394,8 +8266,6 @@ mod tests { !rows.iter().any(|row| row.contains("older completed")), "the query left the truncation on: {rows:?}" ); - - std::fs::remove_dir_all(&dir).ok(); } /// While the query is open the picker still owns the keyboard, so `q` types rather than @@ -8422,8 +8292,6 @@ mod tests { press(&mut board, KeyCode::Esc); assert!(board.picker.is_none(), "the second esc left the picker open"); - - std::fs::remove_dir_all(&dir).ok(); } /// Enter takes the highlighted row whether a query is open or not: filtering is how the @@ -8444,8 +8312,6 @@ mod tests { press(&mut board, KeyCode::Enter); assert!(board.picker.is_none(), "the picker stayed open"); assert_eq!(board.current().campaign, Some(BEAVER.to_string())); - - std::fs::remove_dir_all(&dir).ok(); } /// A query that matches nothing keeps the picker and the query open, and says so in the @@ -8466,8 +8332,6 @@ mod tests { assert!(board.picker.is_some(), "enter on a miss closed the picker"); assert_eq!(query_of(&board).as_deref(), Some("zzz"), "the query was taken away"); assert_eq!(board.current().campaign, None, "a miss selected something"); - - std::fs::remove_dir_all(&dir).ok(); } /// Section headings and the truncation line take no number: they are not campaigns, so @@ -8509,8 +8373,6 @@ mod tests { } back.reverse(); assert_eq!(back, walked[..3], "the walk back is not the walk out"); - - std::fs::remove_dir_all(&dir).ok(); } /// The highlight follows the campaign it was on rather than the number it was at: a @@ -8532,8 +8394,6 @@ mod tests { // And back to the whole list, still on it. press(&mut board, KeyCode::Esc); assert_eq!(highlighted(&board).as_deref(), Some(V1), "clearing the query lost it"); - - std::fs::remove_dir_all(&dir).ok(); } /// A query that excludes the highlighted campaign drops the highlight to the first row @@ -8547,8 +8407,6 @@ mod tests { type_picker_query(&mut board, "polish"); assert_eq!(highlighted(&board).as_deref(), Some(FINISHED[2].0)); - - std::fs::remove_dir_all(&dir).ok(); } /// The footer is the picker's while it is open, and the query's while that is open: with @@ -8566,8 +8424,6 @@ mod tests { assert!(row.contains("/beav"), "the query is not on the row: {row:?}"); assert!(row.contains("esc clear"), "the row does not say what esc does: {row:?}"); assert!(!row.contains("/ search"), "the row names a key that types: {row:?}"); - - std::fs::remove_dir_all(&dir).ok(); } /// The bare count is what the box is. A query that cuts the list down makes the total @@ -8586,8 +8442,6 @@ mod tests { type_picker_query(&mut board, "migration"); assert_eq!(title(&board), " campaigns (2 of 6) "); - - std::fs::remove_dir_all(&dir).ok(); } /// The standing on every row is settled at reload, off the cards the reload already @@ -8614,8 +8468,6 @@ mod tests { rows.iter().any(|row| row.contains(short_id(FINISHED[3].0))), "a completed campaign left the section: {rows:?}" ); - - std::fs::remove_dir_all(&dir).ok(); } /// Paired with the test above, which would pass by never asking the filesystem again: @@ -8646,8 +8498,6 @@ mod tests { let v1 = campaigns.iter().find(|row| row.uuid == V1).expect("no v1"); assert_eq!((v1.standing.done, v1.standing.total), (1, 1), "the standing did not move"); assert!(v1.completed(), "a campaign whose every member is done stayed open"); - - std::fs::remove_dir_all(&dir).ok(); } /// The highlight survives a tick, on the campaign rather than on the number: one filed @@ -8669,8 +8519,6 @@ mod tests { Some(V1), "the highlight held its row rather than its campaign" ); - - std::fs::remove_dir_all(&dir).ok(); } /// The key is named where a reader has to find it, and left out where the frame's own @@ -8686,8 +8534,6 @@ mod tests { let footer = footer(&board, 120, 24); assert!(footer.contains("ctrl-c quit"), "q still claims to quit: {footer:?}"); assert!(!footer.contains("q quit"), "{footer:?}"); - - std::fs::remove_dir_all(&dir).ok(); } /// The filter belongs to the tab, not the board: a campaign is resolved inside one @@ -8721,8 +8567,5 @@ mod tests { // And the tab it was set on kept it. board.select_tab(-1, SCREEN); assert_eq!(board.current().campaign, Some(V1.to_string())); - - std::fs::remove_dir_all(&one).ok(); - std::fs::remove_dir_all(&two).ok(); } } diff --git a/src/util.rs b/src/util.rs index 86052b1..6f21746 100644 --- a/src/util.rs +++ b/src/util.rs @@ -3077,10 +3077,183 @@ pub fn by_status_order(status: Status, a: &TicketItem, b: &TicketItem) -> std::c by_stamp.then_with(|| by_priority_then_title(a, b)) } +/// The environment variable that keeps a test's fixture directory on disk. +/// +/// Opt-in rather than on-by-default-when-a-test-fails, because the assertions in this crate +/// carry the state they are about: a failing board test prints the rendered rows, a failing +/// listing test prints the listing. The path is what you want when you would rather poke at +/// the files than read the message, which is the less common of the two. +#[cfg(test)] +pub const KEEP_FIXTURES: &str = "WORKLANE_KEEP_FIXTURES"; + +/// A fixture directory under the system temp directory that removes itself. +/// +/// Every unit test in this crate builds its board or its status directory by hand under +/// `std::env::temp_dir()`. The ones that remembered a `remove_dir_all` at the end of the +/// test only cleaned up when their assertions passed, and most had no such line at all, so +/// a full run left one directory per test behind. `/tmp` reached 18363 of them and filled +/// the disk, which failed a link step and then a `git add` with "No space left on device" — +/// an error that names neither the tests nor what they left behind. That is b74dc5a. +/// +/// A `Drop` rather than a line at the end of each test, because that is the only shape that +/// runs when an assertion fails, which is exactly when a fixture is most likely to be +/// stranded: unwinding runs destructors, so the guard holds on the failing path without the +/// test having to say anything. +/// +/// `assert_fs::TempDir` is a dev-dependency already and is what the integration tests use, +/// and it was still not the answer here. It names its directories `.tmpXXXXXX`, which says +/// nothing about whose they are for the one case that matters — the one left on disk on +/// purpose — and it has no opinion about naming the path when it keeps one. Wrapping it to +/// add both is more code than this. +/// +/// `Deref` to `Path`, so a fixture reads as the path it stands for at the call sites that +/// already had one and nothing had to change but the type. +#[cfg(test)] +pub struct Fixture { + /// What is removed: the directory this fixture created at the top. + root: std::path::PathBuf, + /// What the test works with, at or below the root. The two differ only for a fixture + /// that needs a named directory inside a parent it can also throw away. + path: std::path::PathBuf, + /// Whether to leave the directory behind, read once here rather than at drop time. + /// + /// At construction because the answer must not be able to change between a test + /// starting and ending, and because it is what [`Fixture::swept`] can then turn off for + /// the tests that are about the guard rather than about this flag. + keep: bool, +} + +#[cfg(test)] +impl Fixture { + /// A fresh directory, named after the family of tests that asked for it. + /// + /// The prefix earns its place on the kept path: `worklane-tui-` says which suite left it + /// where a random name would not, and the uuid is what makes two fixtures with one + /// prefix two directories, so no test can reach another's. + pub fn new(prefix: &str) -> Self { + let root = std::env::temp_dir().join(format!("{prefix}-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&root).unwrap(); + + Fixture { + path: root.clone(), + root, + keep: std::env::var_os(KEEP_FIXTURES).is_some(), + } + } + + /// The same fixture, swept up whatever the environment says. + /// + /// For the tests below, which assert that the directory goes: they are about the guard + /// and not about the flag, so `WORKLANE_KEEP_FIXTURES` in a reader's environment must + /// not be able to fail them. + pub fn swept(mut self) -> Self { + self.keep = false; + self + } + + /// The same fixture, pointing at a directory inside it. + /// + /// For the tree a project test needs: `//.worklane`, where the path the + /// test hands to `projects` is the project and what has to be removed is the root above + /// it. Consuming, so one directory never has two guards and therefore never two attempts + /// to remove it. + pub fn child(mut self, name: &str) -> Self { + self.path = self.root.join(name); + self + } +} + +#[cfg(test)] +impl AsRef for Fixture { + fn as_ref(&self) -> &std::path::Path { + &self.path + } +} + +/// Beside `AsRef`, because the two reach different call sites: a parameter bound by +/// `impl AsRef` is not a coercion site, and a parameter typed `&Path` is. +#[cfg(test)] +impl std::ops::Deref for Fixture { + type Target = std::path::Path; + + fn deref(&self) -> &std::path::Path { + &self.path + } +} + +#[cfg(test)] +impl Drop for Fixture { + fn drop(&mut self) { + if self.keep { + // Named, since a fixture kept and not findable is a fixture kept for nothing. + eprintln!("kept fixture {}", self.root.display()); + return; + } + + // Best effort. A directory that will not go must not turn a passing test into a + // failing one, and must not panic a second time out of a drop that is already + // unwinding, which would lose the failure the test was reporting. + std::fs::remove_dir_all(&self.root).ok(); + } +} + #[cfg(test)] mod tests { use super::*; + /// The guard removes the directory when it goes out of scope, which is what makes the + /// cleanup independent of the assertions passing: unwinding runs destructors, so a + /// failing test drops its fixture on the way out exactly as a passing one does. + #[test] + fn a_fixture_removes_itself_when_its_guard_goes() { + let path = { + let dir = Fixture::new("worklane-guard").swept(); + fs::write(dir.join("a.md"), "body").unwrap(); + assert!(dir.exists(), "the fixture was not created"); + dir.to_path_buf() + }; + + assert!(!path.exists(), "the fixture outlived its guard: {}", path.display()); + } + + /// And on the failing path, which is the whole point: a line at the end of a test does + /// not run when an assertion above it does not pass. + #[test] + fn a_fixture_removes_itself_when_the_test_panics() { + // The default hook would print this deliberate panic and make a green run read as a + // red one. Swapped for the length of the call and put straight back, which is as + // narrow as a process-wide hook can be made. + let hook = std::panic::take_hook(); + std::panic::set_hook(Box::new(|_| {})); + let caught = std::panic::catch_unwind(|| { + let dir = Fixture::new("worklane-guard").swept(); + // Handed out through the payload, so the assertion below has a path to look at + // whether or not the guard did its job. + std::panic::panic_any(dir.to_path_buf()); + }); + std::panic::set_hook(hook); + + let path = *caught + .expect_err("the closure did not panic") + .downcast::() + .expect("the panic did not carry the fixture path"); + + assert!(!path.exists(), "the fixture survived a failing test: {}", path.display()); + } + + /// Two fixtures with one prefix are two directories, so no test can rely on one another + /// test built — which the shared temp directory is what made possible. + #[test] + fn two_fixtures_with_one_prefix_are_two_directories() { + let first = Fixture::new("worklane-guard"); + let second = Fixture::new("worklane-guard"); + assert_ne!(first.to_path_buf(), second.to_path_buf(), "one directory, two guards"); + + let kept = second.to_path_buf(); + drop(first); + assert!(kept.exists(), "one fixture going took the other with it"); + } + #[test] fn no_color_disables_colour_on_a_terminal() { assert!(!colors_wanted(true, Some("1"), Some("xterm-256color"))); @@ -3454,8 +3627,7 @@ mod tests { /// in `show`, so the two cannot disagree about what a criterion is. #[test] fn collect_ticket_items_counts_the_criteria_show_would_number() { - let dir = std::env::temp_dir().join(format!("worklane-count-{}", uuid::Uuid::new_v4())); - fs::create_dir_all(&dir).unwrap(); + let dir = Fixture::new("worklane-count"); let write = |name: &str, body: &str| { fs::write( @@ -3480,8 +3652,6 @@ mod tests { counted.contains(&None), "a ticket with no criteria got a count: {counted:?}" ); - - fs::remove_dir_all(&dir).unwrap(); } /// The count is a directory listing rather than a read: nothing here parses a comment, @@ -3537,8 +3707,7 @@ mod tests { /// listing that stops on one malformed ticket is the worse failure. #[test] fn collect_ticket_items_reads_the_uuid_and_the_blockers_it_records() { - let dir = std::env::temp_dir().join(format!("worklane-blocked-{}", uuid::Uuid::new_v4())); - fs::create_dir_all(&dir).unwrap(); + let dir = Fixture::new("worklane-blocked"); let uuid = |tail: &str| format!("11111111-0000-4000-8000-00000000000{tail}"); let write = |name: &str, relations: &str| { @@ -3563,8 +3732,6 @@ mod tests { assert_eq!(of("T1").blockers, vec![uuid("2")]); assert!(of("T2").blockers.is_empty(), "a regression was read as a blocker"); assert!(of("T3").blockers.is_empty(), "an unreadable section was not survived"); - - fs::remove_dir_all(&dir).unwrap(); } /// Whole values, so a filter or a card cannot confuse two tags that share a prefix. @@ -3591,8 +3758,7 @@ mod tests { #[test] fn collect_ticket_items_lists_only_md_files() { - let dir = std::env::temp_dir().join(format!("worklane-stray-{}", uuid::Uuid::new_v4())); - fs::create_dir_all(&dir).unwrap(); + let dir = Fixture::new("worklane-stray"); fs::write( dir.join("11111111-0000-4000-8000-000000000001.md"), @@ -3608,8 +3774,6 @@ mod tests { let titles: Vec<&str> = items.iter().map(|item| item.title.as_str()).collect(); assert_eq!(titles, vec!["Real"], "{titles:?}"); - - fs::remove_dir_all(&dir).unwrap(); } /// The template ticket, and the shape every insertion test measures against. @@ -3927,8 +4091,7 @@ mod tests { /// comparison time, which is what makes an ordered column cost one read per file. #[test] fn collect_ticket_items_reads_the_stamps_the_order_sorts_on() { - let dir = std::env::temp_dir().join(format!("worklane-stamps-{}", uuid::Uuid::new_v4())); - fs::create_dir_all(&dir).unwrap(); + let dir = Fixture::new("worklane-stamps"); fs::write( dir.join("aaaa_walked.md"), @@ -3959,8 +4122,6 @@ mod tests { assert_eq!(fresh.committed_on, None); assert_eq!(fresh.submitted_on, None); assert_eq!(fresh.completed_on, None); - - fs::remove_dir_all(&dir).unwrap(); } /// Removal is scoped to the section for the same reason the write is: a description