Debian Codegraph @

tests/testsuite/search.rs

raw
1 //! Tests for search support.
2
3 use crate::prelude::*;
4 use mdbook_core::book::{BookItem, Chapter};
5 use snapbox::file;
6 use std::path::Path;
7
8 fn read_book_index(root: &Path) -> serde_json::Value {
9 let index_path = glob_one(root, "book/searchindex*.js");
10 let index = read_to_string(&index_path);
11 let index =
12 index.trim_start_matches("window.search = Object.assign(window.search, JSON.parse('");
13 let index = index.trim_end_matches("'));");
14 // We need unescape the string as it's supposed to be an escaped JS string.
15 serde_json::from_str(&index.replace("\\'", "'").replace("\\\\", "\\")).unwrap()
16 }
17
18 // Some spot checks for the generation of the search index.
19 #[test]
20 fn reasonable_search_index() {
21 let mut test = BookTest::from_dir("search/reasonable_search_index");
22 test.build();
23 let index = read_book_index(&test.dir);
24
25 let doc_urls = index["doc_urls"].as_array().unwrap();
26 eprintln!("doc_urls={doc_urls:#?}",);
27 let get_doc_ref = |url: &str| -> String {
28 doc_urls
29 .iter()
30 .position(|s| s == url)
31 .unwrap_or_else(|| panic!("failed to find {url}"))
32 .to_string()
33 };
34
35 let first_chapter = get_doc_ref("first/index.html#first-chapter");
36 let introduction = get_doc_ref("intro.html#introduction");
37 let some_section = get_doc_ref("first/index.html#some-section");
38 let summary = get_doc_ref("first/includes.html#summary");
39 let no_headers = get_doc_ref("first/no-headers.html");
40 let duplicate_headers_1 = get_doc_ref("first/duplicate-headers.html#header-text-1");
41 let heading_attrs = get_doc_ref("first/heading-attributes.html#both");
42 let sneaky = get_doc_ref("intro.html#sneaky");
43
44 let bodyidx = &index["index"]["index"]["body"]["root"];
45 let textidx = &bodyidx["t"]["e"]["x"]["t"];
46 assert_eq!(textidx["df"], 5);
47 assert_eq!(textidx["docs"][&first_chapter]["tf"], 1.0);
48 assert_eq!(textidx["docs"][&introduction]["tf"], 1.0);
49
50 let docs = &index["index"]["documentStore"]["docs"];
51 assert_eq!(docs[&first_chapter]["body"], "more text.");
52 assert_eq!(docs[&some_section]["body"], "");
53 assert_eq!(
54 docs[&summary]["body"],
55 "Introduction First Chapter Includes Unicode No Headers Duplicate Headers Heading Attributes"
56 );
57 assert_eq!(
58 docs[&summary]["breadcrumbs"],
59 "First Chapter » Includes » Summary"
60 );
61 // See note about InlineHtml in search.rs. Ideally the `alert()` part
62 // should not be in the index, but we don't have a way to scrub inline
63 // html.
64 assert_eq!(
65 docs[&sneaky]["body"],
66 "I put <HTML> in here! Sneaky inline event . But regular inline is indexed."
67 );
68 assert_eq!(
69 docs[&no_headers]["breadcrumbs"],
70 "First Chapter » No Headers"
71 );
72 assert_eq!(
73 docs[&duplicate_headers_1]["breadcrumbs"],
74 "First Chapter » Duplicate Headers » Header Text"
75 );
76 assert_eq!(
77 docs[&no_headers]["body"],
78 "Capybara capybara capybara. Capybara capybara capybara. ThisLongWordIsIncludedSoWeCanCheckThatSufficientlyLongWordsAreOmittedFromTheSearchIndex."
79 );
80 assert_eq!(
81 docs[&heading_attrs]["breadcrumbs"],
82 "First Chapter » Heading Attributes » Heading with id and classes"
83 );
84 }
85
86 // This test is here to catch any unexpected changes to the search index.
87 #[test]
88 fn search_index_hasnt_changed_accidentally() {
89 BookTest::from_dir("search/reasonable_search_index").check_file(
90 "book/searchindex*.js",
91 file!["search/reasonable_search_index/expected_index.js"],
92 );
93 }
94
95 // Ability to disable search chapters.
96 #[test]
97 fn can_disable_individual_chapters() {
98 let mut test = BookTest::from_dir("search/disable_search_chapter");
99 test.build();
100 let index = read_book_index(&test.dir);
101 let doc_urls = index["doc_urls"].as_array().unwrap();
102 let contains = |path| {
103 doc_urls
104 .iter()
105 .any(|p| p.as_str().unwrap().starts_with(path))
106 };
107 assert!(contains("second.html"));
108 assert!(!contains("second/"));
109 assert!(!contains("first/disable_me.html"));
110 assert!(contains("first/keep_me.html"));
111 }
112
113 // Test for a regression where search would fail if source_path is None.
114 // https://github.com/rust-lang/mdBook/pull/2550
115 #[test]
116 fn with_no_source_path() {
117 let test = BookTest::from_dir("search/reasonable_search_index");
118 let mut book = test.load_book();
119 let chapter = Chapter::new("Sample chapter", String::new(), "sample.html", vec![]);
120 book.book.items.push(BookItem::Chapter(chapter));
121 book.build().unwrap();
122 }
123
124 // Checks that invalid settings in search chapter is rejected.
125 #[test]
126 fn chapter_settings_validation_error() {
127 BookTest::from_dir("search/chapter_settings_validation_error").run("build", |cmd| {
128 cmd.expect_failure().expect_stderr(str![[r#"
129 INFO Book building has started
130 INFO Running the html backend
131 ERROR Rendering failed
132 [TAB]Caused by: [output.html.search.chapter] key `does-not-exist` does not match any chapter paths
133
134 "#]]);
135 });
136 }