Debian Codegraph @

tests/test_search.py

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