Debian Codegraph @

mkdocs/tests/utils/utils_tests.py

raw
1 #!/usr/bin/env python
2
3 import dataclasses
4 import datetime
5 import logging
6 import os
7 import posixpath
8 import stat
9 import unittest
10 from unittest import mock
11
12 from mkdocs import exceptions, utils
13 from mkdocs.tests.base import dedent, tempdir
14 from mkdocs.utils import meta
15
16 BASEYML = """
17 INHERIT: parent.yml
18 foo: bar
19 baz:
20 sub1: replaced
21 sub3: new
22 deep1:
23 deep2-1:
24 deep3-1: replaced
25 """
26 PARENTYML = """
27 foo: foo
28 baz:
29 sub1: 1
30 sub2: 2
31 deep1:
32 deep2-1:
33 deep3-1: foo
34 deep3-2: bar
35 deep2-2: baz
36 """
37
38
39 class UtilsTests(unittest.TestCase):
40 def test_is_markdown_file(self):
41 expected_results = {
42 'index.md': True,
43 'index.markdown': True,
44 'index.MARKDOWN': False,
45 'index.txt': False,
46 'indexmd': False,
47 }
48 for path, expected_result in expected_results.items():
49 with self.subTest(path):
50 is_markdown = utils.is_markdown_file(path)
51 self.assertEqual(is_markdown, expected_result)
52
53 def test_get_relative_url(self):
54 for case in [
55 dict(url='foo/bar', other='foo', expected='bar'),
56 dict(url='foo/bar.txt', other='foo', expected='bar.txt'),
57 dict(url='foo', other='foo/bar', expected='..'),
58 dict(url='foo', other='foo/bar.txt', expected='.'),
59 dict(url='foo/../../bar', other='.', expected='bar'),
60 dict(url='foo/../../bar', other='foo', expected='../bar'),
61 dict(url='foo//./bar/baz', other='foo/bar/baz', expected='.'),
62 dict(url='a/b/.././../c', other='.', expected='c'),
63 dict(url='a/b/c/d/ee', other='a/b/c/d/e', expected='../ee'),
64 dict(url='a/b/c/d/ee', other='a/b/z/d/e', expected='../../../c/d/ee'),
65 dict(url='foo', other='bar.', expected='foo'),
66 dict(url='foo', other='bar./', expected='../foo'),
67 dict(url='foo', other='foo/bar./', expected='..'),
68 dict(url='foo', other='foo/bar./.', expected='..'),
69 dict(url='foo', other='foo/bar././', expected='..'),
70 dict(url='foo/', other='foo/bar././', expected='../'),
71 dict(url='foo', other='foo', expected='.'),
72 dict(url='.foo', other='.foo', expected='.foo'),
73 dict(url='.foo/', other='.foo', expected='.foo/'),
74 dict(url='.foo', other='.foo/', expected='.'),
75 dict(url='.foo/', other='.foo/', expected='./'),
76 dict(url='///', other='', expected='./'),
77 dict(url='a///', other='', expected='a/'),
78 dict(url='a///', other='a', expected='./'),
79 dict(url='.', other='here', expected='..'),
80 dict(url='..', other='here', expected='..'),
81 dict(url='../..', other='here', expected='..'),
82 dict(url='../../a', other='here', expected='../a'),
83 dict(url='..', other='here.txt', expected='.'),
84 dict(url='a', other='', expected='a'),
85 dict(url='a', other='..', expected='a'),
86 dict(url='a', other='b', expected='../a'),
87 # The dots are considered a file. Documenting a long-standing bug:
88 dict(url='a', other='b/..', expected='../a'),
89 dict(url='a', other='b/../..', expected='a'),
90 dict(url='a/..../b', other='a/../b', expected='../a/..../b'),
91 dict(url='a/я/b', other='a/я/c', expected='../b'),
92 dict(url='a/я/b', other='a/яя/c', expected='../../я/b'),
93 ]:
94 url, other, expected = case['url'], case['other'], case['expected']
95 with self.subTest(url=url, other=other):
96 # Leading slash intentionally ignored
97 self.assertEqual(utils.get_relative_url(url, other), expected)
98 self.assertEqual(utils.get_relative_url('/' + url, other), expected)
99 self.assertEqual(utils.get_relative_url(url, '/' + other), expected)
100 self.assertEqual(utils.get_relative_url('/' + url, '/' + other), expected)
101
102 def test_get_relative_url_empty(self):
103 for url in ['', '.', '/.']:
104 for other in ['', '.', '/', '/.']:
105 with self.subTest(url=url, other=other):
106 self.assertEqual(utils.get_relative_url(url, other), '.')
107
108 self.assertEqual(utils.get_relative_url('/', ''), './')
109 self.assertEqual(utils.get_relative_url('/', '/'), './')
110 self.assertEqual(utils.get_relative_url('/', '.'), './')
111 self.assertEqual(utils.get_relative_url('/', '/.'), './')
112
113 def test_normalize_url(self):
114 def test(path, base, expected):
115 self.assertEqual(utils.normalize_url(path, _Page(base)), expected)
116
117 # Absolute paths and anchors are unaffected.
118 for base in 'about.html', 'foo/bar.html', 'index.html', '', 'about/', 'foo/bar/':
119 test('https://media.cdn.org/jq.js', base, 'https://media.cdn.org/jq.js')
120 test('http://media.cdn.org/jquery.js', base, 'http://media.cdn.org/jquery.js')
121 test('//media.cdn.org/jquery.js', base, '//media.cdn.org/jquery.js')
122 test('#some_id', base, '#some_id')
123
124 path = 'media.cdn.org/jquery.js'
125 test(path, '', 'media.cdn.org/jquery.js')
126 test(path, 'index.html', 'media.cdn.org/jquery.js')
127 test(path, 'about.html', 'media.cdn.org/jquery.js')
128 test(path, 'about/', '../media.cdn.org/jquery.js')
129 test(path, 'foo/bar.html', '../media.cdn.org/jquery.js')
130 test(path, 'foo/bar/', '../../media.cdn.org/jquery.js')
131
132 path = 'local/file/jquery.js'
133 test(path, '', 'local/file/jquery.js')
134 test(path, 'index.html', 'local/file/jquery.js')
135 test(path, 'about.html', 'local/file/jquery.js')
136 test(path, 'about/', '../local/file/jquery.js')
137 test(path, 'foo/bar.html', '../local/file/jquery.js')
138 test(path, 'foo/bar/', '../../local/file/jquery.js')
139
140 path = '../../../../above/jquery.js'
141 test(path, '', '../../../../above/jquery.js')
142 test(path, 'index.html', '../../../../above/jquery.js')
143 test(path, 'about.html', '../../../../above/jquery.js')
144 test(path, 'about/', '../../../../../above/jquery.js')
145 test(path, 'foo/bar.html', '../../../../../above/jquery.js')
146 test(path, 'foo/bar/', '../../../../../../above/jquery.js')
147
148 path = '../some/dir/'
149 test(path, '', '../some/dir/')
150 test(path, 'index.html', '../some/dir/')
151 test(path, 'about.html', '../some/dir/')
152 test(path, 'about/', '../../some/dir/')
153 test(path, 'foo/bar.html', '../../some/dir/')
154 test(path, 'foo/bar/', '../../../some/dir/')
155
156 path = 'image.png'
157 test(path, '', 'image.png')
158 test(path, 'index.html', 'image.png')
159 test(path, 'about.html', 'image.png')
160 test(path, 'about/', '../image.png')
161 test(path, 'foo/bar.html', '../image.png')
162 test(path, 'foo/bar/', '../../image.png')
163
164 path = 'style.css?v=20180308c'
165 test(path, '', 'style.css?v=20180308c')
166 test(path, 'index.html', 'style.css?v=20180308c')
167 test(path, 'about.html', 'style.css?v=20180308c')
168 test(path, 'about/', '../style.css?v=20180308c')
169 test(path, 'foo/bar.html', '../style.css?v=20180308c')
170 test(path, 'foo/bar/', '../../style.css?v=20180308c')
171
172 # TODO: This shouldn't pass on Linux
173 # @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
174 def test_normalize_url_windows(self):
175 def test(path, base, expected):
176 self.assertEqual(utils.normalize_url(path, _Page(base)), expected)
177
178 with self.assertLogs('mkdocs', level='WARNING'):
179 path = 'local\\windows\\file\\jquery.js'
180 test(path, '', 'local/windows/file/jquery.js')
181 test(path, 'about/', '../local/windows/file/jquery.js')
182 test(path, 'foo/bar/', '../../local/windows/file/jquery.js')
183
184 def test_reduce_list(self):
185 self.assertEqual(
186 utils.reduce_list([1, 2, 3, 4, 5, 5, 2, 4, 6, 7, 8]),
187 [1, 2, 3, 4, 5, 6, 7, 8],
188 )
189
190 def test_insort(self):
191 a = [1, 2, 3]
192 utils.insort(a, 5)
193 self.assertEqual(a, [1, 2, 3, 5])
194 utils.insort(a, -1)
195 self.assertEqual(a, [-1, 1, 2, 3, 5])
196 utils.insort(a, 2)
197 self.assertEqual(a, [-1, 1, 2, 2, 3, 5])
198 utils.insort(a, 4)
199 self.assertEqual(a, [-1, 1, 2, 2, 3, 4, 5])
200
201 def test_insort_key(self):
202 a = [(1, 'a'), (1, 'b'), (2, 'c')]
203 utils.insort(a, (1, 'a'), key=lambda v: v[0])
204 self.assertEqual(a, [(1, 'a'), (1, 'b'), (1, 'a'), (2, 'c')])
205
206 def test_nest_paths(self, j=posixpath.join):
207 result = utils.nest_paths(
208 [
209 'index.md',
210 j('user-guide', 'configuration.md'),
211 j('user-guide', 'styling-your-docs.md'),
212 j('user-guide', 'writing-your-docs.md'),
213 j('about', 'contributing.md'),
214 j('about', 'license.md'),
215 j('about', 'release-notes.md'),
216 ]
217 )
218
219 self.assertEqual(
220 result,
221 [
222 'index.md',
223 {
224 'User guide': [
225 j('user-guide', 'configuration.md'),
226 j('user-guide', 'styling-your-docs.md'),
227 j('user-guide', 'writing-your-docs.md'),
228 ]
229 },
230 {
231 'About': [
232 j('about', 'contributing.md'),
233 j('about', 'license.md'),
234 j('about', 'release-notes.md'),
235 ]
236 },
237 ],
238 )
239
240 def test_nest_paths_native(self):
241 self.test_nest_paths(os.path.join)
242
243 def test_unicode_yaml(self):
244 yaml_src = dedent(
245 '''
246 key: value
247 key2:
248 - value
249 '''
250 )
251
252 config = utils.yaml_load(yaml_src)
253 self.assertTrue(isinstance(config['key'], str))
254 self.assertTrue(isinstance(config['key2'][0], str))
255
256 @mock.patch.dict(os.environ, {'VARNAME': 'Hello, World!', 'BOOLVAR': 'false'})
257 def test_env_var_in_yaml(self):
258 yaml_src = dedent(
259 '''
260 key1: !ENV VARNAME
261 key2: !ENV UNDEFINED
262 key3: !ENV [UNDEFINED, default]
263 key4: !ENV [UNDEFINED, VARNAME, default]
264 key5: !ENV BOOLVAR
265 '''
266 )
267 config = utils.yaml_load(yaml_src)
268 self.assertEqual(config['key1'], 'Hello, World!')
269 self.assertIsNone(config['key2'])
270 self.assertEqual(config['key3'], 'default')
271 self.assertEqual(config['key4'], 'Hello, World!')
272 self.assertIs(config['key5'], False)
273
274 @tempdir(files={'base.yml': BASEYML, 'parent.yml': PARENTYML})
275 def test_yaml_inheritance(self, tdir):
276 expected = {
277 'foo': 'bar',
278 'baz': {
279 'sub1': 'replaced',
280 'sub2': 2,
281 'sub3': 'new',
282 },
283 'deep1': {
284 'deep2-1': {
285 'deep3-1': 'replaced',
286 'deep3-2': 'bar',
287 },
288 'deep2-2': 'baz',
289 },
290 }
291 with open(os.path.join(tdir, 'base.yml')) as fd:
292 result = utils.yaml_load(fd)
293 self.assertEqual(result, expected)
294
295 @tempdir(files={'base.yml': BASEYML})
296 def test_yaml_inheritance_missing_parent(self, tdir):
297 with open(os.path.join(tdir, 'base.yml')) as fd:
298 with self.assertRaises(exceptions.ConfigurationError):
299 utils.yaml_load(fd)
300
301 @tempdir()
302 @tempdir()
303 def test_copy_files(self, src_dir, dst_dir):
304 cases = [
305 dict(
306 src_path='foo.txt',
307 dst_path='foo.txt',
308 expected='foo.txt',
309 ),
310 dict(
311 src_path='bar.txt',
312 dst_path='foo/', # ensure src filename is appended
313 expected='foo/bar.txt',
314 ),
315 dict(
316 src_path='baz.txt',
317 dst_path='foo/bar/baz.txt', # ensure missing dirs are created
318 expected='foo/bar/baz.txt',
319 ),
320 ]
321
322 for case in cases:
323 src, dst, expected = case['src_path'], case['dst_path'], case['expected']
324 with self.subTest(src):
325 src = os.path.join(src_dir, src)
326 with open(src, 'w') as f:
327 f.write('content')
328 dst = os.path.join(dst_dir, dst)
329 utils.copy_file(src, dst)
330 self.assertTrue(os.path.isfile(os.path.join(dst_dir, expected)))
331
332 @tempdir()
333 @tempdir()
334 def test_copy_files_without_permissions(self, src_dir, dst_dir):
335 cases = [
336 dict(src_path='foo.txt', expected='foo.txt'),
337 dict(src_path='bar.txt', expected='bar.txt'),
338 dict(src_path='baz.txt', expected='baz.txt'),
339 ]
340
341 try:
342 for case in cases:
343 src, expected = case['src_path'], case['expected']
344 with self.subTest(src):
345 src = os.path.join(src_dir, src)
346 with open(src, 'w') as f:
347 f.write('content')
348 # Set src file to read-only
349 os.chmod(src, stat.S_IRUSR)
350 utils.copy_file(src, dst_dir)
351 self.assertTrue(os.path.isfile(os.path.join(dst_dir, expected)))
352 self.assertNotEqual(
353 os.stat(src).st_mode, os.stat(os.path.join(dst_dir, expected)).st_mode
354 )
355 # While src was read-only, dst must remain writable
356 self.assertTrue(os.access(os.path.join(dst_dir, expected), os.W_OK))
357 finally:
358 for case in cases:
359 # Undo read-only so we can delete temp files
360 src = os.path.join(src_dir, case['src_path'])
361 if os.path.exists(src):
362 os.chmod(src, stat.S_IRUSR | stat.S_IWUSR)
363
364 def test_mm_meta_data(self):
365 doc = dedent(
366 """
367 Title: Foo Bar
368 Date: 2018-07-10
369 Summary: Line one
370 Line two
371 Tags: foo
372 Tags: bar
373
374 Doc body
375 """
376 )
377 self.assertEqual(
378 meta.get_data(doc),
379 (
380 "Doc body",
381 {
382 'title': 'Foo Bar',
383 'date': '2018-07-10',
384 'summary': 'Line one Line two',
385 'tags': 'foo bar',
386 },
387 ),
388 )
389
390 def test_mm_meta_data_blank_first_line(self):
391 doc = '\nfoo: bar\nDoc body'
392 self.assertEqual(meta.get_data(doc), (doc.lstrip(), {}))
393
394 def test_yaml_meta_data(self):
395 doc = dedent(
396 """
397 ---
398 Title: Foo Bar
399 Date: 2018-07-10
400 Summary: Line one
401 Line two
402 Tags:
403 - foo
404 - bar
405 ---
406 Doc body
407 """
408 )
409 self.assertEqual(
410 meta.get_data(doc),
411 (
412 "Doc body",
413 {
414 'Title': 'Foo Bar',
415 'Date': datetime.date(2018, 7, 10),
416 'Summary': 'Line one Line two',
417 'Tags': ['foo', 'bar'],
418 },
419 ),
420 )
421
422 def test_yaml_meta_data_not_dict(self):
423 doc = dedent(
424 """
425 ---
426 - List item
427 ---
428 Doc body
429 """
430 )
431 self.assertEqual(meta.get_data(doc), (doc, {}))
432
433 def test_yaml_meta_data_invalid(self):
434 doc = dedent(
435 """
436 ---
437 foo: bar: baz
438 ---
439 Doc body
440 """
441 )
442 self.assertEqual(meta.get_data(doc), (doc, {}))
443
444 def test_no_meta_data(self):
445 doc = dedent(
446 """
447 Doc body
448 """
449 )
450 self.assertEqual(meta.get_data(doc), (doc, {}))
451
452
453 class ThemeUtilsTests(unittest.TestCase):
454 def setUp(self):
455 utils.get_themes.cache_clear()
456
457 def test_get_themes(self):
458 themes = utils.get_theme_names()
459 self.assertIn('mkdocs', themes)
460 self.assertIn('readthedocs', themes)
461
462 @mock.patch('mkdocs.utils.entry_points', autospec=True)
463 def test_get_theme_dir(self, mock_iter):
464 path = 'some/path'
465
466 theme = mock.Mock()
467 theme.name = 'mkdocs2'
468 theme.dist.name = 'mkdocs2'
469 theme.load().__file__ = os.path.join(path, '__init__.py')
470
471 mock_iter.return_value = [theme]
472
473 self.assertEqual(utils.get_theme_dir(theme.name), os.path.abspath(path))
474
475 def test_get_theme_dir_error(self):
476 with self.assertRaises(KeyError):
477 utils.get_theme_dir('nonexistanttheme')
478
479 @mock.patch('mkdocs.utils.entry_points', autospec=True)
480 def test_get_theme_dir_importerror(self, mock_iter):
481 theme = mock.Mock()
482 theme.name = 'mkdocs2'
483 theme.dist.name = 'mkdocs2'
484 theme.load.side_effect = ImportError()
485
486 mock_iter.return_value = [theme]
487
488 with self.assertRaises(ImportError):
489 utils.get_theme_dir(theme.name)
490
491 @mock.patch('mkdocs.utils.entry_points', autospec=True)
492 def test_get_themes_warning(self, mock_iter):
493 theme1 = mock.Mock()
494 theme1.name = 'mkdocs2'
495 theme1.dist.name = 'mkdocs2'
496 theme1.load().__file__ = "some/path1"
497
498 theme2 = mock.Mock()
499 theme2.name = 'mkdocs2'
500 theme2.dist.name = 'mkdocs3'
501 theme2.load().__file__ = "some/path2"
502
503 mock_iter.return_value = [theme1, theme2]
504
505 with self.assertLogs('mkdocs') as cm:
506 theme_names = utils.get_theme_names()
507 self.assertEqual(
508 '\n'.join(cm.output),
509 "WARNING:mkdocs.utils:A theme named 'mkdocs2' is provided by the Python "
510 "packages 'mkdocs3' and 'mkdocs2'. The one in 'mkdocs3' will be used.",
511 )
512 self.assertCountEqual(theme_names, ['mkdocs2'])
513
514 @mock.patch('mkdocs.utils.entry_points', autospec=True)
515 def test_get_themes_error(self, mock_iter):
516 theme1 = mock.Mock()
517 theme1.name = 'mkdocs'
518 theme1.dist.name = 'mkdocs'
519 theme1.load().__file__ = "some/path1"
520
521 theme2 = mock.Mock()
522 theme2.name = 'mkdocs'
523 theme2.dist.name = 'mkdocs2'
524 theme2.load().__file__ = "some/path2"
525
526 mock_iter.return_value = [theme1, theme2]
527
528 with self.assertRaisesRegex(
529 exceptions.ConfigurationError,
530 "The theme 'mkdocs' is a builtin theme but the package 'mkdocs2' "
531 "attempts to provide a theme with the same name.",
532 ):
533 utils.get_theme_names()
534
535
536 class LogCounterTests(unittest.TestCase):
537 def setUp(self):
538 self.log = logging.getLogger('dummy')
539 self.log.propagate = False
540 self.log.setLevel(1)
541 self.counter = utils.CountHandler()
542 self.log.addHandler(self.counter)
543
544 def tearDown(self):
545 self.log.removeHandler(self.counter)
546
547 def test_default_values(self):
548 self.assertEqual(self.counter.get_counts(), [])
549
550 def test_count_critical(self):
551 self.assertEqual(self.counter.get_counts(), [])
552 self.log.critical('msg')
553 self.assertEqual(self.counter.get_counts(), [('CRITICAL', 1)])
554
555 def test_count_error(self):
556 self.assertEqual(self.counter.get_counts(), [])
557 self.log.error('msg')
558 self.assertEqual(self.counter.get_counts(), [('ERROR', 1)])
559
560 def test_count_warning(self):
561 self.assertEqual(self.counter.get_counts(), [])
562 self.log.warning('msg')
563 self.assertEqual(self.counter.get_counts(), [('WARNING', 1)])
564
565 def test_count_info(self):
566 self.assertEqual(self.counter.get_counts(), [])
567 self.log.info('msg')
568 self.assertEqual(self.counter.get_counts(), [('INFO', 1)])
569
570 def test_count_debug(self):
571 self.assertEqual(self.counter.get_counts(), [])
572 self.log.debug('msg')
573 self.assertEqual(self.counter.get_counts(), [('DEBUG', 1)])
574
575 def test_count_multiple(self):
576 self.assertEqual(self.counter.get_counts(), [])
577 self.log.warning('msg 1')
578 self.assertEqual(self.counter.get_counts(), [('WARNING', 1)])
579 self.log.warning('msg 2')
580 self.assertEqual(self.counter.get_counts(), [('WARNING', 2)])
581 self.log.debug('msg 3')
582 self.assertEqual(self.counter.get_counts(), [('WARNING', 2), ('DEBUG', 1)])
583 self.log.error('mdg 4')
584 self.assertEqual(self.counter.get_counts(), [('ERROR', 1), ('WARNING', 2), ('DEBUG', 1)])
585
586 def test_log_level(self):
587 self.assertEqual(self.counter.get_counts(), [])
588 self.counter.setLevel(logging.ERROR)
589 self.log.error('counted')
590 self.log.warning('not counted')
591 self.log.info('not counted')
592 self.assertEqual(self.counter.get_counts(), [('ERROR', 1)])
593 self.counter.setLevel(logging.WARNING)
594 self.log.error('counted')
595 self.log.warning('counted')
596 self.log.info('not counted')
597 self.assertEqual(self.counter.get_counts(), [('ERROR', 2), ('WARNING', 1)])
598
599
600 @dataclasses.dataclass
601 class _Page:
602 url: str