use std::fs;
use std::path::PathBuf;
use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH};
#[cfg(unix)]
use std::time::{Duration, Instant};
#[cfg(target_os = "linux")]
use std::hash::{Hash, Hasher};
#[cfg(target_os = "linux")]
use std::os::unix::fs::{symlink, PermissionsExt};
fn fixture_dir(name: &str) -> PathBuf {
let stamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system time should be after Unix epoch")
.as_nanos();
let dir = std::env::temp_dir().join(format!("mdo-test-{name}-{}-{stamp}", std::process::id()));
fs::create_dir_all(&dir).expect("failed to create temp fixture dir");
dir
}
#[test]
fn setup_prints_new_user_path_without_prompt_when_piped() {
let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
.arg("--setup")
.output()
.expect("failed to run mdo");
assert!(output.status.success(), "mdo failed: {output:?}");
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(stdout.contains("Welcome to mdo."));
assert!(stdout.contains("mdo --open notes.md"));
if cfg!(any(target_os = "linux", target_os = "windows")) {
assert!(stdout.contains("mdo --install-file-manager"));
} else {
assert!(stdout.contains("does not have a built-in mdo installer yet"));
}
assert!(!stdout.contains("Install Open as HTML file-manager integration now?"));
}
#[test]
fn no_args_prints_short_landing_page_and_succeeds() {
let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
.output()
.expect("failed to run mdo");
assert!(output.status.success(), "mdo failed: {output:?}");
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(stdout.contains("Open Markdown as HTML."));
assert!(stdout.contains("mdo FILE.md"));
assert!(stdout.contains("mdo --setup"));
assert!(stdout.contains("mdo --help"));
assert!(!stdout.contains("--unsafe-html"));
assert!(output.stderr.is_empty());
}
#[test]
fn help_prints_full_cli_reference() {
let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
.arg("--help")
.output()
.expect("failed to run mdo");
assert!(output.status.success(), "mdo --help failed: {output:?}");
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(stdout
.lines()
.any(|line| line.starts_with("Usage: mdo") && line.ends_with("[OPTIONS] [INPUT]")));
assert!(stdout.contains("--setup"));
assert!(stdout.contains("--unsafe-html"));
}
#[test]
fn converts_markdown_to_styled_html5_document() {
let dir = fixture_dir("html5");
let input = dir.join("sample.md");
fs::write(
&input,
"# Sample Title\n\nA paragraph with **strong** text.\n\n| A | B |\n|---|---|\n| 1 | 2 |\n",
)
.expect("failed to write markdown fixture");
let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
.arg(&input)
.output()
.expect("failed to run mdo");
assert!(output.status.success(), "mdo failed: {output:?}");
let html = fs::read_to_string(dir.join("sample.html"))
.expect("failed to read html output")
.replace("\r\n", "\n");
assert!(html.contains("<!DOCTYPE html>"));
assert!(html.contains("<title>Sample Title</title>"));
assert!(html.contains("<h1>Sample Title</h1>"));
assert!(html.contains("<strong>strong</strong>"));
assert!(html.contains("<table>"));
assert!(html.contains("#theme-toggle"));
assert!(html.contains(r#"id="mdo-default-typography""#));
assert!(html.contains("body {\n font-size: 1rem;"));
assert!(html.contains("h1 {\n font-size: 2.4rem;"));
assert!(html.contains("h2 {\n font-size: 2rem;"));
assert!(html.contains("h3 {\n font-size: 1.4rem;"));
assert!(html.contains(&format!(
"<meta name=\"generator\" content=\"mdo {}\">",
env!("CARGO_PKG_VERSION")
)));
assert!(!html.contains("Generated by"));
assert!(!html.contains(env!("CARGO_PKG_HOMEPAGE")));
assert_eq!(
html.matches(env!("CARGO_PKG_VERSION")).count(),
1,
"mdo version should appear only in the generator meta tag"
);
assert!(html.contains("<footer class=\"mdo-source-meta\">Source modified: <time datetime=\""));
assert!(html.contains("</time></footer>"));
assert!(html.contains("aria-label"));
fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}
#[test]
fn theme_toggle_manual_flag_survives_storage_write_failure() {
let dir = fixture_dir("theme-manual-flag");
let input = dir.join("sample.md");
fs::write(&input, "# Sample Title\n\nBody text.\n").expect("failed to write markdown fixture");
let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
.arg(&input)
.output()
.expect("failed to run mdo");
assert!(output.status.success(), "mdo failed: {output:?}");
let html = fs::read_to_string(dir.join("sample.html"))
.expect("failed to read html output")
.replace("\r\n", "\n");
let manual_init_pos = html
.find("var manual=saved!==null;")
.expect("script should initialize an in-memory manual-choice flag from saved state");
let click_set_pos = html
.find("manual=true;")
.expect("click handler should set the manual flag unconditionally");
let click_try_pos = html
.find("try{localStorage.setItem('theme',next)}catch(e){}")
.expect("click handler should still attempt to persist the choice");
assert!(
click_set_pos < click_try_pos,
"manual flag must be set before the (possibly failing) localStorage write, so a \
persistence failure can never suppress the in-memory record of an explicit choice"
);
let mq_change_pos = html
.find("mq.addEventListener('change'")
.expect("script should still track OS theme changes live");
assert!(
mq_change_pos > manual_init_pos,
"manual flag should be declared before it is referenced by the media-query handler"
);
assert!(
html[mq_change_pos..].contains("if(!manual){"),
"prefers-color-scheme handler must gate on the in-memory manual flag, not a fresh \
localStorage read, so a failed setItem() can't cause it to override an explicit choice"
);
assert!(
!html[mq_change_pos..].contains("if(!read())"),
"prefers-color-scheme handler should not fall back to re-reading localStorage to decide \
whether the user already made a manual choice"
);
fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}
#[test]
fn css_override_is_embedded_after_default_styles() {
let dir = fixture_dir("css-override");
let input = dir.join("sample.md");
let css = dir.join("override.css");
let output_path = dir.join("sample.html");
fs::write(&input, "# Sample Title\n\nA paragraph.\n")
.expect("failed to write markdown fixture");
fs::write(
&css,
"h1 { font-size: 1.75rem; }\nh2 { font-size: 1.35rem; }\n",
)
.expect("failed to write css fixture");
let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
.arg("--css")
.arg(&css)
.arg("--output")
.arg(&output_path)
.arg(&input)
.output()
.expect("failed to run mdo");
assert!(output.status.success(), "mdo failed: {output:?}");
let html = fs::read_to_string(output_path).expect("failed to read html output");
let theme_pos = html
.find("#theme-toggle")
.expect("styled output should contain theme toggle CSS");
let default_pos = html
.find("id=\"mdo-default-typography\"")
.expect("styled output should contain default mdo typography block");
let override_pos = html
.find("id=\"mdo-css-override\"")
.expect("styled output should contain CSS override block");
assert!(
default_pos > theme_pos,
"default mdo typography should be appended after built-in styles"
);
assert!(
override_pos > default_pos,
"custom CSS should be appended after mdo defaults"
);
assert!(html.contains("h1 { font-size: 1.75rem; }"));
assert!(html.contains("h2 { font-size: 1.35rem; }"));
fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}
#[test]
fn bundled_restore_simple_css_can_restore_vendored_typography() {
let dir = fixture_dir("restore-simple-css");
let input = dir.join("sample.md");
let output_path = dir.join("sample.html");
let restore_css = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("assets")
.join("restore-simple-css.css");
fs::write(&input, "# Sample Title\n\nA paragraph.\n")
.expect("failed to write markdown fixture");
let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
.arg("--css")
.arg(&restore_css)
.arg("--output")
.arg(&output_path)
.arg(&input)
.output()
.expect("failed to run mdo");
assert!(output.status.success(), "mdo failed: {output:?}");
let html = fs::read_to_string(output_path).expect("failed to read html output");
let default_pos = html
.find("id=\"mdo-default-typography\"")
.expect("styled output should contain default mdo typography block");
let override_pos = html
.find("id=\"mdo-css-override\"")
.expect("styled output should contain CSS override block");
assert!(
override_pos > default_pos,
"restore CSS should be appended after mdo defaults"
);
assert!(html.contains("font-size: 1.15rem;"));
assert!(html.contains("font-size: 3rem;"));
assert!(html.contains("font-size: 2.6rem;"));
assert!(html.contains("font-size: 2rem;"));
assert!(html.contains("@media only screen and (width <= 720px)"));
fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}
#[test]
fn css_override_cannot_be_combined_with_bare_output() {
let dir = fixture_dir("css-override-bare");
let input = dir.join("sample.md");
let css = dir.join("override.css");
fs::write(&input, "# Sample Title\n").expect("failed to write markdown fixture");
fs::write(&css, "h1 { font-size: 1.75rem; }\n").expect("failed to write css fixture");
let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
.arg("--bare")
.arg("--css")
.arg(&css)
.arg(&input)
.output()
.expect("failed to run mdo");
assert!(!output.status.success(), "mdo unexpectedly succeeded");
assert_eq!(output.status.code(), Some(2));
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("--css cannot be combined with --bare"));
fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}
#[test]
fn bare_output_omits_document_shell() {
let dir = fixture_dir("bare");
let input = dir.join("fragment.md");
let output_path = dir.join("fragment.html");
fs::write(&input, "**bare** fragment").expect("failed to write markdown fixture");
let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
.args(["--bare", "--output"])
.arg(&output_path)
.arg(&input)
.output()
.expect("failed to run mdo");
assert!(output.status.success(), "mdo failed: {output:?}");
let html = fs::read_to_string(output_path).expect("failed to read html output");
assert!(html.contains("<p><strong>bare</strong> fragment</p>"));
assert!(!html.contains("<!DOCTYPE html>"));
assert!(!html.contains("<html"));
assert!(!html.contains("<style>"));
assert!(!html.contains("name=\"generator\""));
assert!(!html.contains("Generated by"));
assert!(!html.contains("Source modified"));
fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}
#[test]
fn sanitizes_active_html_by_default() {
let dir = fixture_dir("sanitize");
let input = dir.join("payload.md");
let output_path = dir.join("payload.html");
fs::write(
&input,
"# Payload\n\n<script>window.__mdo_xss=1</script>\n\n<img src=x onerror=\"window.__mdo_img=1\">\n",
)
.expect("failed to write markdown fixture");
let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
.args(["--bare", "--output"])
.arg(&output_path)
.arg(&input)
.output()
.expect("failed to run mdo");
assert!(output.status.success(), "mdo failed: {output:?}");
let html = fs::read_to_string(output_path).expect("failed to read html output");
assert!(html.contains("<h1>Payload</h1>"));
assert!(!html.contains("<script>"));
assert!(!html.contains("window.__mdo_xss"));
assert!(!html.contains("onerror"));
assert!(html.contains("<img src=\"x\">"));
fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}
#[test]
fn unsafe_html_preserves_raw_html() {
let dir = fixture_dir("unsafe-html");
let input = dir.join("payload.md");
let output_path = dir.join("payload.html");
fs::write(
&input,
"# Payload\n\n<script>window.__mdo_xss=1</script>\n\n<img src=x onerror=\"window.__mdo_img=1\">\n",
)
.expect("failed to write markdown fixture");
let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
.args(["--unsafe-html", "--bare", "--output"])
.arg(&output_path)
.arg(&input)
.output()
.expect("failed to run mdo");
assert!(output.status.success(), "mdo failed: {output:?}");
let html = fs::read_to_string(output_path).expect("failed to read html output");
assert!(html.contains("<script>window.__mdo_xss=1</script>"));
assert!(html.contains("onerror=\"window.__mdo_img=1\""));
fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}
#[test]
fn sanitizer_keeps_markdown_task_list_checkboxes() {
let dir = fixture_dir("task-list");
let input = dir.join("tasks.md");
let output_path = dir.join("tasks.html");
fs::write(&input, "- [ ] unchecked\n- [x] checked\n")
.expect("failed to write markdown fixture");
let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
.args(["--bare", "--output"])
.arg(&output_path)
.arg(&input)
.output()
.expect("failed to run mdo");
assert!(output.status.success(), "mdo failed: {output:?}");
let html = fs::read_to_string(output_path).expect("failed to read html output");
assert!(html.contains(r#"<input type="checkbox" disabled="">"#));
assert!(html.contains(r#"<input type="checkbox" checked="" disabled="">"#));
fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}
#[test]
fn sanitizer_keeps_markdown_footnote_links() {
let dir = fixture_dir("footnotes");
let input = dir.join("notes.md");
let output_path = dir.join("notes.html");
fs::write(&input, "A footnote ref[^1].\n\n[^1]: Footnote text.\n")
.expect("failed to write markdown fixture");
let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
.args(["--bare", "--output"])
.arg(&output_path)
.arg(&input)
.output()
.expect("failed to run mdo");
assert!(output.status.success(), "mdo failed: {output:?}");
let html = fs::read_to_string(output_path).expect("failed to read html output");
assert!(html.contains(r#"class="footnote-reference""#));
assert!(html.contains(r##"href="#1""##));
assert!(html.contains(r#"class="footnote-definition""#));
assert!(html.contains(r#"id="1""#));
fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}
#[test]
fn verbose_html_is_byte_identical_and_diagnostics_go_to_stderr() {
let dir = fixture_dir("verbose");
let input = dir.join("sample.md");
let quiet_out = dir.join("quiet.html");
let verbose_out = dir.join("verbose.html");
fs::write(
&input,
"# Sample Title\n\nA paragraph with **strong** text.\n\n- [ ] a task\n",
)
.expect("failed to write markdown fixture");
let quiet = Command::new(env!("CARGO_BIN_EXE_mdo"))
.arg("--output")
.arg(&quiet_out)
.arg(&input)
.output()
.expect("failed to run mdo");
assert!(quiet.status.success(), "mdo failed: {quiet:?}");
assert!(
quiet.stderr.is_empty(),
"a successful non-verbose run should write nothing to stderr: {quiet:?}"
);
let verbose = Command::new(env!("CARGO_BIN_EXE_mdo"))
.arg("--verbose")
.arg("--output")
.arg(&verbose_out)
.arg(&input)
.output()
.expect("failed to run mdo");
assert!(
verbose.status.success(),
"mdo --verbose failed: {verbose:?}"
);
let quiet_html = fs::read(&quiet_out).expect("failed to read quiet html output");
let verbose_html = fs::read(&verbose_out).expect("failed to read verbose html output");
assert_eq!(
quiet_html, verbose_html,
"--verbose must not change the generated HTML"
);
assert!(!String::from_utf8_lossy(&verbose_html).contains("Render workflow"));
let stderr = String::from_utf8_lossy(&verbose.stderr);
assert!(
stderr.contains("Render workflow"),
"stderr should carry the timing report: {stderr}"
);
for stage in ["read", "markdown", "sanitize", "assemble", "write", "total"] {
assert!(
stderr.contains(stage),
"stderr should report the {stage} stage: {stderr}"
);
}
assert!(stderr.contains(" ms"), "timings should be in ms: {stderr}");
let stdout = String::from_utf8_lossy(&verbose.stdout);
assert!(stdout.contains("Converted"));
assert!(
!stdout.contains("Render workflow") && !stdout.contains("total"),
"timing diagnostics must not appear on stdout: {stdout}"
);
fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}
#[test]
fn verbose_cannot_be_combined_with_setup() {
let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
.args(["--setup", "--verbose"])
.output()
.expect("failed to run mdo");
assert!(!output.status.success(), "mdo unexpectedly succeeded");
assert_eq!(output.status.code(), Some(2));
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("--setup cannot be combined"));
}
#[cfg(target_os = "linux")]
#[test]
fn normal_output_respects_umask_for_new_files() {
let dir = fixture_dir("normal-permissions");
let input = dir.join("sample.md");
let output_path = dir.join("sample.html");
fs::write(&input, "# Permissions\n").expect("failed to write markdown fixture");
let output = Command::new("sh")
.arg("-c")
.arg("umask 022; exec \"$@\"")
.arg("mdo-test-sh")
.arg(env!("CARGO_BIN_EXE_mdo"))
.arg("--output")
.arg(&output_path)
.arg(&input)
.output()
.expect("failed to run mdo through shell");
assert!(output.status.success(), "mdo failed: {output:?}");
let mode = fs::metadata(&output_path)
.expect("failed to stat html output")
.permissions()
.mode()
& 0o777;
assert_eq!(mode, 0o644);
fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}
#[cfg(target_os = "linux")]
#[test]
fn open_output_refuses_precreated_symlink() {
let dir = fixture_dir("open-symlink");
let input = dir.join("sample.md");
let target = dir.join("target.txt");
fs::write(&input, "# Safe\n\nreplacement").expect("failed to write markdown fixture");
fs::write(&target, "do not overwrite").expect("failed to write symlink target");
let output_path = temp_output_for_test(&input);
fs::create_dir_all(
output_path
.parent()
.expect("temp output should have a parent"),
)
.expect("failed to create temp output parent");
symlink(&target, &output_path).expect("failed to create temp output symlink");
let fake_bin = dir.join("bin");
fs::create_dir_all(&fake_bin).expect("failed to create fake bin dir");
let fake_xdg_open = fake_bin.join("xdg-open");
fs::write(&fake_xdg_open, "#!/bin/sh\nexit 0\n").expect("failed to write fake xdg-open");
fs::set_permissions(&fake_xdg_open, fs::Permissions::from_mode(0o700))
.expect("failed to chmod fake xdg-open");
let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
.arg("--open")
.arg(&input)
.env("PATH", &fake_bin)
.output()
.expect("failed to run mdo");
assert!(
!output.status.success(),
"mdo should exit non-zero when it refuses the symlinked output: {output:?}"
);
let target_contents = fs::read_to_string(&target).expect("failed to read symlink target");
assert_eq!(target_contents, "do not overwrite");
assert!(
fs::symlink_metadata(&output_path)
.expect("failed to stat temp output")
.file_type()
.is_symlink(),
"temp output symlink should not have been replaced"
);
fs::remove_file(&output_path).expect("failed to remove temp output symlink");
fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}
#[cfg(target_os = "linux")]
fn temp_output_for_test(input: &std::path::Path) -> PathBuf {
let canonical = fs::canonicalize(input).unwrap_or_else(|_| input.to_path_buf());
let mut hasher = std::collections::hash_map::DefaultHasher::new();
canonical.hash(&mut hasher);
let hash = hasher.finish();
let stem = input
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("document");
std::env::temp_dir()
.join(format!("mdo-{}", unsafe { libc::geteuid() }))
.join(format!("{hash:016x}"))
.join(format!("{stem}.html"))
}
#[cfg(target_os = "linux")]
fn empty_path_dir(dir: &std::path::Path) -> PathBuf {
let empty = dir.join("empty-path");
fs::create_dir_all(&empty).expect("failed to create empty PATH dir");
empty
}
#[cfg(target_os = "linux")]
#[test]
fn open_launch_failure_exits_nonzero_and_reports_path() {
let dir = fixture_dir("open-launch-failure");
let input = dir.join("sample.md");
fs::write(&input, "# Sample\n\nSome text.\n").expect("failed to write markdown fixture");
let empty_path = empty_path_dir(&dir);
let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
.arg("--open")
.arg(&input)
.env("PATH", &empty_path)
.output()
.expect("failed to run mdo");
assert!(
!output.status.success(),
"mdo --open should exit non-zero when the browser launch fails: {output:?}"
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("Failed to launch browser"),
"stderr should report the launch failure: {stderr}"
);
let rendered_path = temp_output_for_test(&input);
assert!(
stderr.contains(
rendered_path
.to_str()
.expect("rendered path should be valid UTF-8")
),
"stderr should point at the rendered output path {rendered_path:?}: {stderr}"
);
assert!(
rendered_path.exists(),
"rendered output should still exist at {rendered_path:?} after a launch failure"
);
let html = fs::read_to_string(&rendered_path).expect("failed to read rendered output");
assert!(html.contains("<h1>Sample</h1>"));
fs::remove_dir_all(rendered_path.parent().expect("rendered path has a parent"))
.expect("failed to clean up temp render dir");
fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}
#[cfg(target_os = "linux")]
#[test]
fn open_success_exits_zero() {
let dir = fixture_dir("open-launch-success");
let input = dir.join("sample.md");
fs::write(&input, "# Sample\n\nSome text.\n").expect("failed to write markdown fixture");
let fake_bin = dir.join("bin");
fs::create_dir_all(&fake_bin).expect("failed to create fake bin dir");
let fake_xdg_open = fake_bin.join("xdg-open");
fs::write(&fake_xdg_open, "#!/bin/sh\nexit 0\n").expect("failed to write fake xdg-open");
fs::set_permissions(&fake_xdg_open, fs::Permissions::from_mode(0o700))
.expect("failed to chmod fake xdg-open");
let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
.arg("--open")
.arg(&input)
.env("PATH", &fake_bin)
.output()
.expect("failed to run mdo");
assert!(
output.status.success(),
"mdo --open should exit zero when render and launch both succeed: {output:?}"
);
let rendered_path = temp_output_for_test(&input);
assert!(rendered_path.exists());
fs::remove_dir_all(rendered_path.parent().expect("rendered path has a parent"))
.expect("failed to clean up temp render dir");
fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}
#[cfg(target_os = "linux")]
#[test]
fn open_reports_failure_when_opener_exits_nonzero() {
let dir = fixture_dir("open-opener-fails");
let input = dir.join("sample.md");
fs::write(&input, "# Sample\n\nSome text.\n").expect("failed to write markdown fixture");
let fake_bin = dir.join("bin");
fs::create_dir_all(&fake_bin).expect("failed to create fake bin dir");
let fake_xdg_open = fake_bin.join("xdg-open");
fs::write(&fake_xdg_open, "#!/bin/sh\nexit 3\n").expect("failed to write fake xdg-open");
fs::set_permissions(&fake_xdg_open, fs::Permissions::from_mode(0o700))
.expect("failed to chmod fake xdg-open");
let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
.arg("--open")
.arg(&input)
.env("PATH", &fake_bin)
.output()
.expect("failed to run mdo");
assert!(
!output.status.success(),
"mdo --open should exit non-zero when the opener runs but fails: {output:?}"
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("Failed to launch browser"),
"stderr should report the launch failure: {stderr}"
);
let rendered_path = temp_output_for_test(&input);
assert!(
rendered_path.exists(),
"rendered output should survive an opener failure"
);
fs::remove_dir_all(rendered_path.parent().expect("rendered path has a parent"))
.expect("failed to clean up temp render dir");
fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}
#[cfg(unix)]
fn wait_for_file_containing(path: &std::path::Path, needle: &str, timeout: Duration) -> bool {
let start = Instant::now();
loop {
if let Ok(contents) = fs::read_to_string(path) {
if contents.contains(needle) {
return true;
}
}
if start.elapsed() >= timeout {
return false;
}
std::thread::sleep(Duration::from_millis(100));
}
}
#[cfg(unix)]
struct WatchGuard(std::process::Child);
#[cfg(unix)]
impl Drop for WatchGuard {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
#[cfg(unix)]
#[test]
fn watch_survives_atomic_rename() {
use std::process::Stdio;
let dir = fixture_dir("watch-atomic-rename");
let input = dir.join("sample.md");
let output_path = dir.join("sample.html");
let tmp = dir.join("sample.md.tmp");
fs::write(&input, "# Initial\n").expect("failed to write markdown fixture");
let child = Command::new(env!("CARGO_BIN_EXE_mdo"))
.arg("--watch")
.arg(&input)
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.expect("failed to spawn mdo --watch");
let _guard = WatchGuard(child);
assert!(
wait_for_file_containing(&output_path, "Initial", Duration::from_secs(10)),
"initial render should appear within the timeout"
);
for i in 0..3 {
let marker = format!("Rewrite marker {i}");
fs::write(&tmp, format!("# {marker}\n")).expect("failed to write rewrite temp file");
fs::rename(&tmp, &input).expect("failed to atomically rename over the target");
assert!(
wait_for_file_containing(&output_path, &marker, Duration::from_secs(10)),
"rewrite {i} should be re-rendered within the timeout"
);
}
fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}
#[cfg(unix)]
#[test]
fn watch_ignores_sibling_changes() {
use std::process::Stdio;
let dir = fixture_dir("watch-sibling-changes");
let input = dir.join("sample.md");
let output_path = dir.join("sample.html");
let sibling = dir.join("other.md");
fs::write(&input, "# Initial\n").expect("failed to write markdown fixture");
let child = Command::new(env!("CARGO_BIN_EXE_mdo"))
.arg("--watch")
.arg(&input)
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.expect("failed to spawn mdo --watch");
let _guard = WatchGuard(child);
assert!(
wait_for_file_containing(&output_path, "Initial", Duration::from_secs(10)),
"initial render should appear within the timeout"
);
let rendered_before =
fs::read_to_string(&output_path).expect("failed to read initial rendered output");
let mtime_before = fs::metadata(&output_path)
.and_then(|m| m.modified())
.expect("failed to read initial rendered output mtime");
fs::write(&sibling, "# Sibling\n\nUnrelated file.\n")
.expect("failed to write sibling markdown file");
std::thread::sleep(Duration::from_secs(1));
let rendered_after = fs::read_to_string(&output_path)
.expect("failed to read rendered output after sibling change");
let mtime_after = fs::metadata(&output_path)
.and_then(|m| m.modified())
.expect("failed to read rendered output mtime after sibling change");
assert_eq!(
rendered_before, rendered_after,
"watch mode should not re-render sample.html for changes to an unrelated sibling file"
);
assert_eq!(
mtime_before, mtime_after,
"sample.html should not have been rewritten (mtime changed) for a sibling-file change"
);
fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}