Debian Codegraph @

mkdocs/tests/search_tests.py

raw
1 #!/usr/bin/env python
2
3 import json
4 import unittest
5 from unittest import mock
6
7 from mkdocs.config.config_options import ValidationError
8 from mkdocs.contrib import search
9 from mkdocs.contrib.search import search_index
10 from mkdocs.structure.files import File
11 from mkdocs.structure.pages import Page
12 from mkdocs.structure.toc import get_toc
13 from mkdocs.tests.base import dedent, get_markdown_toc, load_config
14
15
16 def strip_whitespace(string):
17 return string.replace("\n", "").replace(" ", "")
18
19
20 class SearchConfigTests(unittest.TestCase):
21 def test_lang_default(self):
22 option = search.LangOption(default=['en'])
23 value = option.validate(None)
24 self.assertEqual(['en'], value)
25
26 def test_lang_str(self):
27 option = search.LangOption()
28 value = option.validate('en')
29 self.assertEqual(['en'], value)
30
31 def test_lang_list(self):
32 option = search.LangOption()
33 value = option.validate(['en'])
34 self.assertEqual(['en'], value)
35
36 def test_lang_multi_list(self):
37 option = search.LangOption()
38 value = option.validate(['en', 'es', 'fr'])
39 self.assertEqual(['en', 'es', 'fr'], value)
40
41 def test_lang_no_default_none(self):
42 option = search.LangOption()
43 value = option.validate(None)
44 self.assertIsNone(value)
45
46 def test_lang_no_default_str(self):
47 option = search.LangOption(default=[])
48 value = option.validate('en')
49 self.assertEqual(['en'], value)
50
51 def test_lang_no_default_list(self):
52 option = search.LangOption(default=[])
53 value = option.validate(['en'])
54 self.assertEqual(['en'], value)
55
56 def test_lang_bad_type(self):
57 option = search.LangOption()
58 with self.assertRaises(ValidationError):
59 option.validate({})
60
61 def test_lang_bad_code(self):
62 option = search.LangOption()
63 value = option.validate(['foo'])
64 self.assertEqual(['en'], value)
65
66 def test_lang_good_and_bad_code(self):
67 option = search.LangOption()
68 value = option.validate(['en', 'foo'])
69 self.assertEqual(['en'], value)
70
71 def test_lang_missing_and_with_territory(self):
72 option = search.LangOption()
73 value = option.validate(['cs_CZ', 'pt_BR', 'fr'])
74 self.assertEqual(['fr', 'en', 'pt'], value)
75
76
77 class SearchPluginTests(unittest.TestCase):
78 def test_plugin_config_defaults(self):
79 expected = {
80 'lang': None,
81 'separator': r'[\s\-]+',
82 'min_search_length': 3,
83 'prebuild_index': False,
84 'indexing': 'full',
85 }
86 plugin = search.SearchPlugin()
87 errors, warnings = plugin.load_config({})
88 self.assertEqual(plugin.config, expected)
89 self.assertEqual(errors, [])
90 self.assertEqual(warnings, [])
91
92 def test_plugin_config_lang(self):
93 expected = {
94 'lang': ['es'],
95 'separator': r'[\s\-]+',
96 'min_search_length': 3,
97 'prebuild_index': False,
98 'indexing': 'full',
99 }
100 plugin = search.SearchPlugin()
101 errors, warnings = plugin.load_config({'lang': 'es'})
102 self.assertEqual(plugin.config, expected)
103 self.assertEqual(errors, [])
104 self.assertEqual(warnings, [])
105
106 def test_plugin_config_separator(self):
107 expected = {
108 'lang': None,
109 'separator': r'[\s\-\.]+',
110 'min_search_length': 3,
111 'prebuild_index': False,
112 'indexing': 'full',
113 }
114 plugin = search.SearchPlugin()
115 errors, warnings = plugin.load_config({'separator': r'[\s\-\.]+'})
116 self.assertEqual(plugin.config, expected)
117 self.assertEqual(errors, [])
118 self.assertEqual(warnings, [])
119
120 def test_plugin_config_min_search_length(self):
121 expected = {
122 'lang': None,
123 'separator': r'[\s\-]+',
124 'min_search_length': 2,
125 'prebuild_index': False,
126 'indexing': 'full',
127 }
128 plugin = search.SearchPlugin()
129 errors, warnings = plugin.load_config({'min_search_length': 2})
130 self.assertEqual(plugin.config, expected)
131 self.assertEqual(errors, [])
132 self.assertEqual(warnings, [])
133
134 def test_plugin_config_prebuild_index(self):
135 expected = {
136 'lang': None,
137 'separator': r'[\s\-]+',
138 'min_search_length': 3,
139 'prebuild_index': True,
140 'indexing': 'full',
141 }
142 plugin = search.SearchPlugin()
143 errors, warnings = plugin.load_config({'prebuild_index': True})
144 self.assertEqual(plugin.config, expected)
145 self.assertEqual(errors, [])
146 self.assertEqual(warnings, [])
147
148 def test_plugin_config_indexing(self):
149 expected = {
150 'lang': None,
151 'separator': r'[\s\-]+',
152 'min_search_length': 3,
153 'prebuild_index': False,
154 'indexing': 'titles',
155 }
156 plugin = search.SearchPlugin()
157 errors, warnings = plugin.load_config({'indexing': 'titles'})
158 self.assertEqual(plugin.config, expected)
159 self.assertEqual(errors, [])
160 self.assertEqual(warnings, [])
161
162 def test_event_on_config_defaults(self):
163 plugin = search.SearchPlugin()
164 plugin.load_config({})
165 result = plugin.on_config(load_config(theme='mkdocs', extra_javascript=[]))
166 self.assertFalse(result['theme']['search_index_only'])
167 self.assertFalse(result['theme']['include_search_page'])
168 self.assertEqual(result['theme'].static_templates, {'404.html', 'sitemap.xml'})
169 self.assertEqual(len(result['theme'].dirs), 3)
170 self.assertEqual(result['extra_javascript'], ['search/main.js'])
171 self.assertEqual(plugin.config.lang, [result['theme']['locale'].language])
172
173 def test_event_on_config_lang(self):
174 plugin = search.SearchPlugin()
175 plugin.load_config({'lang': 'es'})
176 result = plugin.on_config(load_config(theme='mkdocs', extra_javascript=[]))
177 self.assertFalse(result['theme']['search_index_only'])
178 self.assertFalse(result['theme']['include_search_page'])
179 self.assertEqual(result['theme'].static_templates, {'404.html', 'sitemap.xml'})
180 self.assertEqual(len(result['theme'].dirs), 3)
181 self.assertEqual(result['extra_javascript'], ['search/main.js'])
182 self.assertEqual(plugin.config.lang, ['es'])
183
184 def test_event_on_config_theme_locale(self):
185 plugin = search.SearchPlugin()
186 plugin.load_config({})
187 result = plugin.on_config(
188 load_config(theme={'name': 'mkdocs', 'locale': 'fr'}, extra_javascript=[])
189 )
190 self.assertFalse(result['theme']['search_index_only'])
191 self.assertFalse(result['theme']['include_search_page'])
192 self.assertEqual(result['theme'].static_templates, {'404.html', 'sitemap.xml'})
193 self.assertEqual(len(result['theme'].dirs), 3)
194 self.assertEqual(result['extra_javascript'], ['search/main.js'])
195 self.assertEqual(plugin.config.lang, [result['theme']['locale'].language])
196
197 def test_event_on_config_include_search_page(self):
198 plugin = search.SearchPlugin()
199 plugin.load_config({})
200 config = load_config(
201 theme={'name': 'mkdocs', 'include_search_page': True}, extra_javascript=[]
202 )
203 result = plugin.on_config(config)
204 self.assertFalse(result['theme']['search_index_only'])
205 self.assertTrue(result['theme']['include_search_page'])
206 self.assertEqual(
207 result['theme'].static_templates, {'404.html', 'sitemap.xml', 'search.html'}
208 )
209 self.assertEqual(len(result['theme'].dirs), 3)
210 self.assertEqual(result['extra_javascript'], ['search/main.js'])
211
212 def test_event_on_config_search_index_only(self):
213 plugin = search.SearchPlugin()
214 plugin.load_config({})
215 config = load_config(
216 theme={'name': 'mkdocs', 'search_index_only': True}, extra_javascript=[]
217 )
218 result = plugin.on_config(config)
219 self.assertTrue(result['theme']['search_index_only'])
220 self.assertFalse(result['theme']['include_search_page'])
221 self.assertEqual(result['theme'].static_templates, {'404.html', 'sitemap.xml'})
222 self.assertEqual(len(result['theme'].dirs), 2)
223 self.assertEqual(len(result['extra_javascript']), 0)
224
225 @mock.patch('mkdocs.utils.write_file', autospec=True)
226 @mock.patch('mkdocs.utils.copy_file', autospec=True)
227 def test_event_on_post_build_defaults(self, mock_copy_file, mock_write_file):
228 plugin = search.SearchPlugin()
229 plugin.load_config({})
230 config = load_config(theme='mkdocs')
231 plugin.on_config(config)
232 plugin.on_pre_build(config)
233 plugin.on_post_build(config)
234 self.assertEqual(mock_copy_file.call_count, 0)
235 self.assertEqual(mock_write_file.call_count, 1)
236
237 @mock.patch('mkdocs.utils.write_file', autospec=True)
238 @mock.patch('mkdocs.utils.copy_file', autospec=True)
239 def test_event_on_post_build_single_lang(self, mock_copy_file, mock_write_file):
240 plugin = search.SearchPlugin()
241 plugin.load_config({'lang': ['es']})
242 config = load_config(theme='mkdocs')
243 plugin.on_pre_build(config)
244 plugin.on_post_build(config)
245 self.assertEqual(mock_copy_file.call_count, 2)
246 self.assertEqual(mock_write_file.call_count, 1)
247
248 @mock.patch('mkdocs.utils.write_file', autospec=True)
249 @mock.patch('mkdocs.utils.copy_file', autospec=True)
250 def test_event_on_post_build_multi_lang(self, mock_copy_file, mock_write_file):
251 plugin = search.SearchPlugin()
252 plugin.load_config({'lang': ['es', 'fr']})
253 config = load_config(theme='mkdocs')
254 plugin.on_pre_build(config)
255 plugin.on_post_build(config)
256 self.assertEqual(mock_copy_file.call_count, 4)
257 self.assertEqual(mock_write_file.call_count, 1)
258
259 @mock.patch('mkdocs.utils.write_file', autospec=True)
260 @mock.patch('mkdocs.utils.copy_file', autospec=True)
261 def test_event_on_post_build_search_index_only(self, mock_copy_file, mock_write_file):
262 plugin = search.SearchPlugin()
263 plugin.load_config({'lang': ['es']})
264 config = load_config(theme={'name': 'mkdocs', 'search_index_only': True})
265 plugin.on_pre_build(config)
266 plugin.on_post_build(config)
267 self.assertEqual(mock_copy_file.call_count, 0)
268 self.assertEqual(mock_write_file.call_count, 1)
269
270
271 class SearchIndexTests(unittest.TestCase):
272 def test_html_stripping(self):
273 stripper = search_index.ContentParser()
274
275 stripper.feed("<h1>Testing</h1><p>Content</p>")
276
277 self.assertEqual(stripper.stripped_html, "Testing\nContent")
278
279 def test_content_parser(self):
280 parser = search_index.ContentParser()
281
282 parser.feed('<h1 id="title">Title</h1>TEST')
283 parser.close()
284
285 self.assertEqual(
286 parser.data, [search_index.ContentSection(text=["TEST"], id_="title", title="Title")]
287 )
288
289 def test_content_parser_no_id(self):
290 parser = search_index.ContentParser()
291
292 parser.feed("<h1>Title</h1>TEST")
293 parser.close()
294
295 self.assertEqual(
296 parser.data, [search_index.ContentSection(text=["TEST"], id_=None, title="Title")]
297 )
298
299 def test_content_parser_content_before_header(self):
300 parser = search_index.ContentParser()
301
302 parser.feed("Content Before H1 <h1>Title</h1>TEST")
303 parser.close()
304
305 self.assertEqual(
306 parser.data, [search_index.ContentSection(text=["TEST"], id_=None, title="Title")]
307 )
308
309 def test_content_parser_no_sections(self):
310 parser = search_index.ContentParser()
311
312 parser.feed("No H1 or H2<span>Title</span>TEST")
313
314 self.assertEqual(parser.data, [])
315
316 def test_find_toc_by_id(self):
317 """Test finding the relevant TOC item by the tag ID."""
318 index = search_index.SearchIndex()
319
320 md = dedent(
321 """
322 # Heading 1
323 ## Heading 2
324 ### Heading 3
325 """
326 )
327 toc = get_toc(get_markdown_toc(md))
328
329 toc_item = index._find_toc_by_id(toc, "heading-1")
330 self.assertEqual(toc_item.url, "#heading-1")
331 self.assertEqual(toc_item.title, "Heading 1")
332
333 toc_item2 = index._find_toc_by_id(toc, "heading-2")
334 self.assertEqual(toc_item2.url, "#heading-2")
335 self.assertEqual(toc_item2.title, "Heading 2")
336
337 toc_item3 = index._find_toc_by_id(toc, "heading-3")
338 self.assertEqual(toc_item3.url, "#heading-3")
339 self.assertEqual(toc_item3.title, "Heading 3")
340
341 def test_create_search_index(self):
342 html_content = """
343 <h1 id="heading-1">Heading 1</h1>
344 <p>Content 1</p>
345 <h2 id="heading-2">Heading 2</h1>
346 <p>Content 2</p>
347 <h3 id="heading-3">Heading 3</h1>
348 <p>Content 3</p>
349 """
350
351 base_cfg = load_config()
352 pages = [
353 Page(
354 'Home',
355 File('index.md', base_cfg.docs_dir, base_cfg.site_dir, base_cfg.use_directory_urls),
356 base_cfg,
357 ),
358 Page(
359 'About',
360 File('about.md', base_cfg.docs_dir, base_cfg.site_dir, base_cfg.use_directory_urls),
361 base_cfg,
362 ),
363 ]
364
365 md = dedent(
366 """
367 # Heading 1
368 ## Heading 2
369 ### Heading 3
370 """
371 )
372 toc = get_toc(get_markdown_toc(md))
373
374 full_content = ''.join(f"Heading{i}Content{i}" for i in range(1, 4))
375
376 plugin = search.SearchPlugin()
377 errors, warnings = plugin.load_config({})
378
379 for page in pages:
380 # Fake page.read_source() and page.render()
381 page.markdown = md
382 page.toc = toc
383 page.content = html_content
384
385 index = search_index.SearchIndex(**plugin.config)
386 index.add_entry_from_context(page)
387
388 self.assertEqual(len(index._entries), 4)
389
390 loc = page.url
391
392 self.assertEqual(index._entries[0]['title'], page.title)
393 self.assertEqual(strip_whitespace(index._entries[0]['text']), full_content)
394 self.assertEqual(index._entries[0]['location'], loc)
395
396 self.assertEqual(index._entries[1]['title'], "Heading 1")
397 self.assertEqual(index._entries[1]['text'], "Content 1")
398 self.assertEqual(index._entries[1]['location'], f"{loc}#heading-1")
399
400 self.assertEqual(index._entries[2]['title'], "Heading 2")
401 self.assertEqual(strip_whitespace(index._entries[2]['text']), "Content2")
402 self.assertEqual(index._entries[2]['location'], f"{loc}#heading-2")
403
404 self.assertEqual(index._entries[3]['title'], "Heading 3")
405 self.assertEqual(strip_whitespace(index._entries[3]['text']), "Content3")
406 self.assertEqual(index._entries[3]['location'], f"{loc}#heading-3")
407
408 def test_search_indexing_options(self):
409 def test_page(title, filename, config):
410 test_page = Page(
411 title,
412 File(filename, config.docs_dir, config.site_dir, config.use_directory_urls),
413 config,
414 )
415 test_page.content = """
416 <h1 id="heading-1">Heading 1</h1>
417 <p>Content 1</p>
418 <h2 id="heading-2">Heading 2</h1>
419 <p>Content 2</p>
420 <h3 id="heading-3">Heading 3</h1>
421 <p>Content 3</p>"""
422 test_page.markdown = dedent(
423 """
424 # Heading 1
425 ## Heading 2
426 ### Heading 3"""
427 )
428 test_page.toc = get_toc(get_markdown_toc(test_page.markdown))
429 return test_page
430
431 def validate_full(data, page):
432 self.assertEqual(len(data), 4)
433 for x in data:
434 self.assertTrue(x['title'])
435 self.assertTrue(x['text'])
436
437 def validate_sections(data, page):
438 # Sanity
439 self.assertEqual(len(data), 4)
440 # Page
441 self.assertEqual(data[0]['title'], page.title)
442 self.assertFalse(data[0]['text'])
443 # Headings
444 for x in data[1:]:
445 self.assertTrue(x['title'])
446 self.assertFalse(x['text'])
447
448 def validate_titles(data, page):
449 # Sanity
450 self.assertEqual(len(data), 1)
451 for x in data:
452 self.assertFalse(x['text'])
453
454 for option, validate in {
455 'full': validate_full,
456 'sections': validate_sections,
457 'titles': validate_titles,
458 }.items():
459 with self.subTest(option):
460 plugin = search.SearchPlugin()
461
462 # Load plugin config, overriding indexing for test case
463 errors, warnings = plugin.load_config({'indexing': option})
464 self.assertEqual(errors, [])
465 self.assertEqual(warnings, [])
466
467 base_cfg = load_config(plugins=['search'])
468 base_cfg.plugins['search'].config.indexing = option
469
470 pages = [
471 test_page('Home', 'index.md', base_cfg),
472 test_page('About', 'about.md', base_cfg),
473 ]
474
475 for page in pages:
476 index = search_index.SearchIndex(**plugin.config)
477 index.add_entry_from_context(page)
478 data = index.generate_search_index()
479 validate(json.loads(data)['docs'], page)
480
481 @mock.patch('subprocess.Popen', autospec=True)
482 def test_prebuild_index(self, mock_popen):
483 # See https://stackoverflow.com/a/36501078/866026
484 mock_popen.return_value = mock.Mock()
485 mock_popen_obj = mock_popen.return_value
486 mock_popen_obj.communicate.return_value = ('{"mock": "index"}', None)
487 mock_popen_obj.returncode = 0
488
489 index = search_index.SearchIndex(prebuild_index=True)
490 expected = {
491 'docs': [],
492 'config': {'prebuild_index': True},
493 'index': {'mock': 'index'},
494 }
495 result = json.loads(index.generate_search_index())
496 self.assertEqual(mock_popen.call_count, 1)
497 self.assertEqual(mock_popen_obj.communicate.call_count, 1)
498 self.assertEqual(result, expected)
499
500 @mock.patch('subprocess.Popen', autospec=True)
501 def test_prebuild_index_returns_error(self, mock_popen):
502 # See https://stackoverflow.com/a/36501078/866026
503 mock_popen.return_value = mock.Mock()
504 mock_popen_obj = mock_popen.return_value
505 mock_popen_obj.communicate.return_value = ('', 'Some Error')
506 mock_popen_obj.returncode = 0
507
508 index = search_index.SearchIndex(prebuild_index=True)
509 expected = {
510 'docs': [],
511 'config': {'prebuild_index': True},
512 }
513 with self.assertLogs('mkdocs') as cm:
514 result = json.loads(index.generate_search_index())
515 self.assertEqual(
516 '\n'.join(cm.output),
517 'WARNING:mkdocs.contrib.search.search_index:Failed to pre-build search index. Error: Some Error',
518 )
519
520 self.assertEqual(mock_popen.call_count, 1)
521 self.assertEqual(mock_popen_obj.communicate.call_count, 1)
522 self.assertEqual(result, expected)
523
524 @mock.patch('subprocess.Popen', autospec=True)
525 def test_prebuild_index_raises_ioerror(self, mock_popen):
526 # See https://stackoverflow.com/a/36501078/866026
527 mock_popen.return_value = mock.Mock()
528 mock_popen_obj = mock_popen.return_value
529 mock_popen_obj.communicate.side_effect = OSError
530 mock_popen_obj.returncode = 1
531
532 index = search_index.SearchIndex(prebuild_index=True)
533 expected = {
534 'docs': [],
535 'config': {'prebuild_index': True},
536 }
537 with self.assertLogs('mkdocs') as cm:
538 result = json.loads(index.generate_search_index())
539 self.assertEqual(
540 '\n'.join(cm.output),
541 'WARNING:mkdocs.contrib.search.search_index:Failed to pre-build search index. Error: ',
542 )
543
544 self.assertEqual(mock_popen.call_count, 1)
545 self.assertEqual(mock_popen_obj.communicate.call_count, 1)
546 self.assertEqual(result, expected)
547
548 @mock.patch('subprocess.Popen', autospec=True, side_effect=OSError)
549 def test_prebuild_index_raises_oserror(self, mock_popen):
550 # See https://stackoverflow.com/a/36501078/866026
551 mock_popen.return_value = mock.Mock()
552 mock_popen_obj = mock_popen.return_value
553 mock_popen_obj.communicate.return_value = ('foo', 'bar')
554 mock_popen_obj.returncode = 0
555
556 index = search_index.SearchIndex(prebuild_index=True)
557 expected = {
558 'docs': [],
559 'config': {'prebuild_index': True},
560 }
561 with self.assertLogs('mkdocs') as cm:
562 result = json.loads(index.generate_search_index())
563 self.assertEqual(
564 '\n'.join(cm.output),
565 'WARNING:mkdocs.contrib.search.search_index:Failed to pre-build search index. Error: ',
566 )
567
568 self.assertEqual(mock_popen.call_count, 1)
569 self.assertEqual(mock_popen_obj.communicate.call_count, 0)
570 self.assertEqual(result, expected)
571
572 @mock.patch('subprocess.Popen', autospec=True)
573 def test_prebuild_index_false(self, mock_popen):
574 # See https://stackoverflow.com/a/36501078/866026
575 mock_popen.return_value = mock.Mock()
576 mock_popen_obj = mock_popen.return_value
577 mock_popen_obj.communicate.return_value = ('', '')
578 mock_popen_obj.returncode = 0
579
580 index = search_index.SearchIndex(prebuild_index=False)
581 expected = {
582 'docs': [],
583 'config': {'prebuild_index': False},
584 }
585 result = json.loads(index.generate_search_index())
586 self.assertEqual(mock_popen.call_count, 0)
587 self.assertEqual(mock_popen_obj.communicate.call_count, 0)
588 self.assertEqual(result, expected)
589
590 @unittest.skipUnless(search_index.haslunrpy, 'lunr.py is not installed')
591 @mock.patch('mkdocs.contrib.search.search_index.lunr', autospec=True)
592 def test_prebuild_index_python(self, mock_lunr):
593 mock_lunr.return_value.serialize.return_value = {'mock': 'index'}
594 index = search_index.SearchIndex(prebuild_index='python', lang='en')
595 expected = {
596 'docs': [],
597 'config': {'prebuild_index': 'python', 'lang': 'en'},
598 'index': {'mock': 'index'},
599 }
600 result = json.loads(index.generate_search_index())
601 self.assertEqual(mock_lunr.call_count, 1)
602 self.assertEqual(result, expected)
603
604 @unittest.skipIf(search_index.haslunrpy, 'lunr.py is installed')
605 def test_prebuild_index_python_missing_lunr(self):
606 # When the lunr.py dependencies are not installed no prebuilt index is created.
607 index = search_index.SearchIndex(prebuild_index='python', lang='en')
608 expected = {
609 'docs': [],
610 'config': {'prebuild_index': 'python', 'lang': 'en'},
611 }
612 with self.assertLogs('mkdocs', level='WARNING'):
613 result = json.loads(index.generate_search_index())
614 self.assertEqual(result, expected)
615
616 @mock.patch('subprocess.Popen', autospec=True)
617 def test_prebuild_index_node(self, mock_popen):
618 # See https://stackoverflow.com/a/36501078/866026
619 mock_popen.return_value = mock.Mock()
620 mock_popen_obj = mock_popen.return_value
621 mock_popen_obj.communicate.return_value = ('{"mock": "index"}', None)
622 mock_popen_obj.returncode = 0
623
624 index = search_index.SearchIndex(prebuild_index='node')
625 expected = {
626 'docs': [],
627 'config': {'prebuild_index': 'node'},
628 'index': {'mock': 'index'},
629 }
630 result = json.loads(index.generate_search_index())
631 self.assertEqual(mock_popen.call_count, 1)
632 self.assertEqual(mock_popen_obj.communicate.call_count, 1)
633 self.assertEqual(result, expected)