mdbook/tests/testsuite/redirects.rs
Eric Huss 15c93b56ed Add support for fragment redirects
This adds the ability to redirect URLs with `#` fragments. This is
useful when section headers get renamed or moved to other pages.

This works both for deleted pages and existing pages.

The implementation requires the use of JavaScript in order to manipulate
the location. (Ideally this would be handled on the server side.)

This also makes it so that deleted page redirects preserve the fragment
ID. Previously if you had a deleted page redirect, and the user went to
something like `page.html#foo`, it would redirect to `bar.html` without
the fragment. I think preserving the fragment is probably a better
behavior. If the new page doesn't have the fragment ID, then no harm is
really done. This is technically an open redirect, but I don't think
that there is too much danger with preserving a fragment ID?
2025-07-08 15:37:46 -07:00

49 lines
1.8 KiB
Rust

//! Tests for the HTML redirect feature.
use crate::prelude::*;
use snapbox::file;
// Basic check of redirects.
#[test]
fn redirects_are_emitted_correctly() {
BookTest::from_dir("redirects/redirects_are_emitted_correctly")
.check_file(
"book/overview.html",
file!["redirects/redirects_are_emitted_correctly/expected/overview.html"],
)
.check_file(
"book/nested/page.html",
file!["redirects/redirects_are_emitted_correctly/expected/nested/page.html"],
);
}
// Invalid redirect with only fragments.
#[test]
fn redirect_removed_with_fragments_only() {
BookTest::from_dir("redirects/redirect_removed_with_fragments_only").run("build", |cmd| {
cmd.expect_failure().expect_stderr(str![[r#"
[TIMESTAMP] [INFO] (mdbook::book): Book building has started
[TIMESTAMP] [INFO] (mdbook::book): Running the html backend
[TIMESTAMP] [ERROR] (mdbook::utils): Error: Rendering failed
[TIMESTAMP] [ERROR] (mdbook::utils): [TAB]Caused By: Unable to emit redirects
[TIMESTAMP] [ERROR] (mdbook::utils): [TAB]Caused By: redirect entry for `old-file.html` only has source paths with `#` fragments
There must be an entry without the `#` fragment to determine the default destination.
"#]]);
});
}
// Invalid redirect for an existing page.
#[test]
fn redirect_existing_page() {
BookTest::from_dir("redirects/redirect_existing_page").run("build", |cmd| {
cmd.expect_failure().expect_stderr(str![[r#"
[TIMESTAMP] [INFO] (mdbook::book): Book building has started
[TIMESTAMP] [INFO] (mdbook::book): Running the html backend
[TIMESTAMP] [ERROR] (mdbook::utils): Error: Rendering failed
[TIMESTAMP] [ERROR] (mdbook::utils): [TAB]Caused By: redirect found for existing chapter at `/chapter_1.html`
Either delete the redirect or remove the chapter.
"#]]);
});
}