Debian Codegraph @

tests/test_search.py

raw ◀ ▶
1 Debian patch touch this file
1 """Test the search index builder."""
2
3 from __future__ import annotations
4
5 import json
6 from io import BytesIO
7 from typing import TYPE_CHECKING
8
9 import pytest
10 from docutils import frontend, utils
11 from docutils.parsers import rst
12
13 from sphinx.search import IndexBuilder
14
15 from tests.utils import TESTS_ROOT
16
17 if TYPE_CHECKING:
18 from collections.abc import Iterable, Iterator
19 from pathlib import Path
20 from typing import Any
21
22 from sphinx.domains import ObjType
23 from sphinx.testing.util import SphinxTestApp
24
25 JAVASCRIPT_TEST_ROOTS = [
26 directory
27 for directory in (TESTS_ROOT / 'js' / 'roots').iterdir()
28 if (directory / 'conf.py').exists()
29 ]
30
31
32 class DummyDomainsContainer:
33 def __init__(self, **domains: DummyDomain) -> None:
34 self._domain_instances = domains
35
36 def sorted(self) -> Iterator[DummyDomain]:
37 for _domain_name, domain in sorted(self._domain_instances.items()):
38 yield domain
39
40
41 class DummyEnvironment:
42 def __init__(self, version: str, domains: DummyDomainsContainer) -> None:
43 self.version = version
44 self.domains = domains
45
46 def __getattr__(self, name: str) -> Any:
47 if name.startswith('_search_index_'):
48 setattr(self, name, {})
49 return getattr(self, name, {})
50
51 def __str__(self) -> str:
52 return f'DummyEnvironment({self.version!r}, {self.domains!r})'
53
54
55 class DummyDomain:
56 def __init__(
57 self, name: str, data: Iterable[tuple[str, str, str, str, str, int]]
58 ) -> None:
59 self.name = name
60 self.data = data
61 self.object_types: dict[str, ObjType] = {}
62
63 def get_objects(self) -> Iterable[tuple[str, str, str, str, str, int]]:
64 return self.data
65
66
67 def load_searchindex(path: Path) -> Any:
68 searchindex = path.read_text(encoding='utf8')
69 assert searchindex.startswith('Search.setIndex(')
70 assert searchindex.endswith(')')
71
72 return json.loads(searchindex[16:-1])
73
74
75 def is_registered_term(index: Any, keyword: str) -> bool:
76 return index['terms'].get(keyword, []) != []
77
78
•79 def is_registered_prefix(index: Any, prefix: str) -> bool:
80 terms = index['terms']
81 return any(k.startswith(prefix) and v != [] for k, v in terms.items())
82
83
84 FILE_CONTENTS = """\
85 section_title
86 =============
87
88 .. test that comments are not indexed: boson
89
90 another_title
91 =============
92
93 test that non-comments are indexed: fermion
94 """
95
96
97 @pytest.mark.sphinx('html', testroot='ext-viewcode')
98 def test_objects_are_escaped(app: SphinxTestApp) -> None:
99 app.build(force_all=True)
100 index = load_searchindex(app.outdir / 'searchindex.js')
101 for item in index.get('objects').get(''):
102 if item[-1] == 'n::Array&lt;T, d&gt;': # n::Array<T,d> is escaped
103 break
104 else:
105 raise AssertionError(index.get('objects').get(''))
106
107
108 @pytest.mark.sphinx('html', testroot='search')
109 def test_meta_keys_are_handled_for_language_en(app: SphinxTestApp) -> None:
110 app.build(force_all=True)
111 searchindex = load_searchindex(app.outdir / 'searchindex.js')
112 assert not is_registered_term(searchindex, 'thisnoteith')
113 assert is_registered_term(searchindex, 'thisonetoo')
114 assert is_registered_term(searchindex, 'findthiskey')
115 assert is_registered_term(searchindex, 'thistoo')
116 assert not is_registered_term(searchindex, 'onlygerman')
117 assert is_registered_term(searchindex, 'notgerman')
118 assert not is_registered_term(searchindex, 'onlytoogerman')
119
120
121 @pytest.mark.sphinx(
122 'html',
123 testroot='search',
124 confoverrides={'html_search_language': 'de'},
125 freshenv=True,
126 )
127 def test_meta_keys_are_handled_for_language_de(app: SphinxTestApp) -> None:
128 app.build(force_all=True)
129 searchindex = load_searchindex(app.outdir / 'searchindex.js')
130 assert not is_registered_term(searchindex, 'thisnoteith')
131 assert is_registered_term(searchindex, 'thisonetoo')
132 assert not is_registered_term(searchindex, 'findthiskey')
133 assert not is_registered_term(searchindex, 'thistoo')
134 assert is_registered_term(searchindex, 'onlygerman')
135 assert not is_registered_term(searchindex, 'notgerman')
136 assert is_registered_term(searchindex, 'onlytoogerman')
137
138
139 @pytest.mark.sphinx('html', testroot='search')
140 def test_stemmer_does_not_remove_short_words(app: SphinxTestApp) -> None:
141 app.build(force_all=True)
142 searchindex = (app.outdir / 'searchindex.js').read_text(encoding='utf8')
143 assert 'bat' in searchindex
144
145
146 @pytest.mark.sphinx('html', testroot='search')
147 def test_stemmer(app: SphinxTestApp) -> None:
148 app.build(force_all=True)
149 searchindex = load_searchindex(app.outdir / 'searchindex.js')
150 print(searchindex)
151 assert is_registered_term(searchindex, 'findthisstemmedkey')
•152 assert is_registered_prefix(searchindex, 'intern')
153
154
155 @pytest.mark.sphinx('html', testroot='search')
156 def test_term_in_heading_and_section(app: SphinxTestApp) -> None:
157 app.build(force_all=True)
158 searchindex = (app.outdir / 'searchindex.js').read_text(encoding='utf8')
159 # if search term is in the title of one doc and in the text of another
160 # both documents should be a hit in the search index as a title,
161 # respectively text hit
162 assert '"textinhead":3' in searchindex
163 assert '"textinhead":1' in searchindex
164
165
166 @pytest.mark.sphinx('html', testroot='search')
167 def test_escaped_title(app: SphinxTestApp) -> None:
168 app.build(force_all=True)
169 searchindex = load_searchindex(app.outdir / 'searchindex.js')
170 print(searchindex)
171 assert 'escapedtitle' in searchindex['docnames']
172 assert 'escaped title with < and > in it' in searchindex['titles']
173
174
175 @pytest.mark.sphinx('html', testroot='search')
176 def test_term_in_raw_directive(app: SphinxTestApp) -> None:
177 app.build(force_all=True)
178 searchindex = load_searchindex(app.outdir / 'searchindex.js')
179 assert not is_registered_term(searchindex, 'raw')
180 assert is_registered_term(searchindex, 'rawword')
181 assert not is_registered_term(searchindex, 'latex_keyword')
182
183
184 def test_IndexBuilder():
185 settings = frontend.get_default_settings(rst.Parser)
186 parser = rst.Parser()
187
188 domain1 = DummyDomain(
189 'dummy1',
190 [
191 ('objname1', 'objdispname1', 'objtype1', 'docname1_1', '#anchor', 1),
192 ('objname2', 'objdispname2', 'objtype2', 'docname1_2', '', -1),
193 ],
194 )
195 domain2 = DummyDomain(
196 'dummy2',
197 [
198 ('objname1', 'objdispname1', 'objtype1', 'docname2_1', '#anchor', 1),
199 ('objname2', 'objdispname2', 'objtype2', 'docname2_2', '', -1),
200 ],
201 )
202 env = DummyEnvironment('1.0', DummyDomainsContainer(dummy1=domain1, dummy2=domain2))
203 doc = utils.new_document('test data', settings)
204 doc['file'] = 'dummy'
205 parser.parse(FILE_CONTENTS, doc)
206
207 # feed
208 index = IndexBuilder(env, 'en', {}, '')
209 index.feed('docname1_1', 'filename1_1', 'title1_1', doc)
210 index.feed('docname1_2', 'filename1_2', 'title1_2', doc)
211 index.feed('docname2_2', 'filename2_2', 'title2_2', doc)
212 index.feed('docname2_1', 'filename2_1', 'title2_1', doc)
213 assert index._titles == {
214 'docname1_1': 'title1_1',
215 'docname1_2': 'title1_2',
216 'docname2_1': 'title2_1',
217 'docname2_2': 'title2_2',
218 }
219 assert index._filenames == {
220 'docname1_1': 'filename1_1',
221 'docname1_2': 'filename1_2',
222 'docname2_1': 'filename2_1',
223 'docname2_2': 'filename2_2',
224 }
225 # note: element iteration order (sort order) is important when the index
226 # is frozen (serialized) during build -- however, the _mapping-related
227 # dictionaries below may be iterated in arbitrary order by Python at
228 # runtime.
229 assert index._mapping == {
230 'fermion': {'docname1_1', 'docname1_2', 'docname2_1', 'docname2_2'},
231 'comment': {'docname1_1', 'docname1_2', 'docname2_1', 'docname2_2'},
232 'non': {'docname1_1', 'docname1_2', 'docname2_1', 'docname2_2'},
233 'index': {'docname1_1', 'docname1_2', 'docname2_1', 'docname2_2'},
234 'test': {'docname1_1', 'docname1_2', 'docname2_1', 'docname2_2'},
235 }
236 assert index._title_mapping == {
237 'another_titl': {'docname1_1', 'docname1_2', 'docname2_1', 'docname2_2'},
238 'section_titl': {'docname1_1', 'docname1_2', 'docname2_1', 'docname2_2'},
239 }
240 assert index._objtypes == {}
241 assert index._objnames == {}
242
243 # freeze
244 assert index.freeze() == {
245 'docnames': ('docname1_1', 'docname1_2', 'docname2_1', 'docname2_2'),
246 'envversion': '1.0',
247 'filenames': ['filename1_1', 'filename1_2', 'filename2_1', 'filename2_2'],
248 'objects': {
249 '': [
250 (0, 0, 1, '#anchor', 'objdispname1'),
251 (2, 1, 1, '#anchor', 'objdispname1'),
252 ]
253 },
254 'objnames': {
255 0: ('dummy1', 'objtype1', 'objtype1'),
256 1: ('dummy2', 'objtype1', 'objtype1'),
257 },
258 'objtypes': {0: 'dummy1:objtype1', 1: 'dummy2:objtype1'},
259 'terms': {
260 'comment': [0, 1, 2, 3],
261 'fermion': [0, 1, 2, 3],
262 'index': [0, 1, 2, 3],
263 'non': [0, 1, 2, 3],
264 'test': [0, 1, 2, 3],
265 },
266 'titles': ('title1_1', 'title1_2', 'title2_1', 'title2_2'),
267 'titleterms': {
268 'another_titl': [0, 1, 2, 3],
269 'section_titl': [0, 1, 2, 3],
270 },
271 'alltitles': {
272 'another_title': [
273 (0, 'another-title'),
274 (1, 'another-title'),
275 (2, 'another-title'),
276 (3, 'another-title'),
277 ],
278 'section_title': [(0, None), (1, None), (2, None), (3, None)],
279 },
280 'indexentries': {},
281 }
282 assert index._objtypes == {('dummy1', 'objtype1'): 0, ('dummy2', 'objtype1'): 1}
283 assert index._objnames == {
284 0: ('dummy1', 'objtype1', 'objtype1'),
285 1: ('dummy2', 'objtype1', 'objtype1'),
286 }
287
288 env = DummyEnvironment('1.0', DummyDomainsContainer(dummy1=domain1, dummy2=domain2))
289
290 # dump / load
291 stream = BytesIO()
292 index.dump(stream, 'pickle')
293 stream.seek(0)
294
295 index2 = IndexBuilder(env, 'en', {}, '')
296 index2.load(stream, 'pickle')
297
298 assert index2._titles == index._titles
299 assert index2._filenames == index._filenames
300 assert index2._mapping == index._mapping
301 assert index2._title_mapping == index._title_mapping
302 assert index2._objtypes == {}
303 assert index2._objnames == {}
304
305 # freeze after load
306 assert index2.freeze() == index.freeze()
307 assert index2._objtypes == index._objtypes
308 assert index2._objnames == index._objnames
309
310 # prune
311 index.prune(['docname1_2', 'docname2_2'])
312 assert index._titles == {'docname1_2': 'title1_2', 'docname2_2': 'title2_2'}
313 assert index._filenames == {
314 'docname1_2': 'filename1_2',
315 'docname2_2': 'filename2_2',
316 }
317 assert index._mapping == {
318 'fermion': {'docname1_2', 'docname2_2'},
319 'comment': {'docname1_2', 'docname2_2'},
320 'non': {'docname1_2', 'docname2_2'},
321 'index': {'docname1_2', 'docname2_2'},
322 'test': {'docname1_2', 'docname2_2'},
323 }
324 assert index._title_mapping == {
325 'another_titl': {'docname1_2', 'docname2_2'},
326 'section_titl': {'docname1_2', 'docname2_2'},
327 }
328 assert index._objtypes == {('dummy1', 'objtype1'): 0, ('dummy2', 'objtype1'): 1}
329 assert index._objnames == {
330 0: ('dummy1', 'objtype1', 'objtype1'),
331 1: ('dummy2', 'objtype1', 'objtype1'),
332 }
333
334 # freeze after prune
335 assert index.freeze() == {
336 'docnames': ('docname1_2', 'docname2_2'),
337 'envversion': '1.0',
338 'filenames': ['filename1_2', 'filename2_2'],
339 'objects': {},
340 'objnames': {
341 0: ('dummy1', 'objtype1', 'objtype1'),
342 1: ('dummy2', 'objtype1', 'objtype1'),
343 },
344 'objtypes': {0: 'dummy1:objtype1', 1: 'dummy2:objtype1'},
345 'terms': {
346 'comment': [0, 1],
347 'fermion': [0, 1],
348 'index': [0, 1],
349 'non': [0, 1],
350 'test': [0, 1],
351 },
352 'titles': ('title1_2', 'title2_2'),
353 'titleterms': {
354 'another_titl': [0, 1],
355 'section_titl': [0, 1],
356 },
357 'alltitles': {
358 'another_title': [(0, 'another-title'), (1, 'another-title')],
359 'section_title': [(0, None), (1, None)],
360 },
361 'indexentries': {},
362 }
363 assert index._objtypes == {('dummy1', 'objtype1'): 0, ('dummy2', 'objtype1'): 1}
364 assert index._objnames == {
365 0: ('dummy1', 'objtype1', 'objtype1'),
366 1: ('dummy2', 'objtype1', 'objtype1'),
367 }
368
369
370 def test_IndexBuilder_lookup():
371 env = DummyEnvironment('1.0', {})
372
373 # zh
374 index = IndexBuilder(env, 'zh', {}, '')
375 assert index.lang.lang == 'zh'
376
377 # zh_CN
378 index = IndexBuilder(env, 'zh_CN', {}, '')
379 assert index.lang.lang == 'zh'
380
381
382 @pytest.mark.sphinx(
383 'html',
384 testroot='search',
385 confoverrides={'html_search_language': 'zh'},
386 srcdir='search_zh',
387 )
388 def test_search_index_gen_zh(app: SphinxTestApp) -> None:
389 app.build(force_all=True)
390 index = load_searchindex(app.outdir / 'searchindex.js')
391 assert 'chinesetest ' not in index['terms']
392 assert 'chinesetest' in index['terms']
393 assert 'chinesetesttwo' in index['terms']
394 assert 'cas' in index['terms']
395
396
397 @pytest.mark.sphinx(
398 'html',
399 testroot='search',
400 freshenv=True,
401 )
402 def test_nosearch(app: SphinxTestApp) -> None:
403 app.build()
404 index = load_searchindex(app.outdir / 'searchindex.js')
405 assert index['docnames'] == ['escapedtitle', 'index', 'nosearch', 'tocitem']
406 # latex is in 'nosearch.rst', and nowhere else
407 assert 'latex' not in index['terms']
408 # cat is in 'index.rst' but is marked with the 'no-search' class
409 assert 'cat' not in index['terms']
410 # bat is indexed from 'index.rst' and 'tocitem.rst' (document IDs 0, 2), and
411 # not from 'nosearch.rst' (document ID 1)
412 assert 'bat' in index['terms']
413 assert index['terms']['bat'] == [1, 3]
414
415
416 @pytest.mark.sphinx(
417 'html',
418 testroot='search',
419 parallel=3,
420 freshenv=True,
421 )
422 def test_parallel(app: SphinxTestApp) -> None:
423 app.build()
424 index = load_searchindex(app.outdir / 'searchindex.js')
425 assert index['docnames'] == ['escapedtitle', 'index', 'nosearch', 'tocitem']
426
427
428 @pytest.mark.sphinx('html', testroot='search')
429 def test_search_index_is_deterministic(app: SphinxTestApp) -> None:
430 app.build(force_all=True)
431 index = load_searchindex(app.outdir / 'searchindex.js')
432 # Pretty print the index. Only shown by pytest on failure.
433 print(f'searchindex.js contents:\n\n{json.dumps(index, indent=2)}')
434 assert_is_sorted(index, '')
435
436
437 def is_title_tuple_type(item: list[int | str]) -> bool:
438 """In the search index, titles inside .alltitles are stored as a tuple of
439 (document_idx, title_anchor). Tuples are represented as lists in JSON,
440 but their contents must not be sorted. We cannot sort them anyway, as
441 document_idx is an int and title_anchor is a str.
442 """
443 return len(item) == 2 and isinstance(item[0], int) and isinstance(item[1], str)
444
445
446 def assert_is_sorted(
447 item: dict[str, str] | list[int | str] | int | str, path: str
448 ) -> None:
449 lists_not_to_sort = {
450 # Each element of .titles is related to the element of .docnames in the same position.
451 # The ordering is deterministic because .docnames is sorted.
452 '.titles',
453 # Each element of .filenames is related to the element of .docnames in the same position.
454 # The ordering is deterministic because .docnames is sorted.
455 '.filenames',
456 }
457
458 err_path = path or '<root>'
459 if isinstance(item, dict):
460 assert list(item.keys()) == sorted(item.keys()), f'{err_path} is not sorted'
461 for key, value in item.items():
462 assert_is_sorted(value, f'{path}.{key}')
463 elif isinstance(item, list):
464 if not is_title_tuple_type(item) and path not in lists_not_to_sort:
465 # sort nulls last; http://stackoverflow.com/questions/19868767/
466 assert item == sorted(item, key=lambda x: (x is None, x)), (
467 f'{err_path} is not sorted'
468 )
469 for i, child in enumerate(item):
470 assert_is_sorted(child, f'{path}[{i}]')
471
472
473 @pytest.mark.parametrize('directory', JAVASCRIPT_TEST_ROOTS, ids=lambda p: p.name)
474 def test_check_js_search_indexes(make_app, sphinx_test_tempdir, directory):
475 app = make_app(
476 'html',
477 srcdir=directory,
478 builddir=sphinx_test_tempdir / directory.name,
479 )
480 app.build()
481
482 fresh_searchindex = app.outdir / 'searchindex.js'
483 existing_searchindex = (
484 TESTS_ROOT / 'js' / 'fixtures' / directory.name / 'searchindex.js'
485 )
486
487 msg = (
488 f'Search index fixture {existing_searchindex} does not match regenerated copy.'
489 )
490 assert fresh_searchindex.read_bytes() == existing_searchindex.read_bytes(), msg