use super::*;
#[test]
fn popup_gradient_tracks_black_theme() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.theme = crate::theme::Theme::BLACK;
assert!(app.popup_gradient());
app.theme = crate::theme::Theme::DARK_BLUE;
assert!(!app.popup_gradient());
}
#[test]
fn black_theme_context_menu_uses_gradient_border_and_muted_selection() {
use crate::gradient::{GRAD_TL, POPUP_SEL_BG, rgb_color};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.theme = crate::theme::Theme::BLACK;
app.context_menu = Some(ContextMenu::flat(
(10, 10),
vec![
(
String::from("New File"),
MenuAction::Create(CreateKind::File),
),
(
String::from("New Folder"),
MenuAction::Create(CreateKind::Folder),
),
],
tmp.path().to_path_buf(),
));
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer();
assert_eq!(buf[(10, 10)].fg, rgb_color(GRAD_TL));
assert_eq!(buf[(11, 11)].bg, rgb_color(POPUP_SEL_BG));
}
#[test]
fn croft_loch_context_menu_is_a_card_with_keycaps_and_a_selected_bar() {
use crate::widgets::surface;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.theme = crate::theme::Theme::from_id("loch");
let t = crate::theme::tones(app.theme).unwrap();
let mut menu = ContextMenu::flat(
(10, 10),
vec![
(
String::from("New File"),
MenuAction::Create(CreateKind::File),
),
(
String::from("New Folder"),
MenuAction::Create(CreateKind::Folder),
),
],
tmp.path().to_path_buf(),
);
menu.items.insert(1, MenuEntry::Separator);
app.context_menu = Some(menu);
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer();
let r = app.menu_rect().unwrap();
assert_eq!(buf[(r.x, r.y + 1)].symbol(), surface::ROW_BAR);
assert_eq!(buf[(r.x, r.y + 1)].fg, t.accent());
assert_eq!(buf[(r.x + 2, r.y + 1)].bg, t.band());
for x in r.x..r.right() {
assert_eq!(buf[(x, r.y + 2)].symbol(), "\u{2500}", "({x}) on the rule");
}
let hint = menu_hint(&MenuAction::Create(CreateKind::Folder), &app.keymap).unwrap();
let caps: u16 = surface::keycap_spans(&hint, t, t.raised(), false)
.iter()
.map(|s| s.width() as u16)
.sum();
assert!(r.width >= "New Folder".len() as u16 + caps + 4, "{r:?}");
let cap_bg = t.keycap_on(t.raised());
assert!((r.x..r.right()).any(|x| buf[(x, r.y + 3)].bg == cap_bg));
assert_eq!(
buf[(r.right() - 1, r.y + 3)].symbol(),
"\u{2595}",
"rim kept"
);
}
#[test]
fn black_theme_status_bar_is_near_black_not_navy() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.theme = crate::theme::Theme::BLACK;
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer();
let last_y = buf.area.height - 1;
let near_black = Color::Rgb(0x18, 0x18, 0x18);
let navy = Color::Rgb(0x1e, 0x3a, 0x6e);
assert!(
(0..buf.area.width).any(|x| buf[(x, last_y)].bg == near_black),
"status bar should paint the near-black seam under the Black theme"
);
assert!(
!(0..buf.area.width).any(|x| buf[(x, last_y)].bg == navy),
"status bar must not keep the legacy navy under the Black theme"
);
}
#[test]
fn paint_gradient_box_skips_when_rect_runs_off_buffer() {
let buf_area = Rect {
x: 0,
y: 0,
width: 80,
height: 25,
};
let mut buf = ratatui::buffer::Buffer::empty(buf_area);
let oversized = Rect {
x: 0,
y: 0,
width: 80,
height: 60,
};
paint_gradient_box(&mut buf, oversized);
let off_top_left = Rect {
x: 0,
y: 0,
width: 80,
height: 25,
};
paint_gradient_box(&mut buf, off_top_left);
assert_eq!(buf[(0, 0)].symbol(), "\u{256d}");
}
#[test]
fn the_gradient_box_comes_in_two_weights() {
use ratatui::buffer::Buffer;
let area = ratatui::layout::Rect {
x: 0,
y: 0,
width: 8,
height: 4,
};
let sym = |b: &Buffer, x: u16, y: u16| b[(x, y)].symbol().to_string();
let mut light = Buffer::empty(area);
crate::gradient::paint_gradient_box(&mut light, area);
let mut heavy = Buffer::empty(area);
crate::gradient::paint_gradient_box_heavy(&mut heavy, area);
for (x, y, what) in [(3u16, 0u16, "top"), (3, 3, "bottom")] {
assert_eq!(sym(&light, x, y), "\u{2500}", "light {what} edge");
assert_eq!(sym(&heavy, x, y), "\u{2501}", "heavy {what} edge");
}
for (x, y, what) in [(0u16, 1u16, "left"), (7, 1, "right")] {
assert_eq!(sym(&light, x, y), "\u{2502}", "light {what} edge");
assert_eq!(sym(&heavy, x, y), "\u{2503}", "heavy {what} edge");
}
for (x, y) in [(0, 0), (7, 0), (0, 3), (7, 3)] {
assert_eq!(
sym(&light, x, y),
sym(&heavy, x, y),
"corner ({x},{y}) is the same arc in both weights"
);
}
}
#[test]
fn paint_gradient_box_draws_rounded_corners_with_corner_colours() {
let rect = Rect {
x: 0,
y: 0,
width: 8,
height: 4,
};
let mut buf = ratatui::buffer::Buffer::empty(rect);
paint_gradient_box(&mut buf, rect);
assert_eq!(buf[(0, 0)].symbol(), "\u{256d}", "top-left rounded");
assert_eq!(buf[(7, 0)].symbol(), "\u{256e}", "top-right rounded");
assert_eq!(buf[(0, 3)].symbol(), "\u{2570}", "bottom-left rounded");
assert_eq!(buf[(7, 3)].symbol(), "\u{256f}", "bottom-right rounded");
assert_eq!(buf[(3, 0)].symbol(), "\u{2500}", "top edge horizontal");
assert_eq!(buf[(0, 1)].symbol(), "\u{2502}", "left edge vertical");
let tl_fg = buf[(0, 0)].fg;
assert_eq!(tl_fg, rgb_color(GRAD_TL));
let tr_fg = buf[(7, 0)].fg;
assert_eq!(tr_fg, rgb_color(GRAD_TR));
}
#[test]
fn set_session_bg_srgb_seq_uses_iterm_osc1337_and_srgb_prefix() {
let seq = set_session_bg_srgb_seq(crate::theme::Theme::DARK_BLUE.editor_bg_rgb());
assert_eq!(seq, "\x1b]1337;SetColors=bg=srgb:1e222e\x07");
}
#[test]
fn opening_a_config_file_keeps_the_active_tabs_unsaved_edits() {
let tmp = tempfile::tempdir().unwrap();
let a = tmp.path().join("a.txt");
std::fs::write(&a, "saved\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&a).unwrap();
app.editor.lines = vec![String::from("unsaved")];
app.editor.dirty = true;
let layer = tmp.path().join(".croft").join("config.json");
std::fs::create_dir_all(layer.parent().unwrap()).unwrap();
app.open_config_file_in_editor(layer.clone(), ConfigFileSeed::SettingsLayer);
assert_eq!(app.editor.path.as_deref(), Some(layer.as_path()));
let kept = app
.editor
.editors
.iter()
.find(|e| e.path.as_deref() == Some(a.as_path()))
.expect("a.txt still has its tab");
assert!(kept.dirty);
assert_eq!(kept.lines, vec![String::from("unsaved")]);
}
#[test]
fn open_settings_json_seeds_a_config_with_no_settings() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let path = tmp.path().join("user").join("config.json");
app.open_config_file_in_editor(path.clone(), ConfigFileSeed::Settings);
assert_eq!(app.editor.path.as_deref(), Some(path.as_path()));
let written = std::fs::read_to_string(&path).unwrap();
let doc: serde_json::Value =
serde_json::from_str(&crate::jsonc::strip_jsonc(&written)).unwrap();
assert_eq!(doc, serde_json::json!({}), "{written}");
assert!(written.contains("docs/SETTINGS.md"), "{written}");
assert_eq!(
crate::prefs::Prefs::load(&path).unwrap(),
crate::prefs::Prefs::default()
);
}
#[test]
fn open_settings_json_leaves_an_existing_config_alone() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let path = tmp.path().join("config.json");
std::fs::write(&path, "{ \"vim_mode\": true }\n").unwrap();
app.open_config_file_in_editor(path.clone(), ConfigFileSeed::Settings);
assert_eq!(app.editor.path.as_deref(), Some(path.as_path()));
assert_eq!(
std::fs::read_to_string(&path).unwrap(),
"{ \"vim_mode\": true }\n"
);
}
#[test]
fn settings_gear_is_bottom_anchored_below_the_view_icons() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.overlays.activity.set_images(dummy_activity_images());
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let gear = app.sidebar_areas.activity_icons[ActivityIcon::Settings];
let run_debug = app.sidebar_areas.activity_icons[ActivityIcon::RunDebug];
assert!(gear.width > 0, "gear must lay out on a tall bar");
assert!(
gear.y > run_debug.y,
"the gear is anchored at the bottom, below the Run-and-Debug view icon"
);
assert_eq!(
app.pending_activity_image_overlays().len(),
12,
"seven view icons (CodeQL's is added, not built in) + the sponsor heart + the settings gear + the three layout toolbar icons emit"
);
}
#[test]
fn settings_gear_bottom_inset_matches_the_view_icon_top_inset() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.overlays.activity.set_images(dummy_activity_images());
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let explorer = app.sidebar_areas.activity_icons[ActivityIcon::Explorer];
let gear = app.sidebar_areas.activity_icons[ActivityIcon::Settings];
assert!(gear.width > 0, "gear must lay out on a tall bar");
let bar_bottom = app.last_frame_area.height - 1 - 1;
let top_inset = explorer.y - app.last_frame_area.y;
let bottom_inset = bar_bottom - (gear.y + gear.height - 1);
assert_eq!(
bottom_inset, top_inset,
"the gap below the gear must equal the gap above the first view icon"
);
}
#[test]
fn the_gear_clears_the_last_view_icon_shown() {
let bar = |height| Rect::new(0, 0, 3, height);
let shortest = |codeql| {
(1..80)
.find(|&h| activity_settings_block(bar(h), codeql).width > 0)
.expect("the gear fits on some bar")
};
assert_eq!(
shortest(true) - shortest(false),
activity_view_y(bar(80), ActivityIcon::CodeQL.slot().unwrap())
- activity_view_y(bar(80), ActivityIcon::Testing.slot().unwrap()),
"one icon slot less without CodeQL"
);
}
#[test]
fn clicking_the_gear_opens_the_color_theme_menu_then_the_picker() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.overlays.activity.set_images(dummy_activity_images());
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let gear = app.sidebar_areas.activity_icons[ActivityIcon::Settings];
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(MouseButton::Left),
column: gear.x,
row: gear.y,
modifiers: KeyModifiers::NONE,
});
let menu = app.context_menu.as_ref().expect("gear opens a menu");
assert!(
matches!(
menu.items.as_slice(),
[
MenuEntry::Item {
action: MenuAction::OpenThemePicker,
..
},
MenuEntry::Item {
action: MenuAction::OpenCustomizeLayout,
..
}
]
),
"the gear menu holds Color Theme then Customize Layout"
);
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
let picker = app.context_menu.as_ref().expect("picker opens");
assert_eq!(picker.items.len(), crate::theme::Theme::all().len());
assert!(
picker
.items
.iter()
.all(|e| matches!(e.action(), Some(MenuAction::SetTheme(_)))),
"every picker row switches a theme"
);
}
#[test]
fn the_sponsor_heart_sits_directly_above_the_gear() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.overlays.activity.set_images(dummy_activity_images());
draw(&mut app, 120, 40);
let heart = app.sidebar_areas.activity_icons[ActivityIcon::Sponsor];
let gear = app.sidebar_areas.activity_icons[ActivityIcon::Settings];
assert!(heart.width > 0, "the heart lays out on a tall bar");
assert_eq!((heart.x, heart.width), (gear.x, gear.width));
assert_eq!(heart.y + heart.height, gear.y, "no gap above the gear");
assert_eq!(app.ui_tooltip_at(heart.x, heart.y), Some("Sponsor croft"));
}
#[test]
fn a_short_bar_drops_the_sponsor_heart_before_the_gear() {
let bar = |height| Rect::new(0, 0, 3, height);
for codeql in [false, true] {
let shortest = (1..80)
.find(|&h| activity_settings_block(bar(h), codeql).width > 0)
.expect("the gear fits on some bar");
assert_eq!(activity_sponsor_block(bar(shortest), codeql).width, 0);
let taller = shortest + ACTIVITY_ICON_HEIGHT - 1;
assert_eq!(activity_sponsor_block(bar(taller), codeql).width, 0);
assert!(activity_sponsor_block(bar(taller + 1), codeql).width > 0);
}
}
#[test]
fn clicking_the_sponsor_heart_opens_the_github_sponsors_page() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.overlays.activity.set_images(dummy_activity_images());
draw(&mut app, 120, 40);
let view = app.sidebar_view;
let heart = app.sidebar_areas.activity_icons[ActivityIcon::Sponsor];
left_click(&mut app, heart.x, heart.y);
assert_eq!(app.status, "Open https://github.com/sponsors/vitali87");
assert!(app.context_menu.is_none(), "the heart opens no menu");
assert_eq!(app.sidebar_view, view);
assert!(app.show_tree, "the side bar stays open");
}
#[test]
fn sponsor_croft_is_a_palette_command() {
use crate::widgets::command_palette::Command;
assert_eq!(
Command::from_id("help_sponsor_croft"),
Some(Command::SponsorCroft)
);
assert_eq!(Command::SponsorCroft.title(), "Help: Sponsor croft");
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.run_command(Command::SponsorCroft);
assert_eq!(app.status, "Open https://github.com/sponsors/vitali87");
}
#[test]
fn applying_a_theme_switches_the_active_theme_and_arms_a_repaint() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert_eq!(
app.theme,
crate::theme::Theme::LOCH,
"fresh install defaults to Croft Loch"
);
app.apply_theme(crate::theme::Theme::DARK_BLUE);
assert_eq!(app.theme, crate::theme::Theme::DARK_BLUE);
assert!(app.consume_activity_image_clear());
}
#[test]
fn host_dynamic_colors_follow_the_theme() {
let light = crate::theme::Theme::from_id("light");
let seq = super::host_colors_seq(light);
assert!(
seq.contains("\x1b]11;rgb:ff/ff/ff"),
"light background must reach the host via OSC 11"
);
assert!(
seq.contains("\x1b]10;rgb:3b/3b/3b"),
"light foreground must reach the host via OSC 10"
);
let black = super::host_colors_seq(crate::theme::Theme::BLACK);
assert!(black.contains("\x1b]11;rgb:00/00/00"));
assert!(
String::from_utf8_lossy(super::TERMINAL_RESTORE_SEQ).contains("\x1b]110\x07\x1b]111\x07"),
"the panic/exit restore must reset the host's own colors"
);
}
#[test]
fn the_settings_picker_has_a_vim_mode_row() {
let (mut app, _t) = vim_app("abc");
app.vim.enabled = false;
app.open_settings_view();
let picker = app.list_picker.as_mut().expect("settings open");
let row = picker
.rows
.iter()
.position(|r| r.label.starts_with("Editor: Vim Mode: off"))
.expect("a Vim Mode row");
picker.selected = row;
app.confirm_list_picker();
assert!(app.vim.enabled, "{}", app.status);
}
#[test]
fn the_settings_picker_has_a_multi_cursor_persist_row() {
let (mut app, _t) = vim_app("abc");
app.vim.enabled = false;
app.multi_cursor_persist = false;
app.open_settings_view();
let picker = app.list_picker.as_mut().expect("settings open");
let row = picker
.rows
.iter()
.position(|r| r.label.starts_with("Editor: Multi-Cursor Persistence: off"))
.expect("a Multi-Cursor Persistence row");
picker.selected = row;
app.confirm_list_picker();
assert!(app.multi_cursor_persist, "{}", app.status);
}
#[test]
fn a_settings_reload_keeps_the_current_vim_mode() {
let (mut app, _t) = vim_app("abc");
app.vim.enabled = false;
let on = crate::prefs::Prefs {
vim_mode: true,
..Default::default()
};
app.apply_merged_settings(&on);
type_char(&mut app, 'i');
assert_eq!(app.vim.mode(), crate::vim::VimMode::Insert);
app.apply_merged_settings(&on);
assert!(app.vim.enabled);
assert_eq!(app.vim.mode(), crate::vim::VimMode::Insert);
}
fn app_excluding_vscode_build() -> (App, tempfile::TempDir) {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
for dir in [".vscode", "build", "scripts/build", "src"] {
std::fs::create_dir_all(root.join(dir)).unwrap();
}
std::fs::write(
root.join(".vscode/settings.json"),
r#"{ "files.exclude": { "build": true } }"#,
)
.unwrap();
std::fs::write(root.join("build/out.js"), "release_step()\n").unwrap();
std::fs::write(
root.join("scripts/build/release.py"),
"def release_step(): ...\n",
)
.unwrap();
std::fs::write(root.join("src/main.py"), "release_step()\n").unwrap();
let app = App::new(root.to_path_buf()).unwrap();
(app, tmp)
}
#[test]
fn a_vscode_exclude_of_build_keeps_scripts_build_in_search() {
let (mut app, t) = app_excluding_vscode_build();
assert_eq!(
search_hit_paths(&mut app, t.path(), "release_step"),
vec![
String::from("scripts/build/release.py"),
String::from("src/main.py")
]
);
}
#[test]
fn a_vscode_exclude_of_a_bare_name_keeps_nested_folders_in_go_to_file() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
for dir in [".vscode", "gen", "scripts/gen"] {
std::fs::create_dir_all(root.join(dir)).unwrap();
}
std::fs::write(
root.join(".vscode/settings.json"),
r#"{ "files.exclude": { "gen": true } }"#,
)
.unwrap();
std::fs::write(root.join("gen/out.py"), "\n").unwrap();
std::fs::write(root.join("scripts/gen/release.py"), "\n").unwrap();
let mut app = App::new(root.to_path_buf()).unwrap();
app.open_file_finder();
let rels: Vec<String> = app
.file_finder
.as_ref()
.unwrap()
.entries
.iter()
.map(|e| e.rel.clone())
.collect();
assert!(
rels.contains(&String::from("scripts/gen/release.py")),
"{rels:?}"
);
assert!(!rels.iter().any(|r| r.starts_with("gen/")), "{rels:?}");
}
#[test]
fn a_vscode_exclude_of_build_keeps_scripts_build_in_the_explorer() {
let (mut app, t) = app_excluding_vscode_build();
let release = t.path().join("scripts/build/release.py");
assert!(
app.tree.reveal_path(&release),
"scripts/build/release.py is listed"
);
let listed: Vec<_> = app.tree.nodes.iter().map(|n| n.path.clone()).collect();
assert!(
listed.contains(&t.path().join("scripts/build")),
"{listed:?}"
);
assert!(!listed.contains(&t.path().join("build")), "{listed:?}");
}
fn terminal_header_probe(app: &mut App) -> Rect {
draw(app, 140, 50);
let area = app.terminal().last_area;
assert!(
area.width > 20 && area.height > 2,
"terminal pane must render"
);
app.panel_hits.add_buttons[0]
}
#[test]
fn black_theme_terminal_buttons_are_teal_icons_not_navy_chips() {
use crate::gradient::{INNER_ACCENT, rgb_color};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.apply_theme(crate::theme::Theme::BLACK);
let add = terminal_header_probe(&mut app);
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer();
let plus = (add.x + 1, add.y);
assert_eq!(buf[plus].symbol(), "+");
assert_eq!(buf[plus].fg, rgb_color(INNER_ACCENT));
assert_ne!(
buf[plus].bg,
Color::Rgb(0x1e, 0x3a, 0x6e),
"Black theme must not paint the navy chip behind the + button"
);
}
#[test]
fn black_theme_terminal_button_hover_paints_teal_pill() {
use crate::gradient::{POPUP_SEL_BG, rgb_color};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.apply_theme(crate::theme::Theme::BLACK);
let add = terminal_header_probe(&mut app);
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Moved,
column: add.x + 1,
row: add.y,
modifiers: KeyModifiers::NONE,
});
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer();
let plus = (add.x + 1, add.y);
assert_eq!(
buf[plus].bg,
rgb_color(POPUP_SEL_BG),
"hovered button wears the teal pill"
);
assert_eq!(buf[plus].fg, Color::White);
}
#[test]
fn croft_loch_terminal_buttons_are_muted_until_hovered() {
let t = crate::theme::tones(crate::theme::Theme::LOCH).unwrap();
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let add = terminal_header_probe(&mut app);
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let plus = (add.x + 1, add.y);
assert_eq!(
term.backend().buffer()[plus].fg,
t.muted(),
"idle: muted, not the accent"
);
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Moved,
column: add.x + 1,
row: add.y,
modifiers: KeyModifiers::NONE,
});
term.draw(|f| app.render(f)).unwrap();
let cell = &term.backend().buffer()[plus];
assert_eq!(cell.fg, t.strong(), "hover lifts the icon");
assert_eq!(cell.bg, t.hover_on(t.chrome), "onto a faint chip");
}
#[test]
fn dark_blue_theme_terminal_button_keeps_navy_chip() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.theme = crate::theme::Theme::DARK_BLUE;
app.sync_focus_flags();
let add = terminal_header_probe(&mut app);
let backend = ratatui::backend::TestBackend::new(140, 50);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer();
let navy = Color::Rgb(0x1e, 0x3a, 0x6e);
assert_eq!(buf[(add.x + 1, add.y)].bg, navy);
}
#[test]
fn black_theme_paints_no_legacy_navy_or_button_blue_in_any_sidebar_view() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("probe.txt");
std::fs::write(&f, "alpha\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
let navy = Color::Rgb(0x1e, 0x3a, 0x6e);
let button_blue = Color::Rgb(0x09, 0x67, 0xb8);
for view in [
SidebarView::Explorer,
SidebarView::Search,
SidebarView::SourceControl,
SidebarView::Remote,
SidebarView::RunDebug,
] {
app.sidebar_view = view;
let buf = draw_buffer(&mut app, 140, 50);
assert_eq!(
count_bg(&buf, navy),
0,
"legacy navy chip leaked into {view:?} under the Black theme"
);
assert_eq!(
count_bg(&buf, button_blue),
0,
"legacy button blue leaked into {view:?} under the Black theme"
);
}
}
#[test]
fn black_theme_sidebar_titles_are_chipless_brand_headers() {
use crate::gradient::{PANEL_TITLE_FG, rgb_color};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.apply_theme(crate::theme::Theme::BLACK);
let buf = draw_buffer(&mut app, 140, 50);
let tree = app.tree.last_area;
assert_eq!(buf[(tree.x + 2, tree.y)].symbol(), "E");
assert_eq!(buf[(tree.x + 2, tree.y)].fg, rgb_color(PANEL_TITLE_FG));
app.sidebar_view = SidebarView::Remote;
let buf = draw_buffer(&mut app, 140, 50);
let remote = app.remote.last_area;
assert_eq!(buf[(remote.x + 2, remote.y)].symbol(), "R");
assert_eq!(buf[(remote.x + 2, remote.y)].fg, rgb_color(PANEL_TITLE_FG));
}
#[test]
fn croft_loch_side_bar_title_is_strong_only_while_focused() {
let t = crate::theme::tones(crate::theme::Theme::LOCH).unwrap();
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let buf = draw_buffer(&mut app, 140, 50);
let tree = app.tree.last_area;
let e = (tree.x + 2, tree.y);
assert_eq!(buf[e].symbol(), "E");
assert_eq!(buf[e].fg, t.strong(), "the focused view's title");
assert!(!buf[e].modifier.contains(Modifier::BOLD));
assert_eq!(buf[(tree.x + 10, tree.y)].symbol(), " ", "breathing room");
assert_eq!(buf[(tree.x + 11, tree.y)].symbol(), "\u{2594}", "the lip");
app.focus_pane(Pane::Editor);
let buf = draw_buffer(&mut app, 140, 50);
assert_eq!(buf[e].fg, t.muted(), "an unfocused view's title recedes");
}
#[test]
fn croft_loch_explorer_sections_are_divided_by_hairlines() {
let t = crate::theme::tones(crate::theme::Theme::LOCH).unwrap();
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("a.txt"), "x\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&tmp.path().join("a.txt")).unwrap();
if !app.explorer_views.is_visible(ExplorerView::Outline) {
app.toggle_explorer_view(ExplorerView::Outline);
}
let buf = draw_buffer(&mut app, 140, 50);
let tree = app.tree.last_area;
let outline = app.outline.last_area;
assert_eq!(outline.y, tree.bottom(), "the outline follows the tree");
let seam = (tree.x + 3, tree.bottom() - 1);
assert_eq!(buf[seam].symbol(), "\u{2581}", "a hairline under the tree");
assert_eq!(buf[seam].fg, t.hairline());
let chevron = (outline.x + 1, outline.y);
assert_eq!(
buf[chevron].symbol(),
crate::widgets::surface::CHEVRON_FOLDED.to_string()
);
assert_eq!(buf[chevron].fg, t.muted());
}
const CHROME_DE: &str = r#"{
"EXPLORER": "ERKUNDER",
"OUTLINE": "GLIEDERUNG",
"TIMELINE": "ZEITACHSE",
"SOURCE CONTROL": "QUELLCODEVERWALTUNG",
"PROBLEMS": "PROBLEME",
"OUTPUT": "AUSGABE",
"TERMINAL": "KONSOLE",
"Command Palette — Esc to close, ↑/↓ to navigate, Enter to run": "Befehlspalette — Esc schließt",
"UNSAVED CHANGES": "NICHT GESPEICHERT",
"This tab has unsaved changes:": "Dieser Tab ist nicht gespeichert:",
"DISCARD CHANGES?": "ÄNDERUNGEN VERWERFEN?",
"This will overwrite your local changes from HEAD.": "Lokale Änderungen werden überschrieben."
}"#;
fn screen_with_catalog(app: &mut App, catalog: &str) -> String {
app.apply_theme(crate::theme::Theme::BLACK);
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(140, 50)).unwrap();
crate::i18n::with_test_catalog(catalog, || term.draw(|f| app.render(f)).unwrap());
screen_text(&term)
}
#[test]
fn the_side_bar_and_panel_titles_come_from_the_catalog() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("a.txt"), "x\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&tmp.path().join("a.txt")).unwrap();
for view in [ExplorerView::Outline, ExplorerView::Timeline] {
if !app.explorer_views.is_visible(view) {
app.toggle_explorer_view(view);
}
}
let screen = screen_with_catalog(&mut app, CHROME_DE);
for want in [
" ERKUNDER ",
"GLIEDERUNG",
"ZEITACHSE",
" PROBLEME ",
" AUSGABE ",
" KONSOLE ",
] {
assert!(screen.contains(want), "{want:?} missing:\n{screen}");
}
for gone in [" EXPLORER ", " PROBLEMS ", " OUTPUT ", " TERMINAL "] {
assert!(!screen.contains(gone), "{gone:?} still drawn:\n{screen}");
}
}
#[test]
fn the_source_control_title_comes_from_the_catalog() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_view = SidebarView::SourceControl;
let screen = screen_with_catalog(&mut app, CHROME_DE);
assert!(screen.contains("QUELLCODEVERWALTUNG"), "{screen}");
assert!(!screen.contains("SOURCE CONTROL"), "{screen}");
}
#[test]
fn the_palette_title_comes_from_the_catalog() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_command_palette();
let screen = screen_with_catalog(&mut app, CHROME_DE);
assert!(
screen.contains(" Befehlspalette — Esc schließt "),
"{screen}"
);
assert!(
!screen.contains("Command Palette — Esc to close"),
"{screen}"
);
}
#[test]
fn the_unsaved_and_discard_prompts_come_from_the_catalog() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.py", "x = 1\n");
app.pending_unsaved = Some(UnsavedExit::CloseTab { idx: 0, path: None });
let screen = screen_with_catalog(&mut app, CHROME_DE);
assert!(screen.contains(" NICHT GESPEICHERT "), "{screen}");
assert!(
screen.contains("Dieser Tab ist nicht gespeichert:"),
"{screen}"
);
assert!(!screen.contains("UNSAVED CHANGES"), "{screen}");
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.pending_discard = Some(PendingDiscard {
root: std::path::PathBuf::new(),
rel_path: String::from("a.txt"),
untracked: false,
staged: false,
});
let screen = screen_with_catalog(&mut app, CHROME_DE);
assert!(screen.contains(" ÄNDERUNGEN VERWERFEN? "), "{screen}");
assert!(
screen.contains("Lokale Änderungen werden überschrieben."),
"{screen}"
);
assert!(!screen.contains("DISCARD CHANGES?"), "{screen}");
}
#[test]
fn a_translated_panel_tab_is_clickable_across_its_whole_label() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
screen_with_catalog(
&mut app,
r#"{"PROBLEMS": "問題", "OUTPUT": "AUSGABE-UND-PROTOKOLL"}"#,
);
let problems = app.panel_hits.problems_tab;
let output = app.panel_hits.output_tab;
assert_eq!(problems.width, 6, "' 問題 ' is six cells wide");
assert_eq!(output.x, problems.x + problems.width + 1);
assert_eq!(output.width, " AUSGABE-UND-PROTOKOLL ".len() as u16);
left_click(&mut app, output.x + output.width - 2, output.y);
assert_eq!(app.bottom_panel_tab, BottomPanelTab::Output);
}
#[test]
fn titles_without_a_catalog_entry_stay_english() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let screen = screen_with_catalog(&mut app, r#"{"Move Line Up": "Zeile nach oben"}"#);
for want in [" EXPLORER ", " PROBLEMS ", " OUTPUT ", " TERMINAL "] {
assert!(screen.contains(want), "{want:?} missing:\n{screen}");
}
assert_eq!(app.panel_hits.output_tab.width, " OUTPUT ".len() as u16);
}
#[test]
fn black_theme_remote_header_buttons_are_near_white_icons() {
use crate::gradient::{PANEL_TITLE_FG, rgb_color};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.apply_theme(crate::theme::Theme::BLACK);
app.sidebar_view = SidebarView::Remote;
let buf = draw_buffer(&mut app, 140, 50);
let add = app.remote.header_add_btn;
assert!(add.width > 0, "remote header add button must render");
assert_eq!(buf[(add.x, add.y)].fg, rgb_color(PANEL_TITLE_FG));
}
#[test]
fn croft_loch_side_bar_header_buttons_rest_muted() {
let t = crate::theme::tones(crate::theme::Theme::LOCH).unwrap();
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_view = SidebarView::Remote;
let buf = draw_buffer(&mut app, 140, 50);
let add = app.remote.header_add_btn;
assert!(add.width > 0, "remote header add button must render");
assert_eq!(buf[(add.x, add.y)].fg, t.muted());
assert!(!buf[(add.x, add.y)].modifier.contains(Modifier::BOLD));
}
#[test]
fn black_theme_active_editor_tab_wears_the_teal_selection_fill() {
use crate::gradient::{POPUP_SEL_BG, rgb_color};
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("probe.txt");
std::fs::write(&f, "alpha\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.apply_theme(crate::theme::Theme::BLACK);
app.editor.open_pinned(&f).unwrap();
let buf = draw_buffer(&mut app, 140, 50);
assert!(
count_bg(&buf, rgb_color(POPUP_SEL_BG)) > 0,
"active tab must wear the muted teal fill under the Black theme"
);
}
#[test]
fn black_theme_action_buttons_wear_the_brand_teal_fill() {
use crate::gradient::{PRIMARY_BTN_BG, rgb_color};
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.sidebar_view = SidebarView::SourceControl;
let buf = draw_buffer(&mut app, 140, 50);
let init = app.source_control.last_init_repo_button_area;
assert!(
init.width > 0,
"Initialize button must render outside a repo"
);
assert_eq!(
buf[(init.x + init.width / 2, init.y + init.height / 2)].bg,
rgb_color(PRIMARY_BTN_BG)
);
app.sidebar_view = SidebarView::RunDebug;
let buf = draw_buffer(&mut app, 140, 50);
let run = app.run_debug.last_button_area;
assert!(run.width > 0, "Run and Debug button must render");
assert_eq!(
buf[(run.x + run.width / 2, run.y + run.height / 2)].bg,
rgb_color(PRIMARY_BTN_BG)
);
}
#[test]
fn dark_blue_theme_keeps_the_legacy_blue_chrome() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("probe.py");
std::fs::write(&f, "alpha\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.theme = crate::theme::Theme::DARK_BLUE;
app.sync_focus_flags();
app.editor.open_pinned(&f).unwrap();
let buf = draw_buffer(&mut app, 140, 50);
let navy = Color::Rgb(0x1e, 0x3a, 0x6e);
let tree = app.tree.last_area;
assert_eq!(
buf[(tree.x + 2, tree.y)].bg,
navy,
"EXPLORER chip stays navy"
);
assert!(count_bg(&buf, navy) > 0, "active tab stays navy");
app.sidebar_view = SidebarView::RunDebug;
let buf = draw_buffer(&mut app, 140, 50);
let run = app.run_debug.last_button_area;
assert_eq!(
buf[(run.x + run.width / 2, run.y + run.height / 2)].bg,
Color::Rgb(0x09, 0x67, 0xb8),
"Run and Debug button stays VS Code blue under Croft Dark"
);
}
#[test]
fn per_language_editor_settings_follow_the_tab_s_language() {
use crate::widgets::editor::WhitespaceMode;
let (_tmp, app) = app_with_vscode_settings(
r#"{
"[python]": {
"editor.formatOnType": true,
"editor.autoClosingBrackets": "never",
"editor.renderWhitespace": "all",
"editor.inlayHints.enabled": "off"
}
}"#,
);
assert!(app.format_on_type_for("python"));
assert!(!app.format_on_type_for("c"));
assert!(!app.auto_close_pairs_for("python"));
assert!(app.auto_close_pairs_for("c"));
assert_eq!(app.whitespace_mode_for("python"), WhitespaceMode::All);
assert_eq!(app.whitespace_mode_for("c"), app.whitespace_mode);
assert!(!app.inlay_hints_enabled_for("python"));
assert!(app.inlay_hints_enabled_for("c"));
}
#[test]
fn the_active_editor_takes_its_language_s_settings() {
use crate::widgets::editor::WhitespaceMode;
let (tmp, mut app) = app_with_vscode_settings(
r#"{ "[python]": { "editor.autoClosingBrackets": "never", "editor.renderWhitespace": "all" } }"#,
);
let backend = ratatui::backend::TestBackend::new(100, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
app.editor.open(&tmp.path().join("m.py")).unwrap();
app.sync_blame();
term.draw(|frame| app.render(frame)).unwrap();
assert!(!app.editor.auto_close_pairs);
assert_eq!(app.editor.whitespace_mode, WhitespaceMode::All);
app.editor.open(&tmp.path().join("m.c")).unwrap();
app.sync_blame();
term.draw(|frame| app.render(frame)).unwrap();
assert!(app.editor.auto_close_pairs, "C keeps the global on");
assert_eq!(app.editor.whitespace_mode, app.whitespace_mode);
}
#[test]
fn a_language_block_applies_to_files_that_share_another_language_s_grammar() {
let (tmp, mut app) = app_with_vscode_settings(
r#"{
"[javascriptreact]": { "editor.formatOnSave": true },
"[jsonc]": { "editor.formatOnSave": true },
"[scss]": { "editor.formatOnSave": true }
}"#,
);
for name in ["a.jsx", "a.jsonc", "a.scss"] {
std::fs::write(tmp.path().join(name), "x\n").unwrap();
app.editor.open(&tmp.path().join(name)).unwrap();
assert!(
app.format_on_save_eligible(true),
"{name} takes its own block"
);
}
for name in ["a.js", "a.json", "a.css"] {
std::fs::write(tmp.path().join(name), "x\n").unwrap();
app.editor.open(&tmp.path().join(name)).unwrap();
assert!(
!app.format_on_save_eligible(true),
"{name} keeps the global"
);
}
}
#[test]
fn an_associated_template_opens_in_its_language_every_time() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
std::fs::write(
tmp.path().join(".croft/config.json"),
r#"{ "files_associations": { "*.tpl": "html" } }"#,
)
.unwrap();
let mut app = app_with_open_file(tmp.path(), "card.tpl", "<h1>{{ title }}</h1>\n");
assert_eq!(
app.editor.language(),
Some(crate::highlight::LangKind::Html)
);
assert_eq!(app.editor.language_label(), "HTML");
app.editor.close_active();
app.editor
.open_pinned(&tmp.path().join("card.tpl"))
.unwrap();
assert_eq!(
app.editor.language(),
Some(crate::highlight::LangKind::Html)
);
}
#[test]
fn a_new_association_relanguages_open_tabs_but_not_a_hand_picked_one() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.tpl", "<b>x</b>\n");
assert_eq!(app.editor.language(), None, "no association yet");
std::fs::write(tmp.path().join("b.tpl"), "<i>y</i>\n").unwrap();
app.editor.open_pinned(&tmp.path().join("b.tpl")).unwrap();
app.editor
.pick_language(Some(crate::highlight::LangKind::Xml));
let mut prefs = crate::prefs::Prefs::default();
prefs
.files_associations
.insert(String::from("*.tpl"), String::from("html"));
app.apply_file_associations(&prefs);
let langs: Vec<_> = app
.editor
.editors
.iter()
.map(|e| (e.path.clone().unwrap(), e.language()))
.collect();
assert!(
langs.contains(&(
tmp.path().join("a.tpl"),
Some(crate::highlight::LangKind::Html)
)),
"{langs:?}"
);
assert!(
langs.contains(&(
tmp.path().join("b.tpl"),
Some(crate::highlight::LangKind::Xml)
)),
"{langs:?}"
);
}
#[test]
fn a_hand_picked_language_matching_the_inferred_one_survives_an_association() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.tpl", "<b>x</b>\n");
assert_eq!(app.editor.language(), None);
app.dispatch_menu_action(MenuAction::SetLanguage(None), tmp.path().to_path_buf());
let mut prefs = crate::prefs::Prefs::default();
prefs
.files_associations
.insert(String::from("*.tpl"), String::from("html"));
app.apply_file_associations(&prefs);
assert_eq!(app.editor.language(), None, "Plain Text was picked by hand");
}
#[test]
fn an_association_change_reopens_the_file_on_its_new_server() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.rs", "fn main() {}\n");
let rs = app.editor.path.clone().unwrap();
std::fs::write(tmp.path().join("b.go"), "package b\n").unwrap();
let go = tmp.path().join("b.go");
app.lsp.last_seen.insert(rs.clone(), 3);
app.lsp.last_seen.insert(go.clone(), 4);
let mut prefs = crate::prefs::Prefs::default();
prefs
.files_associations
.insert(String::from("*.rs"), String::from("python"));
app.apply_file_associations(&prefs);
assert!(
!app.lsp.last_seen.contains_key(&rs),
"rerouted file is resent"
);
assert_eq!(app.lsp.last_seen.get(&go), Some(&4), "untouched file stays");
}
#[test]
fn associations_follow_workspace_folders_in_and_out() {
let tmp = tempfile::tempdir().unwrap();
let extra = tempfile::tempdir().unwrap();
let extra_root = extra.path().canonicalize().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "x\n");
let mut prefs = crate::prefs::Prefs::default();
prefs
.files_associations
.insert(String::from("*.tpl"), String::from("html"));
app.apply_file_associations(&prefs);
let card = extra_root.join("card.tpl");
assert_eq!(crate::highlight::associated_language_id(&card), None);
app.add_workspace_folder(extra_root.clone());
assert_eq!(
crate::highlight::associated_language_id(&card).as_deref(),
Some("html")
);
app.remove_workspace_folder(extra_root.clone());
assert_eq!(crate::highlight::associated_language_id(&card), None);
}
#[test]
fn without_an_association_files_keep_the_built_in_languages() {
let tmp = tempfile::tempdir().unwrap();
let app = app_with_open_file(tmp.path(), "card.tpl", "<h1>x</h1>\n");
assert_eq!(app.editor.language(), None);
let app = app_with_open_file(tmp.path(), "main.rs", "fn main() {}\n");
assert_eq!(
app.editor.language(),
Some(crate::highlight::LangKind::Rust)
);
}
#[test]
fn settings_view_toggle_flips_the_setting_and_stays_open() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let before = app.auto_close_pairs;
app.open_settings_view();
app.confirm_list_picker();
assert_eq!(
app.auto_close_pairs, !before,
"the toggle row flips the setting"
);
assert!(
app.list_picker.is_some(),
"a toggle keeps the settings hub open so more can be flipped"
);
}
#[test]
fn workspace_settings_layer_applies_at_startup_and_reloads_live() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
std::fs::write(
tmp.path().join(".croft/config.json"),
r#"{"format_on_save":true,"disable_indent_guides":true}"#,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(app.format_on_save, "committed workspace setting applies");
assert!(!app.indent_guides_enabled);
assert_eq!(
crate::config_layers::layer_of(&app.settings_provenance, "format_on_save"),
crate::config_layers::LayerKind::Workspace
);
std::fs::write(
tmp.path().join(".croft/config.json"),
r#"{"format_on_save":false,"disable_indent_guides":true}"#,
)
.unwrap();
let layer = crate::config_layers::workspace_config_path(tmp.path());
app.reload_config_for_path(&layer);
assert!(!app.format_on_save, "the edit applied without a restart");
assert!(app.status.contains("Settings reloaded"), "{}", app.status);
}
#[test]
fn settings_hub_shows_provenance_and_the_layer_rows() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
std::fs::write(
tmp.path().join(".croft/config.json"),
r#"{"format_on_save":true}"#,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_settings_view();
let rows = app.list_picker.as_ref().expect("hub open").rows.clone();
let fos = rows
.iter()
.find(|r| r.id == "toggle:format_on_save")
.unwrap();
assert!(
fos.label.contains("· workspace"),
"a workspace-won value says so: {}",
fos.label
);
for id in [
"cmd:open_settings_json",
"cmd:open_user_settings_local_json",
"cmd:open_workspace_settings_json",
"cmd:open_workspace_settings_local_json",
] {
assert!(rows.iter().any(|r| r.id == id), "missing hub row {id}");
}
}
#[test]
fn opening_workspace_local_settings_gitignores_it_first() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_workspace_settings(true);
let gi = std::fs::read_to_string(tmp.path().join(".croft/.gitignore")).unwrap();
assert!(gi.contains("config.local.json"), "{gi}");
let local = crate::config_layers::workspace_local_config_path(tmp.path());
assert_eq!(app.editor.path.as_deref(), Some(local.as_path()));
let seeded = std::fs::read_to_string(&local).unwrap();
assert!(seeded.contains("settings overlay"), "{seeded}");
}
#[test]
fn a_settings_reload_applies_format_on_type_live() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(!app.format_on_type, "off by default");
let p = crate::prefs::Prefs {
format_on_type: true,
..Default::default()
};
app.apply_merged_settings(&p);
assert!(app.format_on_type, "a reloaded merge turns it on");
app.apply_merged_settings(&crate::prefs::Prefs::default());
assert!(!app.format_on_type, "and back off");
}
#[test]
fn a_workspace_layer_setting_disable_log_highlight_applies_on_remerge() {
let _exclusive = crate::log_view::DEFAULT_HIGHLIGHT_TEST_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let before = crate::log_view::default_highlight();
let tmp = tempfile::tempdir().unwrap();
let layer = crate::config_layers::workspace_config_path(tmp.path());
std::fs::create_dir_all(layer.parent().unwrap()).unwrap();
std::fs::write(&layer, r#"{"disable_log_highlight": true}"#).unwrap();
let log = tmp.path().join("build.log");
std::fs::write(&log, b"\x1b[32mok\x1b[0m 2024-01-02 step 1\nplain step 2\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(!app.log_highlight, "the workspace layer is read at startup");
app.editor.open_pinned(&log).unwrap();
assert!(
app.editor.log.is_some(),
"a coloured .log opens as a rendered log"
);
app.editor.log.as_mut().unwrap().set_highlight(true);
let other = tmp.path().join("other.log");
std::fs::write(&other, b"\x1b[31merr\x1b[0m 2024-01-02 step 9\n").unwrap();
app.split_editor();
app.editor.open_pinned(&other).unwrap();
assert!(app.editor.log.is_some());
app.editor.log.as_mut().unwrap().set_highlight(true);
fn parked_log_flags(app: &mut App) -> Vec<bool> {
app.editor_layout
.inactive_groups_mut()
.flat_map(|g| g.editors.iter())
.filter_map(|e| e.log.as_ref().map(|l| l.highlight()))
.collect()
}
std::fs::write(&layer, r#"{"disable_log_highlight": false}"#).unwrap();
app.reload_config_for_path(&layer);
assert!(
app.log_highlight,
"the remerge applied the workspace layer's new value"
);
assert!(
app.editor.log.as_ref().unwrap().highlight(),
"and pushed it into the open log view"
);
let parked = parked_log_flags(&mut app);
assert!(
!parked.is_empty() && parked.iter().all(|&h| h),
"and into the log parked in the other split group: {parked:?}"
);
assert!(
crate::log_view::default_highlight(),
"and into the default for later logs"
);
std::fs::write(&layer, r#"{"disable_log_highlight": true}"#).unwrap();
app.reload_config_for_path(&layer);
assert!(!app.log_highlight);
assert!(
!app.editor.log.as_ref().unwrap().highlight(),
"the opt-out reaches the open view"
);
assert!(
parked_log_flags(&mut app).iter().all(|&h| !h),
"and the parked one"
);
crate::log_view::set_default_highlight(before);
}
#[test]
fn the_offer_switches_apply_on_a_settings_remerge() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.remote_offer_refused.clear();
let pane = app.terminals[0].uid();
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(app.ssh_offer.is_some());
let mut prefs = crate::prefs::Prefs {
disable_remote_offer: true,
remote_offer_excluded_hosts: vec![String::from("jump")],
..Default::default()
};
app.apply_merged_settings(&prefs);
assert!(app.remote_offer_disabled && app.remote_offer_excluded == vec![String::from("jump")]);
assert!(
app.ssh_offer.is_none(),
"the live offer went down with the switch"
);
prefs.disable_remote_offer = false;
app.apply_merged_settings(&prefs);
assert!(!app.remote_offer_disabled);
app.consider_ssh_offer(pane, None);
app.consider_ssh_offer(pane, Some(String::from("db-1")));
assert!(app.ssh_offer.is_some());
prefs.remote_offer_excluded_hosts = vec![String::from("db-1")];
app.apply_merged_settings(&prefs);
assert!(
app.ssh_offer.is_none(),
"the newly excluded host's offer went down"
);
}
fn tick_after(app: &mut App, t0: std::time::Instant, n: u32) -> bool {
app.tick_config_watch_at(t0 + crate::config_sync::ConfigWatch::INTERVAL * n)
}
#[test]
fn a_workspace_settings_file_written_outside_croft_applies_live() {
use crate::widgets::editor::WhitespaceMode;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
assert_eq!(app.whitespace_mode, WhitespaceMode::Selection);
let t0 = std::time::Instant::now();
std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
std::fs::write(
tmp.path().join(".croft/config.json"),
r#"{ "render_whitespace": "all" }"#,
)
.unwrap();
assert!(tick_after(&mut app, t0, 2));
assert_eq!(app.whitespace_mode, WhitespaceMode::All);
assert_eq!(app.editor.whitespace_mode, WhitespaceMode::All);
assert_eq!(app.status, "Settings reloaded");
assert!(!tick_after(&mut app, t0, 4), "applied once");
}
#[test]
fn an_extends_target_written_outside_croft_applies_live() {
use crate::widgets::editor::WhitespaceMode;
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
std::fs::write(
tmp.path().join(".croft/config.json"),
r#"{ "extends": "team.json" }"#,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let t0 = std::time::Instant::now();
std::fs::write(
tmp.path().join(".croft/team.json"),
r#"{ "render_whitespace": "none" }"#,
)
.unwrap();
assert!(tick_after(&mut app, t0, 2));
assert_eq!(app.whitespace_mode, WhitespaceMode::None);
assert_eq!(app.status, "Settings reloaded");
}
#[test]
fn a_settings_file_saved_in_croft_reloads_once() {
use crate::widgets::editor::WhitespaceMode;
let tmp = tempfile::tempdir().unwrap();
let layer = crate::config_layers::workspace_config_path(tmp.path());
std::fs::create_dir_all(layer.parent().unwrap()).unwrap();
std::fs::write(&layer, "{}\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let t0 = std::time::Instant::now();
app.editor.open(&layer).unwrap();
app.editor.cursor_row = 0;
app.editor.cursor_col = 1;
app.editor.insert_str(r#" "render_whitespace": "all" "#);
app.save();
assert_eq!(app.whitespace_mode, WhitespaceMode::All);
assert_eq!(app.status, "Settings reloaded");
app.status = String::from("after the save");
assert!(!tick_after(&mut app, t0, 2), "the save already applied it");
assert_eq!(app.status, "after the save");
}
#[test]
fn a_settings_editor_write_is_not_reloaded_again_by_the_watch() {
use crate::widgets::editor::WhitespaceMode;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let t0 = std::time::Instant::now();
app.open_settings_editor();
app.settings_editor.as_mut().unwrap().target = crate::config_layers::LayerKind::Workspace;
app.write_setting("render_whitespace", serde_json::json!("all"));
assert_eq!(app.whitespace_mode, WhitespaceMode::All);
let saved = app.status.clone();
assert!(saved.starts_with("render_whitespace saved to"), "{saved}");
assert!(!tick_after(&mut app, t0, 2));
assert_eq!(app.status, saved);
}
#[test]
fn the_settings_editor_writes_a_commented_layer_file_and_keeps_its_comments() {
use crate::widgets::editor::WhitespaceMode;
let tmp = tempfile::tempdir().unwrap();
let file = crate::config_layers::workspace_config_path(tmp.path());
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
std::fs::write(&file, crate::app::settings::SETTINGS_TEMPLATE).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.open_settings_editor();
app.settings_editor.as_mut().unwrap().target = crate::config_layers::LayerKind::Workspace;
app.write_setting("render_whitespace", serde_json::json!("all"));
assert!(
app.status.starts_with("render_whitespace saved to"),
"{}",
app.status
);
assert_eq!(app.whitespace_mode, WhitespaceMode::All);
let text = std::fs::read_to_string(&file).unwrap();
assert!(text.contains("// Your croft settings"), "{text}");
app.reset_setting("render_whitespace");
assert!(
app.status.starts_with("render_whitespace reset in"),
"{}",
app.status
);
let text = std::fs::read_to_string(&file).unwrap();
assert!(text.contains("// Your croft settings"), "{text}");
assert!(!text.contains("render_whitespace"), "{text}");
}
#[test]
fn a_profile_keeps_the_config_folders_local_layer() {
let tmp = tempfile::tempdir().unwrap();
let config = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.config_dir = config.path().to_path_buf();
app.settings_profile = Some(String::from("work"));
std::fs::create_dir_all(config.path().join("profiles").join("work")).unwrap();
std::fs::write(
config.path().join("config.local.json"),
r#"{ "format_on_save": true }"#,
)
.unwrap();
let merged = app.merged_settings_here();
assert!(merged.prefs.format_on_save, "the local layer is in force");
assert_eq!(
crate::config_layers::layer_of(&merged.provenance, "format_on_save"),
crate::config_layers::LayerKind::UserLocal
);
assert!(
merged
.chain
.contains(&config.path().join("config.local.json")),
"the watch follows it: {:?}",
merged.chain
);
}
#[test]
fn a_settings_editor_reset_is_not_reloaded_again_by_the_watch() {
use crate::widgets::editor::WhitespaceMode;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let t0 = std::time::Instant::now();
app.open_settings_editor();
app.settings_editor.as_mut().unwrap().target = crate::config_layers::LayerKind::Workspace;
app.write_setting("render_whitespace", serde_json::json!("all"));
assert_eq!(app.whitespace_mode, WhitespaceMode::All);
app.reset_setting("render_whitespace");
let reset = app.status.clone();
assert!(reset.starts_with("render_whitespace reset in"), "{reset}");
assert!(!tick_after(&mut app, t0, 2), "the reset already applied it");
assert_eq!(app.status, reset);
}
#[test]
fn an_outside_extends_a_reset_carried_along_is_still_followed() {
use crate::widgets::editor::WhitespaceMode;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let t0 = std::time::Instant::now();
app.open_settings_editor();
app.settings_editor.as_mut().unwrap().target = crate::config_layers::LayerKind::Workspace;
app.write_setting("render_whitespace", serde_json::json!("all"));
let layer = crate::config_layers::workspace_config_path(tmp.path());
std::fs::write(
&layer,
r#"{ "extends": "team.json", "render_whitespace": "all" }"#,
)
.unwrap();
app.reset_setting("render_whitespace");
assert_eq!(app.whitespace_mode, WhitespaceMode::Selection);
assert!(tick_after(&mut app, t0, 2), "the outside edit is applied");
std::fs::write(
tmp.path().join(".croft/team.json"),
r#"{ "render_whitespace": "none" }"#,
)
.unwrap();
assert!(tick_after(&mut app, t0, 4), "team.json is watched now");
assert_eq!(app.whitespace_mode, WhitespaceMode::None);
}
#[test]
fn a_config_file_croft_creates_to_open_is_not_reloaded_by_the_watch() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let t0 = std::time::Instant::now();
let layer = crate::config_layers::workspace_config_path(tmp.path());
assert!(!layer.exists());
app.open_config_file_in_editor(layer.clone(), ConfigFileSeed::SettingsLayer);
assert!(layer.exists());
let opened = app.status.clone();
assert!(!tick_after(&mut app, t0, 2), "croft wrote it itself");
assert_eq!(app.status, opened);
}
#[test]
fn after_a_re_root_only_the_new_roots_settings_are_watched() {
use crate::widgets::editor::WhitespaceMode;
let old = tempfile::tempdir().unwrap();
let new = tempfile::tempdir().unwrap();
for root in [old.path(), new.path()] {
std::fs::create_dir_all(root.join(".croft")).unwrap();
}
let mut app = App::new(old.path().to_path_buf()).unwrap();
app.change_workspace_root(new.path().to_path_buf());
let old_layer = crate::config_layers::workspace_config_path(old.path());
let new_layer = crate::config_layers::workspace_config_path(new.path());
assert!(app.config_watch.watches(&new_layer));
assert!(!app.config_watch.watches(&old_layer));
let t0 = std::time::Instant::now();
std::fs::write(&old_layer, r#"{ "render_whitespace": "all" }"#).unwrap();
assert!(!tick_after(&mut app, t0, 2), "the old root is not watched");
assert_eq!(app.whitespace_mode, WhitespaceMode::Selection);
std::fs::write(&new_layer, r#"{ "render_whitespace": "all" }"#).unwrap();
assert!(tick_after(&mut app, t0, 4));
assert_eq!(app.whitespace_mode, WhitespaceMode::All);
}
#[test]
fn the_config_watch_covers_every_settings_layer_and_only_those() {
let tmp = tempfile::tempdir().unwrap();
let app = App::new(tmp.path().to_path_buf()).unwrap();
for layer in &app.settings_chain {
assert!(app.config_watch.watches(layer), "{}", layer.display());
}
assert!(app.config_watch.watches(&crate::keymap::keybindings_path()));
assert!(
app.config_watch
.watches(&crate::config_layers::synced_config_path())
);
assert!(!app.config_watch.watches(&tmp.path().join("notes.json")));
assert!(
!app.config_watch
.watches(&tmp.path().join(".croft/tasks.json"))
);
}
#[test]
fn sync_config_now_runs_the_cli_in_a_pane_for_a_plain_host_only() {
use crate::widgets::command_palette::Command;
assert_eq!(
Command::from_id("remote_sync_config_now"),
Some(Command::RemoteSyncConfigNow)
);
assert_eq!(
Command::RemoteSyncConfigNow.title(),
"Remote: Sync Config Now"
);
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
for bad in ["dev box", "x;rm -rf ~", "-oProxyCommand=x", ""] {
app.sync_config_to(bad);
assert!(
app.status.contains("not an ssh host alias"),
"{bad:?}: {}",
app.status
);
}
app.sync_config_to("user@dev-box.lan");
assert_eq!(app.status, "Syncing config to user@dev-box.lan");
}
#[test]
fn the_synced_settings_layer_is_in_the_reload_chain() {
let tmp = tempfile::tempdir().unwrap();
let app = App::new(tmp.path().to_path_buf()).unwrap();
let synced = crate::config_layers::synced_config_path();
assert!(
app.settings_chain.contains(&synced),
"{synced:?} in {:?}",
app.settings_chain
);
}
#[test]
fn the_multiline_paste_warning_follows_its_setting() {
use crate::prefs::MultilinePasteWarning;
let (mut app, _tmp) = plain_paste_app();
app.multiline_paste_warning = MultilinePasteWarning::Never;
app.handle_paste(TWO_LINES);
assert_eq!(pasted(&app), TWO_LINES, "never: straight in");
let (mut app, _tmp) = plain_paste_app();
app.multiline_paste_warning = MultilinePasteWarning::Always;
app.terminals[0].feed_bytes_for_test(b"\x1b[?2004h");
app.handle_paste(TWO_LINES);
assert!(
app.pending_terminal_paste.is_some(),
"always: asks even when bracketed"
);
assert_eq!(pasted(&app), "");
}
#[test]
fn the_multiline_paste_warning_setting_parses() {
use crate::prefs::{MultilinePasteWarning, Prefs};
let p: Prefs = serde_json::from_str(r#"{"terminal_multiline_paste_warning":"never"}"#).unwrap();
assert_eq!(
p.terminal_multiline_paste_warning,
MultilinePasteWarning::Never
);
let p: Prefs = serde_json::from_str("{}").unwrap();
assert_eq!(
p.terminal_multiline_paste_warning,
MultilinePasteWarning::Auto
);
}
fn frame_bytes_at(depth: crate::color_depth::ColorDepth) -> String {
frame_bytes_with(depth, true)
}
fn frame_bytes_with(depth: crate::color_depth::ColorDepth, underline_colors: bool) -> String {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("a.py"), "print(1)\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&tmp.path().join("a.py")).unwrap();
app.color_depth = depth;
app.underline_colors = underline_colors;
struct Sink(std::rc::Rc<std::cell::RefCell<Vec<u8>>>);
impl std::io::Write for Sink {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.borrow_mut().extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
let bytes = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
let backend = ratatui::backend::CrosstermBackend::new(Sink(bytes.clone()));
let mut term = ratatui::Terminal::with_options(
backend,
ratatui::TerminalOptions {
viewport: ratatui::Viewport::Fixed(ratatui::layout::Rect::new(0, 0, 100, 30)),
},
)
.unwrap();
term.draw(|f| app.render_for_terminal(f)).unwrap();
drop(term);
String::from_utf8_lossy(&bytes.borrow()).into_owned()
}
#[test]
fn a_256_colour_terminal_gets_no_24_bit_colour() {
let out = frame_bytes_at(crate::color_depth::ColorDepth::Ansi256);
assert_eq!(out.matches(";2;").count(), 0, "{out:?}");
assert!(out.contains("48;5;"), "background indexes are written");
}
#[test]
fn a_16_colour_terminal_gets_only_the_16_ansi_colours() {
let out = frame_bytes_at(crate::color_depth::ColorDepth::Ansi16);
assert_eq!(out.matches(";2;").count(), 0, "{out:?}");
let indexes: Vec<u32> = out
.split("8;5;")
.skip(1)
.map(|rest| {
let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
digits.parse().unwrap()
})
.collect();
assert!(!indexes.is_empty());
assert!(indexes.iter().all(|&i| i < 16), "{indexes:?}");
}
#[test]
fn a_terminal_without_underline_colours_gets_no_underline_colour() {
use crate::color_depth::ColorDepth;
for depth in [
ColorDepth::TrueColor,
ColorDepth::Ansi256,
ColorDepth::Ansi16,
] {
let read = frame_bytes_with(depth, true);
assert!(
read.contains("\x1b[58;"),
"{depth:?}: the frame must hold an underline colour, or this proves nothing"
);
let out = frame_bytes_with(depth, false);
assert!(!out.contains("[58;"), "{depth:?}: {out:?}");
assert!(
out.contains("\x1b[4m"),
"{depth:?}: the underline itself stays"
);
}
}
#[test]
fn a_truecolor_terminal_keeps_24_bit_colour() {
let out = frame_bytes_at(crate::color_depth::ColorDepth::TrueColor);
assert!(out.matches(";2;").count() > 50, "{out:?}");
}
fn settings_editor_app(cfg: &std::path::Path, tmp: &std::path::Path) -> App {
let mut app = App::new(tmp.to_path_buf()).unwrap();
app.config_dir = cfg.to_path_buf();
app.run_command(crate::widgets::command_palette::Command::OpenSettingsEditor);
assert!(app.settings_editor.is_some(), "the editor opens");
app
}
#[test]
fn the_settings_editor_flips_a_setting_into_the_user_layer_and_applies_it() {
let cfg = tempfile::tempdir().unwrap();
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
cfg.path().join("config.json"),
"{\n \"auto_save\": false\n}\n",
)
.unwrap();
std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
std::fs::write(
tmp.path().join(".croft/config.json"),
"{ \"copy_on_select\": true }",
)
.unwrap();
let mut app = settings_editor_app(cfg.path(), tmp.path());
let copy = app
.settings_editor
.as_ref()
.unwrap()
.rows
.iter()
.find(|r| r.key == "copy_on_select")
.cloned()
.unwrap();
assert_eq!(copy.layer, crate::config_layers::LayerKind::Workspace);
type_keys(&mut app, "auto save");
let row = app
.settings_editor
.as_ref()
.unwrap()
.selected_row()
.cloned()
.unwrap();
assert_eq!(row.key, "auto_save");
assert_eq!(row.value, serde_json::json!(false));
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
let written: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(cfg.path().join("config.json")).unwrap())
.unwrap();
assert_eq!(written["auto_save"], serde_json::json!(true));
assert!(app.auto_save, "applied to the live session");
let row = app
.settings_editor
.as_ref()
.unwrap()
.selected_row()
.cloned()
.unwrap();
assert_eq!(row.value, serde_json::json!(true));
assert_eq!(row.layer, crate::config_layers::LayerKind::User);
}
fn user_config(cfg: &std::path::Path) -> serde_json::Value {
serde_json::from_str(&std::fs::read_to_string(cfg.join("config.json")).unwrap()).unwrap()
}
fn selected_setting(app: &App) -> crate::settings_editor::Row {
app.settings_editor
.as_ref()
.unwrap()
.selected_row()
.cloned()
.unwrap()
}
#[test]
fn del_resets_a_toggled_setting_and_drops_its_key() {
let cfg = tempfile::tempdir().unwrap();
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
cfg.path().join("config.json"),
"{\n \"auto_save_on_focus_change\": false,\n \"copy_on_select\": true\n}\n",
)
.unwrap();
let mut app = settings_editor_app(cfg.path(), tmp.path());
type_keys(&mut app, "auto save on focus change");
assert_eq!(
selected_setting(&app).layer,
crate::config_layers::LayerKind::User
);
app.handle_key(key(KeyCode::Delete, KeyModifiers::NONE))
.unwrap();
let written = user_config(cfg.path());
assert!(
written.get("auto_save_on_focus_change").is_none(),
"{written}"
);
assert_eq!(written["copy_on_select"], serde_json::json!(true));
let row = selected_setting(&app);
assert_eq!(row.key, "auto_save_on_focus_change");
assert_eq!(row.layer, crate::config_layers::LayerKind::Default);
assert!(app.status.contains("reset"), "{}", app.status);
}
#[test]
fn del_resets_a_number_setting_to_its_default() {
let cfg = tempfile::tempdir().unwrap();
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
cfg.path().join("config.json"),
"{ \"terminal_scrollback\": 5000, \"auto_save\": true }",
)
.unwrap();
let mut app = settings_editor_app(cfg.path(), tmp.path());
type_keys(&mut app, "terminal scrollback");
app.handle_key(key(KeyCode::Delete, KeyModifiers::NONE))
.unwrap();
let written = user_config(cfg.path());
assert!(written.get("terminal_scrollback").is_none(), "{written}");
let default = serde_json::to_value(crate::prefs::Prefs::default()).unwrap();
assert_eq!(selected_setting(&app).value, default["terminal_scrollback"]);
assert!(app.auto_save, "the other key still applies");
}
#[test]
fn resetting_the_user_value_leaves_the_workspace_one_in_force() {
let cfg = tempfile::tempdir().unwrap();
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
cfg.path().join("config.json"),
"{ \"copy_on_select\": false }",
)
.unwrap();
std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
std::fs::write(
tmp.path().join(".croft/config.json"),
"{ \"copy_on_select\": true }",
)
.unwrap();
let mut app = settings_editor_app(cfg.path(), tmp.path());
type_keys(&mut app, "copy on select");
app.handle_key(key(KeyCode::Delete, KeyModifiers::NONE))
.unwrap();
assert!(user_config(cfg.path()).get("copy_on_select").is_none());
let row = selected_setting(&app);
assert_eq!(row.layer, crate::config_layers::LayerKind::Workspace);
assert_eq!(row.value, serde_json::json!(true));
let ws = std::fs::read_to_string(tmp.path().join(".croft/config.json")).unwrap();
assert!(
ws.contains("copy_on_select"),
"the workspace layer is untouched: {ws}"
);
}
#[test]
fn del_on_a_setting_the_layer_does_not_set_writes_nothing() {
let cfg = tempfile::tempdir().unwrap();
let tmp = tempfile::tempdir().unwrap();
let mut app = settings_editor_app(cfg.path(), tmp.path());
type_keys(&mut app, "copy on select");
app.handle_key(key(KeyCode::Delete, KeyModifiers::NONE))
.unwrap();
assert!(!cfg.path().join("config.json").exists());
assert!(app.status.contains("not set"), "{}", app.status);
std::fs::write(
cfg.path().join("config.json"),
"{ \"copy_on_select\": true }",
)
.unwrap();
app.handle_key(key(KeyCode::Tab, KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Delete, KeyModifiers::NONE))
.unwrap();
assert!(
!tmp.path().join(".croft/config.json").exists(),
"the workspace layer has nothing to reset"
);
assert_eq!(
user_config(cfg.path())["copy_on_select"],
serde_json::json!(true),
"and the user layer is not the target"
);
}
#[test]
fn the_settings_editor_marks_changed_rows_and_shows_del_reset() {
let cfg = tempfile::tempdir().unwrap();
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
cfg.path().join("config.json"),
"{ \"auto_save\": true, \"auto_save_on_focus_change\": false }",
)
.unwrap();
let mut app = settings_editor_app(cfg.path(), tmp.path());
type_keys(&mut app, "auto save");
let buf = draw_buffer(&mut app, 140, 50);
let lines: Vec<String> = (0..buf.area.height)
.map(|y| {
(0..buf.area.width)
.map(|x| buf[(x, y)].symbol())
.collect::<String>()
})
.collect();
let line_of = |needle: &str| {
lines
.iter()
.find(|l| l.contains(needle))
.unwrap_or_else(|| panic!("{needle:?} not drawn:\n{}", lines.join("\n")))
.clone()
};
assert!(line_of("Esc close").contains("Del reset"));
let changed = lines
.iter()
.find(|l| l.contains("auto save ") && !l.contains("focus") && !l.contains("> auto"))
.cloned()
.unwrap_or_default();
assert!(changed.contains("\u{2022} auto save "), "{changed}");
let same = line_of("auto save on focus change");
assert!(!same.contains('\u{2022}'), "{same}");
}
#[test]
fn the_settings_editor_writes_the_workspace_layer_only_for_allowed_keys() {
let cfg = tempfile::tempdir().unwrap();
let tmp = tempfile::tempdir().unwrap();
let mut app = settings_editor_app(cfg.path(), tmp.path());
app.handle_key(key(KeyCode::Tab, KeyModifiers::NONE))
.unwrap();
assert_eq!(
app.settings_editor.as_ref().unwrap().target,
crate::config_layers::LayerKind::Workspace
);
type_keys(&mut app, "format on save");
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
let ws: serde_json::Value = serde_json::from_str(
&std::fs::read_to_string(tmp.path().join(".croft/config.json")).unwrap(),
)
.unwrap();
assert_eq!(ws["format_on_save"], serde_json::json!(true));
assert!(
!cfg.path().join("config.json").exists(),
"the user layer is untouched"
);
for _ in 0.."format on save".len() {
app.handle_key(key(KeyCode::Backspace, KeyModifiers::NONE))
.unwrap();
}
type_keys(&mut app, "sidebar auto hide");
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert!(app.status.contains("user"), "{}", app.status);
let ws = std::fs::read_to_string(tmp.path().join(".croft/config.json")).unwrap();
assert!(!ws.contains("sidebar_auto_hide"), "{ws}");
}
fn settings_editor_app_in_profile(cfg: &std::path::Path, tmp: &std::path::Path) -> App {
let work = cfg.join("profiles/work");
std::fs::create_dir_all(&work).unwrap();
std::fs::write(
work.join("config.json"),
"{\n \"theme\": \"light\",\n \"auto_save\": true\n}\n",
)
.unwrap();
std::fs::write(cfg.join("config.json"), "{\n \"auto_save\": false\n}\n").unwrap();
let mut app = App::new(tmp.to_path_buf()).unwrap();
app.config_dir = cfg.to_path_buf();
app.settings_profile = Some(String::from("work"));
app.run_command(crate::widgets::command_palette::Command::OpenSettingsEditor);
assert!(app.settings_editor.is_some(), "the editor opens");
app
}
fn settings_row(app: &App, key: &str) -> crate::settings_editor::Row {
app.settings_editor
.as_ref()
.unwrap()
.rows
.iter()
.find(|r| r.key == key)
.cloned()
.unwrap()
}
#[test]
fn the_settings_editor_shows_the_active_profile_s_settings() {
let cfg = tempfile::tempdir().unwrap();
let tmp = tempfile::tempdir().unwrap();
let app = settings_editor_app_in_profile(cfg.path(), tmp.path());
let theme = settings_row(&app, "theme");
assert_eq!(theme.value, serde_json::json!("light"));
assert_eq!(theme.layer, crate::config_layers::LayerKind::User);
assert_eq!(
settings_row(&app, "auto_save").value,
serde_json::json!(true),
"the profile's value, not the Default profile's false"
);
assert_eq!(
app.settings_editor.as_ref().unwrap().profile.as_deref(),
Some("work")
);
}
#[test]
fn the_settings_editor_writes_the_active_profile_s_config() {
let cfg = tempfile::tempdir().unwrap();
let tmp = tempfile::tempdir().unwrap();
let mut app = settings_editor_app_in_profile(cfg.path(), tmp.path());
type_keys(&mut app, "auto save");
assert_eq!(
app.settings_editor
.as_ref()
.unwrap()
.selected_row()
.unwrap()
.key,
"auto_save"
);
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
let work: serde_json::Value = serde_json::from_str(
&std::fs::read_to_string(cfg.path().join("profiles/work/config.json")).unwrap(),
)
.unwrap();
assert_eq!(
work["auto_save"],
serde_json::json!(false),
"{}",
app.status
);
assert_eq!(
work["theme"],
serde_json::json!("light"),
"the rest is kept"
);
assert_eq!(
std::fs::read_to_string(cfg.path().join("config.json")).unwrap(),
"{\n \"auto_save\": false\n}\n",
"the Default profile's file is untouched"
);
assert!(!app.auto_save, "applied to the live session");
assert_eq!(
settings_row(&app, "theme").value,
serde_json::json!("light"),
"the re-merge after the write still reads the profile"
);
}
#[test]
fn the_settings_editor_header_names_the_active_profile() {
let cfg = tempfile::tempdir().unwrap();
let tmp = tempfile::tempdir().unwrap();
let mut app = settings_editor_app_in_profile(cfg.path(), tmp.path());
let text = draw_screen(&mut app, 140, 40);
assert!(text.contains("profile work"), "{text}");
}
#[test]
fn without_a_profile_the_settings_editor_keeps_the_default_config() {
let cfg = tempfile::tempdir().unwrap();
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(cfg.path().join("profiles/work")).unwrap();
std::fs::write(
cfg.path().join("profiles/work/config.json"),
"{ \"auto_save\": true }",
)
.unwrap();
std::fs::write(
cfg.path().join("config.json"),
"{\n \"auto_save\": false\n}\n",
)
.unwrap();
let mut app = settings_editor_app(cfg.path(), tmp.path());
assert_eq!(
settings_row(&app, "auto_save").value,
serde_json::json!(false)
);
type_keys(&mut app, "auto save");
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
let written: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(cfg.path().join("config.json")).unwrap())
.unwrap();
assert_eq!(written["auto_save"], serde_json::json!(true));
assert_eq!(
std::fs::read_to_string(cfg.path().join("profiles/work/config.json")).unwrap(),
"{ \"auto_save\": true }",
"the profile's file is untouched"
);
let text = draw_screen(&mut app, 140, 40);
assert!(text.contains("Writing to user (config.json)"), "{text}");
}
#[test]
fn the_settings_editor_asks_for_a_number_and_refuses_one_that_is_not() {
let cfg = tempfile::tempdir().unwrap();
let tmp = tempfile::tempdir().unwrap();
let mut app = settings_editor_app(cfg.path(), tmp.path());
type_keys(&mut app, "terminal scrollback");
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert!(matches!(
app.input_prompt.as_ref().map(|p| &p.purpose),
Some(crate::widgets::input_prompt::InputPurpose::SettingValue { key }) if key == "terminal_scrollback"
));
app.close_input_prompt();
app.submit_setting_value("terminal_scrollback", "lots");
assert!(app.status.contains("number"), "{}", app.status);
assert!(!cfg.path().join("config.json").exists());
app.submit_setting_value("terminal_scrollback", " 5000 ");
let written: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(cfg.path().join("config.json")).unwrap())
.unwrap();
assert_eq!(written["terminal_scrollback"], serde_json::json!(5000));
}
#[test]
fn enter_on_the_unset_language_picks_one_in_the_editor() {
let cfg = tempfile::tempdir().unwrap();
let tmp = tempfile::tempdir().unwrap();
let mut app = settings_editor_app(cfg.path(), tmp.path());
type_keys(&mut app, "locale");
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert!(app.settings_editor.is_some(), "still in the editor");
let lang = user_config(cfg.path())["locale"].clone();
assert!(lang.is_string(), "a language was set: {lang}");
let row = app
.settings_editor
.as_ref()
.unwrap()
.selected_row()
.cloned()
.unwrap();
assert_eq!(row.value, lang, "and the row shows it");
}
#[test]
fn an_unset_number_setting_takes_a_number_and_an_empty_entry_unsets_it() {
let cfg = tempfile::tempdir().unwrap();
let tmp = tempfile::tempdir().unwrap();
let mut app = settings_editor_app(cfg.path(), tmp.path());
type_keys(&mut app, "terminal rewind");
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert!(matches!(
app.input_prompt.as_ref().map(|p| &p.purpose),
Some(crate::widgets::input_prompt::InputPurpose::SettingValue { key }) if key == "terminal_rewind_mb"
));
assert_eq!(
app.input_prompt.as_ref().unwrap().value,
"",
"an unset setting's prompt opens empty, not on (default)"
);
app.close_input_prompt();
app.submit_setting_value("terminal_rewind_mb", "500");
assert_eq!(
user_config(cfg.path())["terminal_rewind_mb"],
serde_json::json!(500)
);
app.submit_setting_value("terminal_rewind_mb", "");
let written = user_config(cfg.path());
assert!(
written.get("terminal_rewind_mb").is_none(),
"unset, so its default applies: {written}"
);
}
#[test]
fn a_value_the_setting_cannot_hold_is_refused() {
let cfg = tempfile::tempdir().unwrap();
let tmp = tempfile::tempdir().unwrap();
let mut app = settings_editor_app(cfg.path(), tmp.path());
app.write_setting("code_scanning", serde_json::json!("enabled"));
assert!(app.status.contains("can't be enabled"), "{}", app.status);
assert!(!cfg.path().join("config.json").exists());
type_keys(&mut app, "code scanning");
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert!(app.input_prompt.is_none(), "a choice: no free text to type");
assert_eq!(
user_config(cfg.path())["code_scanning"],
serde_json::json!("on")
);
}
#[test]
fn a_list_setting_opens_its_layer_file_at_the_key() {
let cfg = tempfile::tempdir().unwrap();
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
let ws_file = tmp.path().join(".croft/config.json");
std::fs::write(
&ws_file,
"{\n \"auto_save\": true,\n \"files_exclude\": [\"target\"]\n}\n",
)
.unwrap();
let mut app = settings_editor_app(cfg.path(), tmp.path());
app.handle_key(key(KeyCode::Tab, KeyModifiers::NONE))
.unwrap();
type_keys(&mut app, "files_exclude");
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert!(app.settings_editor.is_none());
let opened = app.editor.path.clone().unwrap();
assert!(
opened.ends_with(".croft/config.json"),
"{}",
opened.display()
);
assert_eq!(app.editor.cursor_row, 2, "on the key's line");
assert!(app.status.contains("files exclude"), "{}", app.status);
}
#[test]
fn a_list_setting_in_the_user_layer_opens_the_user_file_at_the_key() {
let cfg = tempfile::tempdir().unwrap();
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
cfg.path().join("config.json"),
"{\n \"theme\": \"dark\",\n \"auto_save\": true,\n \"search_exclude\": []\n}\n",
)
.unwrap();
let mut app = settings_editor_app(cfg.path(), tmp.path());
type_keys(&mut app, "search exclude");
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
let opened = app.editor.path.clone().unwrap();
assert_eq!(opened.file_name().unwrap(), "config.json");
assert!(
opened.starts_with(cfg.path()) || opened.starts_with(cfg.path().canonicalize().unwrap())
);
assert_eq!(app.editor.cursor_row, 3);
}
#[test]
fn confirming_an_empty_review_prefix_keeps_it_empty() {
let cfg = tempfile::tempdir().unwrap();
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
cfg.path().join("config.json"),
"{\n \"review_ai_prefix\": \"\"\n}\n",
)
.unwrap();
let mut app = settings_editor_app(cfg.path(), tmp.path());
type_keys(&mut app, "review_ai_prefix");
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
let prompt = app.input_prompt.as_ref().expect("a text prompt");
assert_eq!(prompt.value, "", "opens empty, not on (default)");
let value = prompt.value.clone();
app.close_input_prompt();
app.submit_setting_value("review_ai_prefix", &value);
assert_eq!(
user_config(cfg.path())["review_ai_prefix"],
serde_json::json!("")
);
}
#[test]
fn the_settings_editor_draws_its_value_prompt_on_top() {
let cfg = tempfile::tempdir().unwrap();
let tmp = tempfile::tempdir().unwrap();
let mut app = settings_editor_app(cfg.path(), tmp.path());
type_keys(&mut app, "terminal scrollback");
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert!(app.input_prompt.is_some(), "Enter asks for the number");
type_keys(&mut app, "424242");
let backend = ratatui::backend::TestBackend::new(120, 36);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let screen: String = term
.backend()
.buffer()
.content()
.iter()
.map(|c| c.symbol())
.collect();
assert!(screen.contains("424242"), "the typed value is visible");
}
#[test]
fn vscode_line_numbers_setting_applies() {
use crate::widgets::editor::LineNumbers;
for (value, want) in [
("relative", LineNumbers::Relative),
("off", LineNumbers::Off),
("sideways", LineNumbers::On),
] {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
std::fs::write(
tmp.path().join(".vscode/settings.json"),
format!(r#"{{ "editor.lineNumbers": "{value}" }}"#),
)
.unwrap();
let app = App::new(tmp.path().to_path_buf()).unwrap();
assert_eq!(app.line_numbers, want, "{value}");
}
}
#[test]
fn a_reload_applies_the_settings_read_at_start() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let mut p = app.applied_settings.clone();
p.problems_scope = String::from("open_files");
p.problems_project_scope = String::from("off");
p.diff_ignore_whitespace = String::from("all");
p.sidebar_auto_hide = !app.sidebar_auto_hide;
p.color_depth = Some(String::from("16"));
p.screen_reader = !app.screen_reader;
p.screen_reader_command = Some(String::from("say"));
p.disable_proactive_navigator = app.pair.proactive_navigator_enabled;
p.disable_secret_redaction = app.secret_redaction;
let auto_hide = p.sidebar_auto_hide;
let reader = p.screen_reader;
let proactive = !p.disable_proactive_navigator;
let redaction = !p.disable_secret_redaction;
app.apply_merged_settings(&p);
assert_eq!(
app.problems.scope,
crate::widgets::problems::ProblemScope::from_config("open_files")
);
assert_eq!(app.problems_project_scope, "off");
assert_eq!(
app.diff_ws_default,
crate::widgets::diff::DiffWhitespace::from_config("all")
);
assert_eq!(
app.editor.diff_ws_default, app.diff_ws_default,
"open editors too"
);
assert_eq!(app.sidebar_auto_hide, auto_hide);
assert_eq!(app.color_depth, crate::color_depth::ColorDepth::Ansi16);
assert_eq!(app.screen_reader, reader);
assert_eq!(app.screen_reader_command.as_deref(), Some("say"));
assert_eq!(app.pair.proactive_navigator_enabled, proactive);
assert_eq!(app.secret_redaction, redaction);
}
#[test]
fn a_reload_leaves_a_session_toggle_alone_when_its_setting_did_not_change() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let before = app.problems.scope;
app.problems.scope = before.next();
let mut p = app.applied_settings.clone();
p.format_on_save = !p.format_on_save;
app.apply_merged_settings(&p);
assert_eq!(app.problems.scope, before.next());
}
#[test]
fn a_reload_applies_the_review_ai_prefix() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let mut p = app.applied_settings.clone();
p.review_ai_prefix = Some(String::from("[bot] "));
app.apply_merged_settings(&p);
assert_eq!(app.review.ai_prefix, "[bot] ");
p.review_ai_prefix = None;
app.apply_merged_settings(&p);
assert_eq!(
app.review.ai_prefix,
crate::review_threads::DEFAULT_AI_PREFIX
);
}
#[test]
fn a_reload_after_a_palette_toggle_applies_the_value_changed_back() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let file = app.applied_settings.clone();
assert!(!app.screen_reader);
app.toggle_screen_reader();
app.toggle_sidebar_auto_hide();
app.toggle_secret_redaction();
app.toggle_proactive_navigator();
app.run_command(crate::widgets::command_palette::Command::ProblemsToggleScope);
assert!(app.screen_reader);
app.apply_merged_settings(&file);
assert!(!app.screen_reader, "screen reader mode");
assert_eq!(app.sidebar_auto_hide, file.sidebar_auto_hide, "auto-hide");
assert_eq!(
app.secret_redaction, !file.disable_secret_redaction,
"secret redaction"
);
assert_eq!(
app.pair.proactive_navigator_enabled, !file.disable_proactive_navigator,
"proactive navigator"
);
assert_eq!(
app.problems.scope,
crate::widgets::problems::ProblemScope::from_config(&file.problems_scope),
"PROBLEMS scope"
);
}
#[test]
fn saving_a_setting_read_at_start_says_it_applies_at_the_next_start() {
let tmp = tempfile::tempdir().unwrap();
let cfg = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.config_dir = cfg.path().to_path_buf();
app.open_settings_editor();
app.write_setting("locale", serde_json::json!("de"));
assert!(
app.status
.ends_with("it applies the next time croft starts"),
"{}",
app.status
);
app.write_setting("format_on_save", serde_json::json!(true));
assert!(!app.status.contains("next time"), "{}", app.status);
}
#[test]
fn app_new_reads_only_the_next_start_settings_itself() {
let src = std::fs::read_to_string(
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/app/mod.rs"),
)
.unwrap();
const DEFINED: &str = "let loaded_prefs = merged_settings.prefs.clone();";
let start = src
.find(DEFINED)
.expect("App::new reads the merged settings")
+ DEFINED.len();
let end = start
+ src[start..]
.find(" Ok(app)\n")
.expect("App::new ends");
let body = &src[start..end];
const WHOLE: &[&str] = &[
"settings_to_build_with(&loaded_prefs)",
"publish_pane_settings(&loaded_prefs)",
"apply_merged_settings(&loaded_prefs)",
];
let whole: std::collections::BTreeSet<usize> = WHOLE
.iter()
.flat_map(|w| {
let inner = w.find("loaded_prefs").unwrap();
body.match_indices(w).map(move |(at, _)| at + inner)
})
.collect();
let mut fields = Vec::new();
let mut stray = Vec::new();
for (at, _) in body.match_indices("loaded_prefs") {
let after = body[at + "loaded_prefs".len()..].trim_start();
if let Some(field) = after.strip_prefix('.') {
let key: String = field
.chars()
.take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
.collect();
fields.push(key);
} else if !whole.contains(&at) {
let line = body[..at].rsplit('\n').next().unwrap_or("");
stray.push(format!("{line}loaded_prefs"));
}
}
assert!(
fields.iter().any(|k| k == "layout"),
"fixture: the scan sees App::new's reads: {fields:?}"
);
let live: Vec<&String> = fields
.iter()
.filter(|k| !crate::settings_table::applies_at_next_start(k))
.collect();
assert!(
live.is_empty(),
"App::new reads these itself, where only the apply step a reload runs should: {live:?}"
);
assert!(
stray.is_empty(),
"the loaded settings go whole only to {WHOLE:?}, not to: {stray:?}"
);
let settings = std::fs::read_to_string(
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/app/settings.rs"),
)
.unwrap();
let from = settings
.find("pub(super) fn apply_merged_settings")
.expect("the apply step");
let to = from
+ settings[from..]
.find("pub(super) fn settings_to_build_with")
.expect("the apply step's end");
let apply = &settings[from..to];
let keys = |text: &str, var: &str| -> std::collections::BTreeSet<String> {
let word = |c: char| c.is_ascii_alphanumeric() || c == '_';
text.match_indices(var)
.filter(|(at, _)| !text[..*at].ends_with(word))
.filter_map(|(at, _)| {
let field = text[at + var.len()..].trim_start().strip_prefix('.')?;
Some(field.chars().take_while(|c| word(*c)).collect())
})
.collect()
};
let built = keys(body, "built");
let applied = keys(apply, "p");
assert!(
built.len() > 20 && applied.len() > 20,
"fixture: the scan sees both: {built:?} {applied:?}"
);
let missed: Vec<&String> = built
.iter()
.filter(|k| *k != "clone" && !applied.contains(*k))
.collect();
assert!(
missed.is_empty(),
"App::new builds from these, and the apply step never sets them: {missed:?}"
);
}
#[test]
fn start_applies_the_loaded_settings_through_the_reload_step() {
let tmp = tempfile::tempdir().unwrap();
let layer = crate::config_layers::workspace_config_path(tmp.path());
std::fs::create_dir_all(layer.parent().unwrap()).unwrap();
std::fs::write(
&layer,
r#"{"format_on_save": true, "rulers": [80, 100], "render_whitespace": "all",
"disable_inlay_hints": true, "line_numbers": "relative"}"#,
)
.unwrap();
let app = App::new(tmp.path().to_path_buf()).unwrap();
assert!(app.format_on_save);
assert_eq!(app.rulers, vec![80, 100]);
assert_eq!(
app.whitespace_mode,
crate::widgets::editor::WhitespaceMode::All
);
assert!(!app.inlay_hints_enabled);
assert_eq!(
app.line_numbers,
crate::widgets::editor::LineNumbers::from_pref("relative")
);
assert_eq!(app.applied_settings.rulers, vec![80, 100]);
assert!(app.applied_settings.format_on_save);
}