Debian Codegraph @

mkdocs/tests/config/config_options_tests.py

raw ◀ ▶
1 Debian patch touch this file
1 from __future__ import annotations
2
3 import contextlib
4 import copy
5 import io
6 import logging
7 import os
8 import re
9 import sys
10 import textwrap
11 import unittest
12 from typing import TYPE_CHECKING, Any, Dict, List, Optional, TypeVar, Union
13 from unittest import mock
14
15 if TYPE_CHECKING:
16 from typing_extensions import assert_type
17 else:
18
19 def assert_type(val, typ):
20 return None
21
22
23 import mkdocs
24 from mkdocs.config import config_options as c
25 from mkdocs.config import defaults
26 from mkdocs.config.base import Config
27 from mkdocs.plugins import BasePlugin, PluginCollection
28 from mkdocs.tests.base import tempdir
29 from mkdocs.theme import Theme
30 from mkdocs.utils import write_file, yaml_load
31
32 SomeConfig = TypeVar('SomeConfig', bound=Config)
33
34
35 class UnexpectedError(Exception):
36 pass
37
38
39 class TestCase(unittest.TestCase):
40 @contextlib.contextmanager
41 def expect_error(self, **kwargs):
42 [(key, msg)] = kwargs.items()
43 with self.assertRaises(UnexpectedError) as cm:
44 yield
45 if isinstance(msg, re.Pattern):
46 self.assertRegex(str(cm.exception), f'^{key}="{msg.pattern}"$')
47 else:
48 self.assertEqual(f'{key}="{msg}"', str(cm.exception))
49
50 def get_config(
51 self,
52 config_class: type[SomeConfig],
53 cfg: dict[str, Any],
54 warnings: dict[str, str] = {},
55 config_file_path=None,
56 ) -> SomeConfig:
57 config = config_class(config_file_path=config_file_path)
58 config.load_dict(cfg)
59 actual_errors, actual_warnings = config.validate()
60 if actual_errors:
61 raise UnexpectedError(', '.join(f'{key}="{msg}"' for key, msg in actual_errors))
62 self.assertEqual(warnings, dict(actual_warnings))
63 return config
64
65
66 class TypeTest(TestCase):
67 def test_single_type(self) -> None:
68 class Schema(Config):
69 option = c.Type(str)
70
71 conf = self.get_config(Schema, {'option': "Testing"})
72 assert_type(conf.option, str)
73 self.assertEqual(conf.option, "Testing")
74
75 def test_multiple_types(self) -> None:
76 class Schema(Config):
77 option = c.Type((list, tuple))
78
79 conf = self.get_config(Schema, {'option': [1, 2, 3]})
80 self.assertEqual(conf.option, [1, 2, 3])
81
82 conf = self.get_config(Schema, {'option': (1, 2, 3)})
83 self.assertEqual(conf.option, (1, 2, 3))
84
85 with self.expect_error(
86 option="Expected type: (<class 'list'>, <class 'tuple'>) but received: <class 'dict'>"
87 ):
88 self.get_config(Schema, {'option': {'a': 1}})
89
90 def test_length(self) -> None:
91 class Schema(Config):
92 option = c.Type(str, length=7)
93
94 conf = self.get_config(Schema, {'option': "Testing"})
95 assert_type(conf.option, str)
96 self.assertEqual(conf.option, "Testing")
97
98 with self.expect_error(
99 option="Expected type: <class 'str'> with length 7 but received: 'Testing Long' with length 12"
100 ):
101 self.get_config(Schema, {'option': "Testing Long"})
102
103 def test_optional_with_default(self) -> None:
104 with self.assertRaisesRegex(ValueError, "doesn't need to be wrapped into Optional"):
105 c.Optional(c.Type(int, default=5))
106
107
108 class ChoiceTest(TestCase):
109 def test_required(self) -> None:
110 class Schema(Config):
111 option = c.Choice(('python', 'node'))
112
113 conf = self.get_config(Schema, {'option': 'python'})
114 assert_type(conf.option, str)
115 self.assertEqual(conf.option, 'python')
116
117 def test_optional(self) -> None:
118 class Schema(Config):
119 option = c.Optional(c.Choice(('python', 'node')))
120
121 conf = self.get_config(Schema, {'option': 'python'})
122 assert_type(conf.option, Optional[str])
123 self.assertEqual(conf.option, 'python')
124
125 conf = self.get_config(Schema, {})
126 self.assertEqual(conf.option, None)
127
128 conf = self.get_config(Schema, {'option': None})
129 self.assertEqual(conf.option, None)
130
131 def test_default(self) -> None:
132 class Schema(Config):
133 option = c.Choice(('a', 'b', 'c'), default='b')
134
135 conf = self.get_config(Schema, {})
136 assert_type(conf.option, str)
137 self.assertEqual(conf.option, 'b')
138
139 conf = self.get_config(Schema, {})
140 self.assertEqual(conf.option, 'b')
141
142 conf = self.get_config(Schema, {'option': None})
143 self.assertEqual(conf.option, 'b')
144
145 with self.expect_error(option="Expected one of: ('a', 'b', 'c') but received: 'go'"):
146 self.get_config(Schema, {'option': 'go'})
147
148 def test_invalid_default(self) -> None:
149 with self.assertRaises(ValueError):
150 c.Choice(('a', 'b'), default='c')
151 with self.assertRaises(ValueError):
152 c.Choice(('a', 'b'), default='c', required=True)
153
154 def test_invalid_choice(self) -> None:
155 class Schema(Config):
156 option = c.Choice(('python', 'node'))
157
158 with self.expect_error(option="Expected one of: ('python', 'node') but received: 'go'"):
159 self.get_config(Schema, {'option': 'go'})
160
161 def test_invalid_choices(self) -> None:
162 with self.assertRaises(ValueError):
163 c.Choice('')
164 with self.assertRaises(ValueError):
165 c.Choice([])
166
167
168 class DeprecatedTest(TestCase):
169 def test_deprecated_option_simple(self) -> None:
170 class Schema(Config):
171 d = c.Deprecated()
172
173 self.get_config(
174 Schema,
175 {'d': 'value'},
176 warnings=dict(
177 d="The configuration option 'd' has been deprecated and will be removed in a "
178 "future release."
179 ),
180 )
181
182 def test_deprecated_option_message(self) -> None:
183 class Schema(Config):
184 d = c.Deprecated(message='custom message for {} key')
185
186 self.get_config(Schema, {'d': 'value'}, warnings={'d': 'custom message for d key'})
187
188 def test_deprecated_option_with_type(self) -> None:
189 class Schema(Config):
190 d = c.Deprecated(option_type=c.Type(str))
191
192 self.get_config(
193 Schema,
194 {'d': 'value'},
195 warnings=dict(
196 d="The configuration option 'd' has been deprecated and will be removed in a "
197 "future release."
198 ),
199 )
200
201 def test_deprecated_option_with_invalid_type(self) -> None:
202 class Schema(Config):
203 d = c.Deprecated(option_type=c.Type(list))
204
205 with self.expect_error(d="Expected type: <class 'list'> but received: <class 'str'>"):
206 self.get_config(
207 Schema,
208 {'d': 'value'},
209 warnings=dict(
210 d="The configuration option 'd' has been deprecated and will be removed in a "
211 "future release."
212 ),
213 )
214
215 def test_removed_option(self) -> None:
216 class Schema(Config):
217 d = c.Deprecated(removed=True, moved_to='foo')
218
219 with self.expect_error(
220 d="The configuration option 'd' was removed from MkDocs. Use 'foo' instead.",
221 ):
222 self.get_config(Schema, {'d': 'value'})
223
224 def test_deprecated_option_with_type_undefined(self) -> None:
225 class Schema(Config):
226 option = c.Deprecated(option_type=c.Type(str))
227
228 self.get_config(Schema, {'option': None})
229
230 def test_deprecated_option_move(self) -> None:
231 class Schema(Config):
232 new = c.Type(str)
233 old = c.Deprecated(moved_to='new')
234
235 conf = self.get_config(
236 Schema,
237 {'old': 'value'},
238 warnings=dict(
239 old="The configuration option 'old' has been deprecated and will be removed in a "
240 "future release. Use 'new' instead."
241 ),
242 )
243 self.assertEqual(conf, {'new': 'value', 'old': None})
244
245 def test_deprecated_option_move_complex(self) -> None:
246 class Schema(Config):
247 foo = c.Type(dict)
248 old = c.Deprecated(moved_to='foo.bar')
249
250 conf = self.get_config(
251 Schema,
252 {'old': 'value'},
253 warnings=dict(
254 old="The configuration option 'old' has been deprecated and will be removed in a "
255 "future release. Use 'foo.bar' instead."
256 ),
257 )
258 self.assertEqual(conf, {'foo': {'bar': 'value'}, 'old': None})
259
260 def test_deprecated_option_move_existing(self) -> None:
261 class Schema(Config):
262 foo = c.Type(dict)
263 old = c.Deprecated(moved_to='foo.bar')
264
265 conf = self.get_config(
266 Schema,
267 {'old': 'value', 'foo': {'existing': 'existing'}},
268 warnings=dict(
269 old="The configuration option 'old' has been deprecated and will be removed in a "
270 "future release. Use 'foo.bar' instead."
271 ),
272 )
273 self.assertEqual(conf, {'foo': {'existing': 'existing', 'bar': 'value'}, 'old': None})
274
275 def test_deprecated_option_move_invalid(self) -> None:
276 class Schema(Config):
277 foo = c.Type(dict)
278 old = c.Deprecated(moved_to='foo.bar')
279
280 with self.expect_error(foo="Expected type: <class 'dict'> but received: <class 'str'>"):
281 self.get_config(
282 Schema,
283 {'old': 'value', 'foo': 'wrong type'},
284 warnings=dict(
285 old="The configuration option 'old' has been deprecated and will be removed in a "
286 "future release. Use 'foo.bar' instead."
287 ),
288 )
289
290
291 class IpAddressTest(TestCase):
292 class Schema(Config):
293 option = c.IpAddress()
294
295 def test_valid_address(self) -> None:
296 addr = '127.0.0.1:8000'
297
298 conf = self.get_config(self.Schema, {'option': addr})
299
300 assert_type(conf.option, c._IpAddressValue)
301 assert_type(conf.option.host, str)
302 assert_type(conf.option.port, int)
303
304 self.assertEqual(str(conf.option), addr)
305 self.assertEqual(conf.option.host, '127.0.0.1')
306 self.assertEqual(conf.option.port, 8000)
307
308 def test_valid_IPv6_address(self) -> None:
309 addr = '::1:8000'
310
311 conf = self.get_config(self.Schema, {'option': addr})
312 self.assertEqual(str(conf.option), addr)
313 self.assertEqual(conf.option.host, '::1')
314 self.assertEqual(conf.option.port, 8000)
315
316 def test_valid_full_IPv6_address(self) -> None:
317 addr = '[2001:db8:85a3::8a2e:370:7334]:123'
318
319 conf = self.get_config(self.Schema, {'option': addr})
320 self.assertEqual(conf.option.host, '2001:db8:85a3::8a2e:370:7334')
321 self.assertEqual(conf.option.port, 123)
322
323 def test_named_address(self) -> None:
324 addr = 'localhost:8000'
325
326 conf = self.get_config(self.Schema, {'option': addr})
327 self.assertEqual(str(conf.option), addr)
328 self.assertEqual(conf.option.host, 'localhost')
329 self.assertEqual(conf.option.port, 8000)
330
331 def test_default_address(self) -> None:
332 addr = '127.0.0.1:8000'
333
334 class Schema(Config):
335 option = c.IpAddress(default=addr)
336
337 conf = self.get_config(Schema, {'option': None})
338 self.assertEqual(str(conf.option), addr)
339 self.assertEqual(conf.option.host, '127.0.0.1')
340 self.assertEqual(conf.option.port, 8000)
341
342 def test_bind_all_IPv4_address(self):
343 addr = '0.0.0.0:8000'
344
345 class Schema(Config):
346 option = c.IpAddress(default=addr)
347
348 conf = self.get_config(Schema, {'option': None})
349 self.assertEqual(str(conf['option']), addr)
350 self.assertEqual(conf['option'].host, '0.0.0.0')
351 self.assertEqual(conf['option'].port, 8000)
352
353 def test_bind_all_IPv6_address(self):
354 addr = ':::8000'
355
356 class Schema(Config):
357 option = c.IpAddress(default=addr)
358
359 conf = self.get_config(Schema, {'option': None})
360 self.assertEqual(str(conf['option']), addr)
361 self.assertEqual(conf['option'].host, '::')
362 self.assertEqual(conf['option'].port, 8000)
363
•364 @unittest.skipIf(
365 sys.version_info >= (3, 9, 5),
366 "Leading zeros not allowed in IP addresses since Python3.9.5",
367 )
368 def test_IP_normalization(self):
369 addr = '127.000.000.001:8000'
370 option = config_options.IpAddress(default=addr)
371 value = option.validate(None)
372 self.assertEqual(str(value), '127.0.0.1:8000')
373 self.assertEqual(value.host, '127.0.0.1')
374 self.assertEqual(value.port, 8000)
375
376 @unittest.skipIf(
377 sys.version_info < (3, 9, 5),
378 "Leading zeros allowed in IP addresses before Python3.9.5",
379 )
380 def test_invalid_leading_zeros(self) -> None:
381 with self.expect_error(
382 option="'127.000.000.001' does not appear to be an IPv4 or IPv6 address"
383 ):
384 self.get_config(self.Schema, {'option': '127.000.000.001:8000'})
385
386 def test_invalid_address_range(self) -> None:
387 with self.expect_error(option="'277.0.0.1' does not appear to be an IPv4 or IPv6 address"):
388 self.get_config(self.Schema, {'option': '277.0.0.1:8000'})
389
390 def test_invalid_address_format(self) -> None:
391 with self.expect_error(option="Must be a string of format 'IP:PORT'"):
392 self.get_config(self.Schema, {'option': '127.0.0.18000'})
393
394 def test_invalid_address_type(self) -> None:
395 with self.expect_error(option="Must be a string of format 'IP:PORT'"):
396 self.get_config(self.Schema, {'option': 123})
397
398 def test_invalid_address_port(self) -> None:
399 with self.expect_error(option="'foo' is not a valid port"):
400 self.get_config(self.Schema, {'option': '127.0.0.1:foo'})
401
402 def test_invalid_address_missing_port(self) -> None:
403 with self.expect_error(option="Must be a string of format 'IP:PORT'"):
404 self.get_config(self.Schema, {'option': '127.0.0.1'})
405
406
407 class URLTest(TestCase):
408 def test_valid_url(self) -> None:
409 class Schema(Config):
410 option = c.URL()
411
412 conf = self.get_config(Schema, {'option': "https://mkdocs.org"})
413 assert_type(conf.option, str)
414 self.assertEqual(conf.option, "https://mkdocs.org")
415
416 conf = self.get_config(Schema, {'option': ""})
417 self.assertEqual(conf.option, "")
418
419 def test_valid_url_is_dir(self) -> None:
420 class Schema(Config):
421 option = c.URL(is_dir=True)
422
423 conf = self.get_config(Schema, {'option': "http://mkdocs.org/"})
424 self.assertEqual(conf.option, "http://mkdocs.org/")
425
426 conf = self.get_config(Schema, {'option': "https://mkdocs.org"})
427 self.assertEqual(conf.option, "https://mkdocs.org/")
428
429 def test_optional(self):
430 class Schema(Config):
431 option = c.Optional(c.URL(is_dir=True))
432
433 conf = self.get_config(Schema, {'option': ''})
434 self.assertEqual(conf.option, '')
435
436 conf = self.get_config(Schema, {'option': None})
437 self.assertEqual(conf.option, None)
438
439 def test_invalid_url(self) -> None:
440 class Schema(Config):
441 option = c.URL()
442
443 with self.expect_error(option="Required configuration not provided."):
444 self.get_config(Schema, {'option': None})
445
446 for url in "www.mkdocs.org", "//mkdocs.org/test", "http:/mkdocs.org/", "/hello/":
447 with self.subTest(url=url):
448 with self.expect_error(
449 option="The URL isn't valid, it should include the http:// (scheme)"
450 ):
451 self.get_config(Schema, {'option': url})
452
453 def test_invalid_type(self) -> None:
454 class Schema(Config):
455 option = c.URL()
456
457 with self.expect_error(option="Expected a string, got <class 'int'>"):
458 self.get_config(Schema, {'option': 1})
459
460
461 class EditURITest(TestCase):
462 class Schema(Config):
463 repo_url = c.Optional(c.URL())
464 repo_name = c.Optional(c.RepoName('repo_url'))
465 edit_uri_template = c.Optional(c.EditURITemplate('edit_uri'))
466 edit_uri = c.Optional(c.EditURI('repo_url'))
467
468 def test_repo_name_github(self) -> None:
469 conf = self.get_config(
470 self.Schema,
471 {'repo_url': "https://github.com/mkdocs/mkdocs"},
472 )
473 assert_type(conf.repo_name, Optional[str])
474 self.assertEqual(conf.repo_name, "GitHub")
475
476 def test_repo_name_bitbucket(self) -> None:
477 conf = self.get_config(
478 self.Schema,
479 {'repo_url': "https://bitbucket.org/gutworth/six/"},
480 )
481 self.assertEqual(conf.repo_name, "Bitbucket")
482
483 def test_repo_name_gitlab(self) -> None:
484 conf = self.get_config(
485 self.Schema,
486 {'repo_url': "https://gitlab.com/gitlab-org/gitlab-ce/"},
487 )
488 self.assertEqual(conf.repo_name, "GitLab")
489
490 def test_repo_name_custom(self) -> None:
491 conf = self.get_config(
492 self.Schema,
493 {'repo_url': "https://launchpad.net/python-tuskarclient"},
494 )
495 self.assertEqual(conf.repo_name, "Launchpad")
496
497 def test_edit_uri_github(self) -> None:
498 conf = self.get_config(
499 self.Schema,
500 {'repo_url': "https://github.com/mkdocs/mkdocs"},
501 )
502 assert_type(conf.edit_uri, Optional[str])
503 assert_type(conf.repo_url, Optional[str])
504 self.assertEqual(conf.edit_uri, 'edit/master/docs/')
505 self.assertEqual(conf.repo_url, "https://github.com/mkdocs/mkdocs")
506
507 def test_edit_uri_bitbucket(self) -> None:
508 conf = self.get_config(
509 self.Schema,
510 {'repo_url': "https://bitbucket.org/gutworth/six/"},
511 )
512 self.assertEqual(conf.edit_uri, 'src/default/docs/')
513 self.assertEqual(conf.repo_url, "https://bitbucket.org/gutworth/six/")
514
515 def test_edit_uri_gitlab(self) -> None:
516 conf = self.get_config(
517 self.Schema,
518 {'repo_url': "https://gitlab.com/gitlab-org/gitlab-ce/"},
519 )
520 self.assertEqual(conf.edit_uri, 'edit/master/docs/')
521
522 def test_edit_uri_custom(self) -> None:
523 conf = self.get_config(
524 self.Schema,
525 {'repo_url': "https://launchpad.net/python-tuskarclient"},
526 )
527 self.assertEqual(conf.edit_uri, None)
528 self.assertEqual(conf.repo_url, "https://launchpad.net/python-tuskarclient")
529
530 def test_repo_name_custom_and_empty_edit_uri(self) -> None:
531 conf = self.get_config(
532 self.Schema,
533 {'repo_url': "https://github.com/mkdocs/mkdocs", 'repo_name': 'mkdocs'},
534 )
535 self.assertEqual(conf.edit_uri, 'edit/master/docs/')
536
537 def test_edit_uri_template_ok(self) -> None:
538 conf = self.get_config(
539 self.Schema,
540 {
541 'repo_url': "https://github.com/mkdocs/mkdocs",
542 'edit_uri_template': 'edit/foo/docs/{path}',
543 },
544 )
545 assert_type(conf.edit_uri_template, Optional[str])
546 self.assertEqual(conf.edit_uri_template, 'edit/foo/docs/{path}')
547
548 def test_edit_uri_template_errors(self) -> None:
549 with self.expect_error(
550 edit_uri_template=re.compile(r'.*[{}].*') # Complains about unclosed '{' or missing '}'
551 ):
552 self.get_config(
553 self.Schema,
554 {
555 'repo_url': "https://github.com/mkdocs/mkdocs",
556 'edit_uri_template': 'edit/master/{path',
557 },
558 )
559
560 with self.expect_error(edit_uri_template=re.compile(r'.*\bz\b.*')):
561 self.get_config(
562 self.Schema,
563 {
564 'repo_url': "https://github.com/mkdocs/mkdocs",
565 'edit_uri_template': 'edit/master/{path!z}',
566 },
567 )
568
569 with self.expect_error(edit_uri_template="Unknown template substitute: 'foo'"):
570 self.get_config(
571 self.Schema,
572 {
573 'repo_url': "https://github.com/mkdocs/mkdocs",
574 'edit_uri_template': 'edit/master/{foo}',
575 },
576 )
577
578 def test_edit_uri_template_warning(self) -> None:
579 conf = self.get_config(
580 self.Schema,
581 {
582 'repo_url': "https://github.com/mkdocs/mkdocs",
583 'edit_uri': 'edit',
584 'edit_uri_template': 'edit/master/{path}',
585 },
586 warnings=dict(
587 edit_uri_template="The option 'edit_uri' has no effect when 'edit_uri_template' is set."
588 ),
589 )
590 self.assertEqual(conf.edit_uri_template, 'edit/master/{path}')
591
592
593 class ListOfItemsTest(TestCase):
594 def test_int_type(self) -> None:
595 class Schema(Config):
596 option = c.ListOfItems(c.Type(int))
597
598 conf = self.get_config(Schema, {'option': [1, 2, 3]})
599 assert_type(conf.option, List[int])
600 self.assertEqual(conf.option, [1, 2, 3])
601
602 with self.expect_error(
603 option="Expected type: <class 'int'> but received: <class 'NoneType'>"
604 ):
605 conf = self.get_config(Schema, {'option': [1, None, 3]})
606
607 def test_combined_float_type(self) -> None:
608 class Schema(Config):
609 option = c.ListOfItems(c.Type((int, float)))
610
611 conf = self.get_config(Schema, {'option': [1.4, 2, 3]})
612 self.assertEqual(conf.option, [1.4, 2, 3])
613
614 with self.expect_error(
615 option="Expected type: (<class 'int'>, <class 'float'>) but received: <class 'str'>"
616 ):
617 self.get_config(Schema, {'option': ['a']})
618
619 def test_list_default(self) -> None:
620 class Schema(Config):
621 option = c.ListOfItems(c.Type(int), default=[])
622
623 conf = self.get_config(Schema, {})
624 assert_type(conf.option, List[int])
625 self.assertEqual(conf.option, [])
626
627 with self.expect_error(option="Required configuration not provided."):
628 conf = self.get_config(Schema, {'option': None})
629
630 def test_none_without_default(self) -> None:
631 class Schema(Config):
632 option = c.ListOfItems(c.Type(str))
633
634 with self.expect_error(option="Required configuration not provided."):
635 conf = self.get_config(Schema, {})
636
637 with self.expect_error(option="Required configuration not provided."):
638 conf = self.get_config(Schema, {'option': None})
639
640 conf = self.get_config(Schema, {'option': ['foo']})
641 self.assertEqual(conf.option, ['foo'])
642
643 def test_optional(self) -> None:
644 class Schema(Config):
645 option = c.Optional(c.ListOfItems(c.Type(str)))
646
647 conf = self.get_config(Schema, {})
648 assert_type(conf.option, Optional[List[str]])
649 self.assertEqual(conf.option, None)
650
651 conf = self.get_config(Schema, {'option': None})
652 self.assertEqual(conf.option, None)
653
654 conf = self.get_config(Schema, {'option': ['foo']})
655 self.assertEqual(conf.option, ['foo'])
656
657 def test_list_of_optional(self) -> None:
658 class Schema(Config):
659 option = c.ListOfItems(c.Optional(c.Type(int)), default=[])
660
661 conf = self.get_config(Schema, {})
662 assert_type(conf.option, List[Optional[int]])
663 self.assertEqual(conf.option, [])
664
665 conf = self.get_config(Schema, {'option': [4, None]})
666 self.assertEqual(conf.option, [4, None])
667
668 with self.expect_error(option="Expected type: <class 'int'> but received: <class 'str'>"):
669 conf = self.get_config(Schema, {'option': ['foo']})
670 self.assertEqual(conf.option, ['foo'])
671
672 def test_string_not_a_list_of_strings(self) -> None:
673 class Schema(Config):
674 option = c.ListOfItems(c.Type(str))
675
676 with self.expect_error(option="Expected a list of items, but a <class 'str'> was given."):
677 self.get_config(Schema, {'option': 'foo'})
678
679 def test_post_validation_error(self) -> None:
680 class Schema(Config):
681 option = c.ListOfItems(c.IpAddress())
682
683 with self.expect_error(option="'asdf' is not a valid port"):
684 self.get_config(Schema, {'option': ["localhost:8000", "1.2.3.4:asdf"]})
685
686 def test_warning(self) -> None:
687 class Schema(Config):
688 option = c.ListOfItems(c.Deprecated())
689
690 self.get_config(
691 Schema,
692 {'option': ['a']},
693 warnings=dict(
694 option="The configuration option 'option[0]' has been "
695 "deprecated and will be removed in a future release."
696 ),
697 )
698
699
700 class ExtraScriptsTest(TestCase):
701 def test_js_async(self) -> None:
702 class Schema(Config):
703 option = c.ListOfItems(c.ExtraScript(), default=[])
704
705 conf = self.get_config(Schema, {'option': ['foo.js', {'path': 'bar.js', 'async': True}]})
706 assert_type(conf.option, List[Union[c.ExtraScriptValue, str]])
707 self.assertEqual(len(conf.option), 2)
708 self.assertIsInstance(conf.option[1], c.ExtraScriptValue)
709 self.assertEqual(
710 conf.option,
711 [
712 'foo.js',
713 {'path': 'bar.js', 'type': '', 'defer': False, 'async': True},
714 ],
715 )
716
717 def test_mjs(self) -> None:
718 class Schema(Config):
719 option = c.ListOfItems(c.ExtraScript(), default=[])
720
721 conf = self.get_config(
722 Schema, {'option': ['foo.mjs', {'path': 'bar.js', 'type': 'module'}]}
723 )
724 assert_type(conf.option, List[Union[c.ExtraScriptValue, str]])
725 self.assertEqual(len(conf.option), 2)
726 self.assertIsInstance(conf.option[0], c.ExtraScriptValue)
727 self.assertEqual(
728 conf.option,
729 [
730 {'path': 'foo.mjs', 'type': 'module', 'defer': False, 'async': False},
731 {'path': 'bar.js', 'type': 'module', 'defer': False, 'async': False},
732 ],
733 )
734
735 def test_wrong_type(self) -> None:
736 class Schema(Config):
737 option = c.ListOfItems(c.ExtraScript(), default=[])
738
739 with self.expect_error(
740 option="The configuration is invalid. Expected a key-value mapping (dict) but received: <class 'int'>"
741 ):
742 self.get_config(Schema, {'option': [1]})
743
744 def test_unknown_key(self) -> None:
745 class Schema(Config):
746 option = c.ListOfItems(c.ExtraScript(), default=[])
747
748 conf = self.get_config(
749 Schema,
750 {'option': [{'path': 'foo.js', 'foo': 'bar'}]},
751 warnings=dict(option="Sub-option 'foo': Unrecognised configuration name: foo"),
752 )
753 self.assertEqual(
754 conf.option,
755 [{'path': 'foo.js', 'type': '', 'defer': False, 'async': False, 'foo': 'bar'}],
756 )
757
758
759 class DictOfItemsTest(TestCase):
760 def test_int_type(self) -> None:
761 class Schema(Config):
762 option = c.DictOfItems(c.Type(int))
763
764 conf = self.get_config(Schema, {'option': {"a": 1, "b": 2}})
765 assert_type(conf.option, Dict[str, int])
766 self.assertEqual(conf.option, {"a": 1, "b": 2})
767
768 with self.expect_error(
769 option="Expected type: <class 'int'> but received: <class 'NoneType'>"
770 ):
771 conf = self.get_config(Schema, {'option': {"a": 1, "b": None}})
772
773 def test_combined_float_type(self) -> None:
774 class Schema(Config):
775 option = c.DictOfItems(c.Type((int, float)))
776
777 conf = self.get_config(Schema, {'option': {"a": 1, "b": 2.3}})
778 self.assertEqual(conf.option, {"a": 1, "b": 2.3})
779
780 with self.expect_error(
781 option="Expected type: (<class 'int'>, <class 'float'>) but received: <class 'str'>"
782 ):
783 self.get_config(Schema, {'option': {"a": 1, "b": "2"}})
784
785 def test_dict_default(self) -> None:
786 class Schema(Config):
787 option = c.DictOfItems(c.Type(int), default={})
788
789 conf = self.get_config(Schema, {})
790 assert_type(conf.option, Dict[str, int])
791 self.assertEqual(conf.option, {})
792
793 with self.expect_error(option="Required configuration not provided."):
794 conf = self.get_config(Schema, {'option': None})
795
796 def test_none_without_default(self) -> None:
797 class Schema(Config):
798 option = c.DictOfItems(c.Type(str))
799
800 with self.expect_error(option="Required configuration not provided."):
801 conf = self.get_config(Schema, {})
802
803 with self.expect_error(option="Required configuration not provided."):
804 conf = self.get_config(Schema, {'option': None})
805
806 conf = self.get_config(Schema, {'option': {"foo": "bar"}})
807 self.assertEqual(conf.option, {"foo": "bar"})
808
809 def test_optional(self) -> None:
810 class Schema(Config):
811 option = c.Optional(c.DictOfItems(c.Type(str)))
812
813 conf = self.get_config(Schema, {})
814 assert_type(conf.option, Optional[Dict[str, str]])
815 self.assertEqual(conf.option, None)
816
817 conf = self.get_config(Schema, {'option': None})
818 self.assertEqual(conf.option, None)
819
820 conf = self.get_config(Schema, {'option': {"foo": "bar"}})
821 self.assertEqual(conf.option, {"foo": "bar"})
822
823 def test_dict_of_optional(self) -> None:
824 class Schema(Config):
825 option = c.DictOfItems(c.Optional(c.Type(int)), default={})
826
827 conf = self.get_config(Schema, {})
828 assert_type(conf.option, Dict[str, Optional[int]])
829 self.assertEqual(conf.option, {})
830
831 conf = self.get_config(Schema, {'option': {"a": 1, "b": None}})
832 self.assertEqual(conf.option, {"a": 1, "b": None})
833
834 with self.expect_error(option="Expected type: <class 'int'> but received: <class 'str'>"):
835 conf = self.get_config(Schema, {'option': {"foo": "bar"}})
836 self.assertEqual(conf.option, {"foo": "bar"})
837
838 def test_string_not_a_dict_of_strings(self) -> None:
839 class Schema(Config):
840 option = c.DictOfItems(c.Type(str))
841
842 with self.expect_error(option="Expected a dict of items, but a <class 'str'> was given."):
843 self.get_config(Schema, {'option': 'foo'})
844
845 def test_post_validation_error(self) -> None:
846 class Schema(Config):
847 option = c.DictOfItems(c.IpAddress())
848
849 with self.expect_error(option="'asdf' is not a valid port"):
850 self.get_config(
851 Schema, {'option': {"ip_foo": "localhost:8000", "ip_bar": "1.2.3.4:asdf"}}
852 )
853
854 def test_all_keys_are_strings(self) -> None:
855 class Schema(Config):
856 option = c.DictOfItems(c.Type(int))
857
858 with self.expect_error(
859 option="Expected type: <class 'str'> for keys, but received: <class 'int'> (key=2)"
860 ):
861 self.get_config(Schema, {'option': {"a": 1, 2: 3}})
862
863
864 class FilesystemObjectTest(TestCase):
865 def test_valid_dir(self) -> None:
866 for cls in c.Dir, c.FilesystemObject:
867 with self.subTest(cls):
868 d = os.path.dirname(__file__)
869
870 class Schema(Config):
871 option = cls(exists=True)
872
873 conf = self.get_config(Schema, {'option': d})
874 assert_type(conf.option, str)
875 self.assertEqual(conf.option, d)
876
877 def test_valid_file(self) -> None:
878 for cls in c.File, c.FilesystemObject:
879 with self.subTest(cls):
880 f = __file__
881
882 class Schema(Config):
883 option = cls(exists=True)
884
885 conf = self.get_config(Schema, {'option': f})
886 assert_type(conf.option, str)
887 self.assertEqual(conf.option, f)
888
889 def test_missing_without_exists(self) -> None:
890 for cls in c.Dir, c.File, c.FilesystemObject:
891 with self.subTest(cls):
892 d = os.path.join("not", "a", "real", "path", "I", "hope")
893
894 class Schema(Config):
895 option = cls()
896
897 conf = self.get_config(Schema, {'option': d})
898 assert_type(conf.option, str)
899 self.assertEqual(conf.option, os.path.abspath(d))
900
901 def test_missing_but_required(self) -> None:
902 for cls in c.Dir, c.File, c.FilesystemObject:
903 with self.subTest(cls):
904 d = os.path.join("not", "a", "real", "path", "I", "hope")
905
906 class Schema(Config):
907 option = cls(exists=True)
908
909 with self.expect_error(option=re.compile(r"The path '.+' isn't an existing .+")):
910 self.get_config(Schema, {'option': d})
911
912 def test_not_a_dir(self) -> None:
913 d = __file__
914
915 class Schema(Config):
916 option = c.Dir(exists=True)
917
918 with self.expect_error(option=re.compile(r"The path '.+' isn't an existing directory.")):
919 self.get_config(Schema, {'option': d})
920
921 def test_not_a_file(self) -> None:
922 d = os.path.dirname(__file__)
923
924 class Schema(Config):
925 option = c.File(exists=True)
926
927 with self.expect_error(option=re.compile(r"The path '.+' isn't an existing file.")):
928 self.get_config(Schema, {'option': d})
929
930 def test_incorrect_type_error(self) -> None:
931 for cls in c.Dir, c.File, c.FilesystemObject:
932 with self.subTest(cls):
933
934 class Schema(Config):
935 option = cls()
936
937 with self.expect_error(
938 option="Expected type: <class 'str'> but received: <class 'int'>"
939 ):
940 self.get_config(Schema, {'option': 1})
941 with self.expect_error(
942 option="Expected type: <class 'str'> but received: <class 'list'>"
943 ):
944 self.get_config(Schema, {'option': []})
945
946 def test_with_unicode(self) -> None:
947 for cls in c.Dir, c.File, c.FilesystemObject:
948 with self.subTest(cls):
949
950 class Schema(Config):
951 dir = cls()
952
953 conf = self.get_config(Schema, {'dir': 'юникод'})
954 self.assertIsInstance(conf.dir, str)
955
956 def test_dir_bytes(self) -> None:
957 class Schema(Config):
958 dir = c.Dir()
959
960 with self.expect_error(dir="Expected type: <class 'str'> but received: <class 'bytes'>"):
961 self.get_config(Schema, {'dir': b'foo'})
962
963 def test_config_dir_prepended(self) -> None:
964 for cls in c.Dir, c.File, c.FilesystemObject:
965 with self.subTest(cls):
966 base_path = os.path.dirname(os.path.abspath(__file__))
967
968 class Schema(Config):
969 dir = cls()
970
971 conf = self.get_config(
972 Schema,
973 {'dir': 'foo'},
974 config_file_path=os.path.join(base_path, 'mkdocs.yml'),
975 )
976 self.assertEqual(conf.dir, os.path.join(base_path, 'foo'))
977
978 def test_site_dir_is_config_dir_fails(self) -> None:
979 class Schema(Config):
980 dir = c.DocsDir()
981
982 with self.expect_error(
983 dir="The 'dir' should not be the parent directory of the config file. "
984 "Use a child directory instead so that the 'dir' is a sibling of the config file."
985 ):
986 self.get_config(
987 Schema,
988 {'dir': '.'},
989 config_file_path=os.path.join(os.path.abspath('.'), 'mkdocs.yml'),
990 )
991
992
993 class ListOfPathsTest(TestCase):
994 def test_valid_path(self) -> None:
995 paths = [os.path.dirname(__file__)]
996
997 class Schema(Config):
998 option = c.ListOfPaths()
999
1000 self.get_config(Schema, {'option': paths})
1001
1002 def test_missing_path(self) -> None:
1003 paths = [os.path.join("does", "not", "exist", "i", "hope")]
1004
1005 class Schema(Config):
1006 option = c.ListOfPaths()
1007
1008 with self.expect_error(
1009 option=f"The path '{paths[0]}' isn't an existing file or directory."
1010 ):
1011 self.get_config(Schema, {'option': paths})
1012
1013 def test_non_path(self) -> None:
1014 paths = [os.path.dirname(__file__), None]
1015
1016 class Schema(Config):
1017 option = c.ListOfPaths()
1018
1019 with self.expect_error(
1020 option="Expected type: <class 'str'> but received: <class 'NoneType'>"
1021 ):
1022 self.get_config(Schema, {'option': paths})
1023
1024 def test_empty_list(self) -> None:
1025 class Schema(Config):
1026 option = c.ListOfPaths()
1027
1028 conf = self.get_config(Schema, {'option': []})
1029 assert_type(conf.option, List[str])
1030 self.assertEqual(conf.option, [])
1031
1032 def test_none(self) -> None:
1033 class Schema(Config):
1034 option = c.ListOfPaths()
1035
1036 with self.expect_error(option="Required configuration not provided."):
1037 self.get_config(Schema, {'option': None})
1038
1039 def test_non_list(self) -> None:
1040 paths = os.path.dirname(__file__)
1041
1042 class Schema(Config):
1043 option = c.ListOfPaths()
1044
1045 with self.expect_error(option="Expected a list of items, but a <class 'str'> was given."):
1046 self.get_config(Schema, {'option': paths})
1047
1048 def test_file(self) -> None:
1049 paths = [__file__]
1050
1051 class Schema(Config):
1052 option = c.ListOfPaths()
1053
1054 conf = self.get_config(Schema, {'option': paths})
1055 assert_type(conf.option, List[str])
1056
1057 @tempdir()
1058 def test_paths_localized_to_config(self, base_path) -> None:
1059 with open(os.path.join(base_path, 'foo'), 'w') as f:
1060 f.write('hi')
1061
1062 class Schema(Config):
1063 watch = c.ListOfPaths()
1064
1065 conf = self.get_config(
1066 Schema,
1067 {'watch': ['foo']},
1068 config_file_path=os.path.join(base_path, 'mkdocs.yml'),
1069 )
1070
1071 self.assertEqual(conf.watch, [os.path.join(base_path, 'foo')])
1072
1073
1074 class SiteDirTest(TestCase):
1075 class Schema(Config):
1076 site_dir = c.SiteDir()
1077 docs_dir = c.Dir()
1078
1079 def test_doc_dir_in_site_dir(self) -> None:
1080 j = os.path.join
1081 # The parent dir is not the same on every system, so use the actual dir name
1082 parent_dir = mkdocs.__file__.split(os.sep)[-3]
1083
1084 test_configs = (
1085 {'docs_dir': j('site', 'docs'), 'site_dir': 'site'},
1086 {'docs_dir': 'docs', 'site_dir': '.'},
1087 {'docs_dir': '.', 'site_dir': '.'},
1088 {'docs_dir': 'docs', 'site_dir': ''},
1089 {'docs_dir': '', 'site_dir': ''},
1090 {'docs_dir': j('..', parent_dir, 'docs'), 'site_dir': 'docs'},
1091 {'docs_dir': 'docs', 'site_dir': '/'},
1092 )
1093
1094 for test_config in test_configs:
1095 with self.subTest(test_config):
1096 with self.expect_error(
1097 site_dir=re.compile(r"The 'docs_dir' should not be within the 'site_dir'.*")
1098 ):
1099 self.get_config(self.Schema, test_config)
1100
1101 def test_site_dir_in_docs_dir(self) -> None:
1102 j = os.path.join
1103
1104 test_configs = (
1105 {'docs_dir': 'docs', 'site_dir': j('docs', 'site')},
1106 {'docs_dir': '.', 'site_dir': 'site'},
1107 {'docs_dir': '', 'site_dir': 'site'},
1108 {'docs_dir': '/', 'site_dir': 'site'},
1109 )
1110
1111 for test_config in test_configs:
1112 with self.subTest(test_config):
1113 with self.expect_error(
1114 site_dir=re.compile(r"The 'site_dir' should not be within the 'docs_dir'.*")
1115 ):
1116 self.get_config(self.Schema, test_config)
1117
1118 def test_common_prefix(self) -> None:
1119 """Legitimate settings with common prefixes should not fail validation."""
1120 test_configs = (
1121 {'docs_dir': 'docs', 'site_dir': 'docs-site'},
1122 {'docs_dir': 'site-docs', 'site_dir': 'site'},
1123 )
1124
1125 for test_config in test_configs:
1126 with self.subTest(test_config):
1127 self.get_config(self.Schema, test_config)
1128
1129
1130 class ThemeTest(TestCase):
1131 def test_theme_as_string(self) -> None:
1132 class Schema(Config):
1133 option = c.Theme()
1134
1135 conf = self.get_config(Schema, {'option': "mkdocs"})
1136 assert_type(conf.option, Theme)
1137 assert_type(conf.option.name, Optional[str])
1138 self.assertEqual(conf.option.name, 'mkdocs')
1139
1140 def test_uninstalled_theme_as_string(self) -> None:
1141 class Schema(Config):
1142 theme = c.Theme()
1143 plugins = c.Plugins(theme_key='theme')
1144
1145 with self.expect_error(
1146 theme=re.compile(
1147 r"Unrecognised theme name: 'mkdocs2'. The available installed themes are: .+"
1148 )
1149 ):
1150 self.get_config(Schema, {'theme': "mkdocs2", 'plugins': "search"})
1151
1152 def test_theme_default(self) -> None:
1153 class Schema(Config):
1154 option = c.Theme(default='mkdocs')
1155
1156 conf = self.get_config(Schema, {'option': None})
1157 self.assertEqual(conf.option.name, 'mkdocs')
1158
1159 def test_theme_as_simple_config(self) -> None:
1160 config = {
1161 'name': 'mkdocs',
1162 }
1163
1164 class Schema(Config):
1165 option = c.Theme()
1166
1167 conf = self.get_config(Schema, {'option': config})
1168 self.assertEqual(conf.option.name, 'mkdocs')
1169
1170 @tempdir()
1171 def test_theme_as_complex_config(self, custom_dir) -> None:
1172 config = {
1173 'name': 'mkdocs',
1174 'custom_dir': custom_dir,
1175 'static_templates': ['sitemap.html'],
1176 'show_sidebar': False,
1177 }
1178
1179 class Schema(Config):
1180 option = c.Theme()
1181
1182 conf = self.get_config(Schema, {'option': config})
1183 self.assertEqual(conf.option.name, 'mkdocs')
1184 self.assertEqual(conf.option.custom_dir, custom_dir)
1185 self.assertIn(custom_dir, conf.option.dirs)
1186 self.assertEqual(
1187 conf.option.static_templates,
1188 {'404.html', 'sitemap.xml', 'sitemap.html'},
1189 )
1190 self.assertEqual(conf.option['show_sidebar'], False)
1191
1192 def test_theme_name_is_none(self) -> None:
1193 config = {
1194 'name': None,
1195 }
1196
1197 class Schema(Config):
1198 option = c.Theme()
1199
1200 with self.expect_error(option="At least one of 'name' or 'custom_dir' must be defined."):
1201 self.get_config(Schema, {'option': config})
1202
1203 def test_theme_config_missing_name(self) -> None:
1204 config = {
1205 'custom_dir': 'custom',
1206 }
1207
1208 class Schema(Config):
1209 option = c.Theme()
1210
1211 with self.expect_error(option="No theme name set."):
1212 self.get_config(Schema, {'option': config})
1213
1214 def test_uninstalled_theme_as_config(self) -> None:
1215 config = {
1216 'name': 'mkdocs2',
1217 }
1218
1219 class Schema(Config):
1220 option = c.Theme()
1221
1222 with self.expect_error(
1223 option=re.compile(
1224 r"Unrecognised theme name: 'mkdocs2'. The available installed themes are: .+"
1225 )
1226 ):
1227 self.get_config(Schema, {'option': config})
1228
1229 def test_theme_invalid_type(self) -> None:
1230 config = ['mkdocs2']
1231
1232 class Schema(Config):
1233 option = c.Theme()
1234
1235 with self.expect_error(
1236 option="Invalid type <class 'list'>. Expected a string or key/value pairs."
1237 ):
1238 self.get_config(Schema, {'option': config})
1239
1240 def test_post_validation_none_theme_name_and_missing_custom_dir(self) -> None:
1241 config = {
1242 'theme': {
1243 'name': None,
1244 },
1245 }
1246
1247 class Schema(Config):
1248 theme = c.Theme()
1249
1250 with self.expect_error(theme="At least one of 'name' or 'custom_dir' must be defined."):
1251 self.get_config(Schema, config)
1252
1253 @tempdir()
1254 def test_post_validation_inexisting_custom_dir(self, abs_base_path) -> None:
1255 path = os.path.join(abs_base_path, 'inexisting_custom_dir')
1256 config = {
1257 'theme': {
1258 'name': None,
1259 'custom_dir': path,
1260 },
1261 }
1262
1263 class Schema(Config):
1264 theme = c.Theme()
1265
1266 with self.expect_error(theme=f"The path set in custom_dir ('{path}') does not exist."):
1267 self.get_config(Schema, config)
1268
1269 def test_post_validation_locale_none(self) -> None:
1270 config = {
1271 'theme': {
1272 'name': 'mkdocs',
1273 'locale': None,
1274 },
1275 }
1276
1277 class Schema(Config):
1278 theme = c.Theme()
1279
1280 with self.expect_error(theme="'locale' must be a string."):
1281 self.get_config(Schema, config)
1282
1283 def test_post_validation_locale_invalid_type(self) -> None:
1284 config = {
1285 'theme': {
1286 'name': 'mkdocs',
1287 'locale': 0,
1288 },
1289 }
1290
1291 class Schema(Config):
1292 theme = c.Theme()
1293
1294 with self.expect_error(theme="'locale' must be a string."):
1295 self.get_config(Schema, config)
1296
1297 def test_post_validation_locale(self) -> None:
1298 config = {
1299 'theme': {
1300 'name': 'mkdocs',
1301 'locale': 'fr',
1302 },
1303 }
1304
1305 class Schema(Config):
1306 theme = c.Theme()
1307
1308 conf = self.get_config(Schema, config)
1309 self.assertEqual(conf.theme.locale.language, 'fr')
1310
1311
1312 class NavTest(TestCase):
1313 class Schema(Config):
1314 option = c.Nav()
1315
1316 def test_old_format(self) -> None:
1317 with self.expect_error(
1318 option="Expected nav item to be a string or dict, got a list: ['index.md']"
1319 ):
1320 self.get_config(self.Schema, {'option': [['index.md']]})
1321
1322 def test_provided_dict(self) -> None:
1323 conf = self.get_config(self.Schema, {'option': ['index.md', {"Page": "page.md"}]})
1324 self.assertEqual(conf.option, ['index.md', {'Page': 'page.md'}])
1325
1326 def test_provided_empty(self) -> None:
1327 conf = self.get_config(self.Schema, {'option': []})
1328 self.assertEqual(conf.option, None)
1329
1330 def test_normal_nav(self) -> None:
1331 nav_yaml = textwrap.dedent(
1332 '''\
1333 - Home: index.md
1334 - getting-started.md
1335 - User Guide:
1336 - Overview: user-guide/index.md
1337 - Installation: user-guide/installation.md
1338 '''
1339 )
1340 nav = yaml_load(io.StringIO(nav_yaml))
1341
1342 conf = self.get_config(self.Schema, {'option': nav})
1343 self.assertEqual(conf.option, nav)
1344
1345 def test_invalid_type_dict(self) -> None:
1346 with self.expect_error(option="Expected nav to be a list, got a dict: {}"):
1347 self.get_config(self.Schema, {'option': {}})
1348
1349 def test_invalid_type_int(self) -> None:
1350 with self.expect_error(option="Expected nav to be a list, got a int: 5"):
1351 self.get_config(self.Schema, {'option': 5})
1352
1353 def test_invalid_item_int(self) -> None:
1354 with self.expect_error(option="Expected nav item to be a string or dict, got a int: 1"):
1355 self.get_config(self.Schema, {'option': [1]})
1356
1357 def test_invalid_item_none(self) -> None:
1358 with self.expect_error(option="Expected nav item to be a string or dict, got None"):
1359 self.get_config(self.Schema, {'option': [None]})
1360
1361 def test_invalid_children_config_int(self) -> None:
1362 with self.expect_error(option="Expected nav to be a list, got a int: 1"):
1363 self.get_config(self.Schema, {'option': [{"foo.md": [{"bar.md": 1}]}]})
1364
1365 def test_invalid_children_config_none(self) -> None:
1366 with self.expect_error(option="Expected nav to be a list, got None"):
1367 self.get_config(self.Schema, {'option': [{"foo.md": None}]})
1368
1369 def test_invalid_children_empty_dict(self) -> None:
1370 nav = ['foo', {}]
1371 with self.expect_error(option="Expected nav item to be a dict of size 1, got a dict: {}"):
1372 self.get_config(self.Schema, {'option': nav})
1373
1374 def test_invalid_nested_list(self) -> None:
1375 nav = [{'aaa': [[{"bbb": "user-guide/index.md"}]]}]
1376 with self.expect_error(
1377 option="Expected nav item to be a string or dict, got a list: [{'bbb': 'user-guide/index.md'}]"
1378 ):
1379 self.get_config(self.Schema, {'option': nav})
1380
1381 def test_invalid_children_oversized_dict(self) -> None:
1382 nav = [{"aaa": [{"bbb": "user-guide/index.md", "ccc": "user-guide/installation.md"}]}]
1383 with self.expect_error(
1384 option="Expected nav item to be a dict of size 1, got dict with keys ('bbb', 'ccc')"
1385 ):
1386 self.get_config(self.Schema, {'option': nav})
1387
1388 def test_warns_for_dict(self) -> None:
1389 self.get_config(
1390 self.Schema,
1391 {'option': [{"a": {"b": "c.md", "d": "e.md"}}]},
1392 warnings=dict(option="Expected nav to be a list, got dict with keys ('b', 'd')"),
1393 )
1394
1395
1396 class PrivateTest(TestCase):
1397 def test_defined(self) -> None:
1398 class Schema(Config):
1399 option = c.Private[Any]()
1400
1401 with self.expect_error(option="For internal use only."):
1402 self.get_config(Schema, {'option': 'somevalue'})
1403
1404
1405 class SubConfigTest(TestCase):
1406 def test_subconfig_wrong_type(self) -> None:
1407 # Test that an error is raised if subconfig does not receive a dict
1408 class Schema(Config):
1409 option = c.SubConfig()
1410
1411 for val in "not_a_dict", ("not_a_dict",), ["not_a_dict"]:
1412 with self.subTest(val):
1413 with self.expect_error(
1414 option=re.compile(
1415 r"The configuration is invalid. Expected a key-value mapping "
1416 r"\(dict\) but received: .+"
1417 )
1418 ):
1419 self.get_config(Schema, {'option': val})
1420
1421 def test_subconfig_unknown_option(self) -> None:
1422 class Schema(Config):
1423 option = c.SubConfig(validate=True)
1424
1425 conf = self.get_config(
1426 Schema,
1427 {'option': {'unknown': 0}},
1428 warnings=dict(option="Sub-option 'unknown': Unrecognised configuration name: unknown"),
1429 )
1430 self.assertEqual(conf.option, {"unknown": 0})
1431
1432 def test_subconfig_invalid_option(self) -> None:
1433 class Sub(Config):
1434 cc = c.Choice(('foo', 'bar'))
1435
1436 class Schema(Config):
1437 option = c.SubConfig(Sub)
1438
1439 with self.expect_error(
1440 option="Sub-option 'cc': Expected one of: ('foo', 'bar') but received: True"
1441 ):
1442 self.get_config(Schema, {'option': {'cc': True}})
1443
1444 def test_subconfig_normal(self) -> None:
1445 class Sub(Config):
1446 cc = c.Choice(('foo', 'bar'))
1447
1448 class Schema(Config):
1449 option = c.SubConfig(Sub)
1450
1451 conf = self.get_config(Schema, {'option': {'cc': 'foo'}})
1452 assert_type(conf.option, Sub)
1453 self.assertEqual(conf.option, {'cc': 'foo'})
1454 assert_type(conf.option.cc, str)
1455 self.assertEqual(conf.option.cc, 'foo')
1456
1457 def test_subconfig_with_multiple_items(self) -> None:
1458 # This had a bug where subsequent items would get merged into the same dict.
1459 class Sub(Config):
1460 value = c.Type(str)
1461
1462 class Schema(Config):
1463 the_items = c.ListOfItems(c.SubConfig(Sub))
1464
1465 conf = self.get_config(
1466 Schema,
1467 {
1468 'the_items': [
1469 {'value': 'a'},
1470 {'value': 'b'},
1471 ]
1472 },
1473 )
1474 assert_type(conf.the_items, List[Sub])
1475 self.assertEqual(conf.the_items, [{'value': 'a'}, {'value': 'b'}])
1476 assert_type(conf.the_items[1].value, str)
1477 self.assertEqual(conf.the_items[1].value, 'b')
1478
1479 def test_optional(self) -> None:
1480 class Sub(Config):
1481 opt = c.Optional(c.Type(int))
1482
1483 class Schema(Config):
1484 sub = c.Optional(c.ListOfItems(c.SubConfig(Sub)))
1485
1486 conf = self.get_config(Schema, {})
1487 self.assertEqual(conf.sub, None)
1488
1489 conf = self.get_config(Schema, {'sub': None})
1490 self.assertEqual(conf.sub, None)
1491
1492 conf = self.get_config(Schema, {'sub': [{'opt': 1}, {}]})
1493 assert_type(conf.sub, Optional[List[Sub]])
1494 self.assertEqual(conf.sub, [{'opt': 1}, {'opt': None}])
1495 assert conf.sub is not None
1496 assert_type(conf.sub[0].opt, Optional[int])
1497 self.assertEqual(conf.sub[0].opt, 1)
1498
1499 conf = self.get_config(Schema, {'sub': []})
1500
1501 conf = self.get_config(Schema, {'sub': [{'opt': 1}, {'opt': 2}]})
1502 self.assertEqual(conf.sub, [{'opt': 1}, {'opt': 2}])
1503
1504 def test_required(self) -> None:
1505 class Sub(Config):
1506 opt = c.Type(int)
1507
1508 class Schema(Config):
1509 sub = c.ListOfItems(c.SubConfig(Sub))
1510
1511 with self.expect_error(sub="Required configuration not provided."):
1512 conf = self.get_config(Schema, {})
1513
1514 with self.expect_error(sub="Required configuration not provided."):
1515 conf = self.get_config(Schema, {'sub': None})
1516
1517 with self.expect_error(
1518 sub="Sub-option 'opt': Expected type: <class 'int'> but received: <class 'str'>"
1519 ):
1520 conf = self.get_config(Schema, {'sub': [{'opt': 'asdf'}, {}]})
1521
1522 conf = self.get_config(Schema, {'sub': []})
1523
1524 conf = self.get_config(Schema, {'sub': [{'opt': 1}, {'opt': 2}]})
1525 assert_type(conf.sub, List[Sub])
1526 self.assertEqual(conf.sub, [{'opt': 1}, {'opt': 2}])
1527 assert_type(conf.sub[0].opt, int)
1528 self.assertEqual(conf.sub[0].opt, 1)
1529
1530 with self.expect_error(
1531 sub="Sub-option 'opt': Expected type: <class 'int'> but received: <class 'str'>"
1532 ):
1533 self.get_config(Schema, {'sub': [{'opt': 'z'}, {'opt': 2}]})
1534
1535 with self.expect_error(
1536 sub="Sub-option 'opt': Expected type: <class 'int'> but received: <class 'str'>"
1537 ):
1538 conf = self.get_config(Schema, {'sub': [{'opt': 'z'}, {'opt': 2}]})
1539
1540 with self.expect_error(
1541 sub="The configuration is invalid. Expected a key-value mapping "
1542 "(dict) but received: <class 'int'>"
1543 ):
1544 conf = self.get_config(Schema, {'sub': [1, 2]})
1545
1546 def test_default(self) -> None:
1547 class Sub(Config):
1548 opt = c.Type(int)
1549
1550 class Schema(Config):
1551 sub = c.ListOfItems(c.SubConfig(Sub), default=[])
1552
1553 conf = self.get_config(Schema, {})
1554 assert_type(conf.sub, List[Sub])
1555 self.assertEqual(conf.sub, [])
1556
1557 with self.expect_error(sub="Required configuration not provided."):
1558 conf = self.get_config(Schema, {'sub': None})
1559
1560 def test_config_file_path_pass_through(self) -> None:
1561 """Necessary to ensure FilesystemObject validates the correct path."""
1562 passed_config_path = None
1563
1564 class SubType(c.BaseConfigOption):
1565 def pre_validation(self, config: Config, key_name: str) -> None:
1566 nonlocal passed_config_path
1567 passed_config_path = config.config_file_path
1568
1569 class Sub(Config):
1570 opt = SubType()
1571
1572 class Schema(Config):
1573 sub = c.ListOfItems(c.SubConfig(Sub), default=[])
1574
1575 config_path = "foo/mkdocs.yaml"
1576 self.get_config(Schema, {"sub": [{"opt": "bar"}]}, config_file_path=config_path)
1577 self.assertEqual(passed_config_path, config_path)
1578
1579
1580 class NestedSubConfigTest(TestCase):
1581 def defaults(self):
1582 return {
1583 'nav': {
1584 'omitted_files': logging.INFO,
1585 'not_found': logging.WARNING,
1586 'absolute_links': logging.INFO,
1587 },
1588 'links': {
1589 'not_found': logging.WARNING,
1590 'absolute_links': logging.INFO,
1591 'unrecognized_links': logging.INFO,
1592 'anchors': logging.INFO,
1593 },
1594 }
1595
1596 class Schema(Config):
1597 validation = c.PropagatingSubConfig[defaults.MkDocsConfig.Validation]()
1598
1599 def test_unspecified(self) -> None:
1600 cfgs: list[dict] = [{}, {'validation': {}}]
1601 for cfg in cfgs:
1602 with self.subTest(cfg):
1603 conf = self.get_config(
1604 self.Schema,
1605 {},
1606 )
1607 self.assertEqual(conf.validation, self.defaults())
1608
1609 def test_sets_nested_and_not_nested(self) -> None:
1610 conf = self.get_config(
1611 self.Schema,
1612 {'validation': {'not_found': 'ignore', 'links': {'absolute_links': 'warn'}}},
1613 )
1614 expected = self.defaults()
1615 expected['nav']['not_found'] = logging.DEBUG
1616 expected['links']['not_found'] = logging.DEBUG
1617 expected['links']['absolute_links'] = logging.WARNING
1618 self.assertEqual(conf.validation, expected)
1619
1620 def test_sets_nested_different(self) -> None:
1621 conf = self.get_config(
1622 self.Schema,
1623 {'validation': {'not_found': 'ignore', 'links': {'not_found': 'warn'}}},
1624 )
1625 expected = self.defaults()
1626 expected['nav']['not_found'] = logging.DEBUG
1627 expected['links']['not_found'] = logging.WARNING
1628 self.assertEqual(conf.validation, expected)
1629
1630 def test_sets_only_one_nested(self) -> None:
1631 conf = self.get_config(
1632 self.Schema,
1633 {'validation': {'omitted_files': 'ignore'}},
1634 )
1635 expected = self.defaults()
1636 expected['nav']['omitted_files'] = logging.DEBUG
1637 self.assertEqual(conf.validation, expected)
1638
1639 def test_sets_nested_not_dict(self) -> None:
1640 with self.expect_error(
1641 validation="Sub-option 'links': Sub-option 'unrecognized_links': Expected a string, but a <class 'list'> was given."
1642 ):
1643 self.get_config(
1644 self.Schema,
1645 {'validation': {'unrecognized_links': [], 'links': {'absolute_links': 'warn'}}},
1646 )
1647
1648 def test_wrong_key_nested(self) -> None:
1649 conf = self.get_config(
1650 self.Schema,
1651 {'validation': {'foo': 'warn', 'not_found': 'warn'}},
1652 warnings=dict(validation="Sub-option 'foo': Unrecognised configuration name: foo"),
1653 )
1654 expected = self.defaults()
1655 expected['nav']['not_found'] = logging.WARNING
1656 expected['links']['not_found'] = logging.WARNING
1657 expected['foo'] = 'warn'
1658 self.assertEqual(conf.validation, expected)
1659
1660 def test_wrong_type_nested(self) -> None:
1661 with self.expect_error(
1662 validation="Sub-option 'nav': Sub-option 'omitted_files': Expected one of ['warn', 'info', 'ignore'], got 'hi'"
1663 ):
1664 self.get_config(
1665 self.Schema,
1666 {'validation': {'omitted_files': 'hi'}},
1667 )
1668
1669
1670 class MarkdownExtensionsTest(TestCase):
1671 @mock.patch('markdown.Markdown', mock.Mock())
1672 def test_simple_list(self) -> None:
1673 class Schema(Config):
1674 markdown_extensions = c.MarkdownExtensions()
1675 mdx_configs = c.Private[Dict[str, dict]]()
1676
1677 config = {
1678 'markdown_extensions': ['foo', 'bar'],
1679 }
1680 conf = self.get_config(Schema, config)
1681 assert_type(conf.markdown_extensions, List[str])
1682 assert_type(conf.mdx_configs, Dict[str, dict])
1683 self.assertEqual(conf.markdown_extensions, ['foo', 'bar'])
1684 self.assertEqual(conf.mdx_configs, {})
1685
1686 @mock.patch('markdown.Markdown', mock.Mock())
1687 def test_list_dicts(self) -> None:
1688 class Schema(Config):
1689 markdown_extensions = c.MarkdownExtensions()
1690 mdx_configs = c.Private[Dict[str, dict]]()
1691
1692 config = {
1693 'markdown_extensions': [
1694 {'foo': {'foo_option': 'foo value'}},
1695 {'bar': {'bar_option': 'bar value'}},
1696 {'baz': None},
1697 ]
1698 }
1699 conf = self.get_config(Schema, config)
1700 self.assertEqual(conf.markdown_extensions, ['foo', 'bar', 'baz'])
1701 self.assertEqual(
1702 conf.mdx_configs,
1703 {
1704 'foo': {'foo_option': 'foo value'},
1705 'bar': {'bar_option': 'bar value'},
1706 },
1707 )
1708
1709 @mock.patch('markdown.Markdown', mock.Mock())
1710 def test_mixed_list(self) -> None:
1711 class Schema(Config):
1712 markdown_extensions = c.MarkdownExtensions()
1713 mdx_configs = c.Private[Dict[str, dict]]()
1714
1715 config = {
1716 'markdown_extensions': [
1717 'foo',
1718 {'bar': {'bar_option': 'bar value'}},
1719 ]
1720 }
1721 conf = self.get_config(Schema, config)
1722 self.assertEqual(conf.markdown_extensions, ['foo', 'bar'])
1723 self.assertEqual(
1724 conf.mdx_configs,
1725 {
1726 'bar': {'bar_option': 'bar value'},
1727 },
1728 )
1729
1730 @mock.patch('markdown.Markdown', mock.Mock())
1731 def test_dict_of_dicts(self) -> None:
1732 class Schema(Config):
1733 markdown_extensions = c.MarkdownExtensions()
1734 mdx_configs = c.Private[Dict[str, dict]]()
1735
1736 config = {
1737 'markdown_extensions': {
1738 'foo': {'foo_option': 'foo value'},
1739 'bar': {'bar_option': 'bar value'},
1740 'baz': {},
1741 }
1742 }
1743 conf = self.get_config(Schema, config)
1744 self.assertEqual(conf.markdown_extensions, ['foo', 'bar', 'baz'])
1745 self.assertEqual(
1746 conf.mdx_configs,
1747 {
1748 'foo': {'foo_option': 'foo value'},
1749 'bar': {'bar_option': 'bar value'},
1750 },
1751 )
1752
1753 @mock.patch('markdown.Markdown', mock.Mock())
1754 def test_builtins(self) -> None:
1755 class Schema(Config):
1756 markdown_extensions = c.MarkdownExtensions(builtins=['meta', 'toc'])
1757 mdx_configs = c.Private[Dict[str, dict]]()
1758
1759 config = {
1760 'markdown_extensions': ['foo', 'bar'],
1761 }
1762 conf = self.get_config(Schema, config)
1763 self.assertEqual(conf.markdown_extensions, ['meta', 'toc', 'foo', 'bar'])
1764 self.assertEqual(conf.mdx_configs, {})
1765
1766 def test_duplicates(self) -> None:
1767 class Schema(Config):
1768 markdown_extensions = c.MarkdownExtensions(builtins=['meta', 'toc'])
1769 mdx_configs = c.Private[Dict[str, dict]]()
1770
1771 config = {
1772 'markdown_extensions': ['meta', 'toc'],
1773 }
1774 conf = self.get_config(Schema, config)
1775 self.assertEqual(conf.markdown_extensions, ['meta', 'toc'])
1776 self.assertEqual(conf.mdx_configs, {})
1777
1778 def test_builtins_config(self) -> None:
1779 class Schema(Config):
1780 markdown_extensions = c.MarkdownExtensions(builtins=['meta', 'toc'])
1781 mdx_configs = c.Private[Dict[str, dict]]()
1782
1783 config = {
1784 'markdown_extensions': [
1785 {'toc': {'permalink': True}},
1786 ],
1787 }
1788 conf = self.get_config(Schema, config)
1789 self.assertEqual(conf.markdown_extensions, ['meta', 'toc'])
1790 self.assertEqual(conf.mdx_configs, {'toc': {'permalink': True}})
1791
1792 @mock.patch('markdown.Markdown', mock.Mock())
1793 def test_configkey(self) -> None:
1794 class Schema(Config):
1795 markdown_extensions = c.MarkdownExtensions(configkey='bar')
1796 bar = c.Private[Dict[str, dict]]()
1797
1798 config = {
1799 'markdown_extensions': [
1800 {'foo': {'foo_option': 'foo value'}},
1801 ]
1802 }
1803 conf = self.get_config(Schema, config)
1804 self.assertEqual(conf.markdown_extensions, ['foo'])
1805 self.assertEqual(
1806 conf.bar,
1807 {
1808 'foo': {'foo_option': 'foo value'},
1809 },
1810 )
1811
1812 def test_missing_default(self) -> None:
1813 class Schema(Config):
1814 markdown_extensions = c.MarkdownExtensions()
1815 mdx_configs = c.Private[Dict[str, dict]]()
1816
1817 conf = self.get_config(Schema, {})
1818 self.assertEqual(conf.markdown_extensions, [])
1819 self.assertEqual(conf.mdx_configs, {})
1820
1821 def test_none(self) -> None:
1822 class Schema(Config):
1823 markdown_extensions = c.MarkdownExtensions(default=[])
1824 mdx_configs = c.Private[Dict[str, dict]]()
1825
1826 config = {
1827 'markdown_extensions': None,
1828 }
1829 conf = self.get_config(Schema, config)
1830 self.assertEqual(conf.markdown_extensions, [])
1831 self.assertEqual(conf.mdx_configs, {})
1832
1833 @mock.patch('markdown.Markdown', mock.Mock())
1834 def test_not_list(self) -> None:
1835 class Schema(Config):
1836 option = c.MarkdownExtensions()
1837
1838 with self.expect_error(option="Invalid Markdown Extensions configuration"):
1839 self.get_config(Schema, {'option': 'not a list'})
1840
1841 @mock.patch('markdown.Markdown', mock.Mock())
1842 def test_invalid_config_option(self) -> None:
1843 class Schema(Config):
1844 markdown_extensions = c.MarkdownExtensions()
1845
1846 config = {
1847 'markdown_extensions': [
1848 {'foo': 'not a dict'},
1849 ],
1850 }
1851 with self.expect_error(
1852 markdown_extensions="Invalid config options for Markdown Extension 'foo'."
1853 ):
1854 self.get_config(Schema, config)
1855
1856 @mock.patch('markdown.Markdown', mock.Mock())
1857 def test_invalid_config_item(self) -> None:
1858 class Schema(Config):
1859 markdown_extensions = c.MarkdownExtensions()
1860
1861 config = {
1862 'markdown_extensions': [
1863 ['not a dict'],
1864 ],
1865 }
1866 with self.expect_error(markdown_extensions="Invalid Markdown Extensions configuration"):
1867 self.get_config(Schema, config)
1868
1869 @mock.patch('markdown.Markdown', mock.Mock())
1870 def test_invalid_dict_item(self) -> None:
1871 class Schema(Config):
1872 markdown_extensions = c.MarkdownExtensions()
1873
1874 config = {
1875 'markdown_extensions': [
1876 {'key1': 'value', 'key2': 'too many keys'},
1877 ],
1878 }
1879 with self.expect_error(markdown_extensions="Invalid Markdown Extensions configuration"):
1880 self.get_config(Schema, config)
1881
1882 def test_unknown_extension(self) -> None:
1883 class Schema(Config):
1884 markdown_extensions = c.MarkdownExtensions()
1885
1886 config = {
1887 'markdown_extensions': ['unknown'],
1888 }
1889 with self.expect_error(
1890 markdown_extensions=re.compile(r"Failed to load extension 'unknown'.\n.+")
1891 ):
1892 self.get_config(Schema, config)
1893
1894 def test_multiple_markdown_config_instances(self) -> None:
1895 # This had a bug where an extension config would persist to separate
1896 # config instances that didn't specify extensions.
1897 class Schema(Config):
1898 markdown_extensions = c.MarkdownExtensions()
1899 mdx_configs = c.Private[Dict[str, dict]]()
1900
1901 conf = self.get_config(
1902 Schema,
1903 {
1904 'markdown_extensions': [{'toc': {'permalink': '##'}}],
1905 },
1906 )
1907 self.assertEqual(conf.mdx_configs['toc'], {'permalink': '##'})
1908
1909 conf = self.get_config(
1910 Schema,
1911 {},
1912 )
1913 self.assertIsNone(conf.mdx_configs.get('toc'))
1914
1915
1916 class _FakePluginConfig(Config):
1917 foo = c.Type(str, default='default foo')
1918 bar = c.Type(int, default=0)
1919 dir = c.Optional(c.Dir(exists=False))
1920
1921
1922 class FakePlugin(BasePlugin[_FakePluginConfig]):
1923 pass
1924
1925
1926 class _FakePlugin2Config(_FakePluginConfig):
1927 depr = c.Deprecated()
1928
1929
1930 class FakePlugin2(BasePlugin[_FakePlugin2Config]):
1931 supports_multiple_instances = True
1932
1933
1934 class _EnabledPluginConfig(Config):
1935 enabled = c.Type(bool, default=True)
1936 bar = c.Type(int, default=0)
1937
1938
1939 class EnabledPlugin(BasePlugin[_EnabledPluginConfig]):
1940 pass
1941
1942
1943 class ThemePlugin(BasePlugin[_FakePluginConfig]):
1944 pass
1945
1946
1947 class ThemePlugin2(BasePlugin[_FakePluginConfig]):
1948 pass
1949
1950
1951 class FakeEntryPoint:
1952 def __init__(self, name, cls):
1953 self.name = name
1954 self.cls = cls
1955
1956 def load(self):
1957 return self.cls
1958
1959
1960 @mock.patch(
1961 'mkdocs.plugins.entry_points',
1962 mock.Mock(
1963 return_value=[
1964 FakeEntryPoint('sample', FakePlugin),
1965 FakeEntryPoint('sample2', FakePlugin2),
1966 FakeEntryPoint('sample-e', EnabledPlugin),
1967 FakeEntryPoint('readthedocs/sub_plugin', ThemePlugin),
1968 FakeEntryPoint('overridden', FakePlugin2),
1969 FakeEntryPoint('readthedocs/overridden', ThemePlugin2),
1970 ]
1971 ),
1972 )
1973 class PluginsTest(TestCase):
1974 def test_plugin_config_without_options(self) -> None:
1975 class Schema(Config):
1976 plugins = c.Plugins()
1977
1978 cfg = {
1979 'plugins': ['sample'],
1980 }
1981 conf = self.get_config(Schema, cfg)
1982
1983 assert_type(conf.plugins, PluginCollection)
1984 self.assertIsInstance(conf.plugins, PluginCollection)
1985 self.assertIn('sample', conf.plugins)
1986
1987 plugin = conf.plugins['sample']
1988 assert_type(plugin, BasePlugin)
1989 self.assertIsInstance(plugin, FakePlugin)
1990 self.assertIsInstance(plugin.config, _FakePluginConfig)
1991 expected = {
1992 'foo': 'default foo',
1993 'bar': 0,
1994 'dir': None,
1995 }
1996 self.assertEqual(plugin.config, expected)
1997
1998 def test_plugin_config_with_options(self) -> None:
1999 class Schema(Config):
2000 plugins = c.Plugins()
2001
2002 cfg = {
2003 'plugins': [
2004 {
2005 'sample': {
2006 'foo': 'foo value',
2007 'bar': 42,
2008 },
2009 }
2010 ],
2011 }
2012 conf = self.get_config(Schema, cfg)
2013
2014 self.assertIsInstance(conf.plugins, PluginCollection)
2015 self.assertIn('sample', conf.plugins)
2016 self.assertIsInstance(conf.plugins['sample'], BasePlugin)
2017 expected = {
2018 'foo': 'foo value',
2019 'bar': 42,
2020 'dir': None,
2021 }
2022 self.assertEqual(conf.plugins['sample'].config, expected)
2023
2024 def test_plugin_config_as_dict(self) -> None:
2025 class Schema(Config):
2026 plugins = c.Plugins()
2027
2028 cfg = {
2029 'plugins': {
2030 'sample': {
2031 'foo': 'foo value',
2032 'bar': 42,
2033 },
2034 },
2035 }
2036 conf = self.get_config(Schema, cfg)
2037
2038 self.assertIsInstance(conf.plugins, PluginCollection)
2039 self.assertIn('sample', conf.plugins)
2040 self.assertIsInstance(conf.plugins['sample'], BasePlugin)
2041 expected = {
2042 'foo': 'foo value',
2043 'bar': 42,
2044 'dir': None,
2045 }
2046 self.assertEqual(conf.plugins['sample'].config, expected)
2047
2048 def test_plugin_config_with_explicit_theme_namespace(self) -> None:
2049 class Schema(Config):
2050 theme = c.Theme(default='mkdocs')
2051 plugins = c.Plugins(theme_key='theme')
2052
2053 cfg = {'theme': 'readthedocs', 'plugins': ['readthedocs/sub_plugin']}
2054 conf = self.get_config(Schema, cfg)
2055
2056 self.assertEqual(set(conf.plugins), {'readthedocs/sub_plugin'})
2057 self.assertIsInstance(conf.plugins['readthedocs/sub_plugin'], ThemePlugin)
2058
2059 cfg = {'plugins': ['readthedocs/sub_plugin']}
2060 conf = self.get_config(Schema, cfg)
2061
2062 self.assertEqual(set(conf.plugins), {'readthedocs/sub_plugin'})
2063 self.assertIsInstance(conf.plugins['readthedocs/sub_plugin'], ThemePlugin)
2064
2065 def test_plugin_config_with_deduced_theme_namespace(self) -> None:
2066 class Schema(Config):
2067 theme = c.Theme(default='mkdocs')
2068 plugins = c.Plugins(theme_key='theme')
2069
2070 cfg = {'theme': 'readthedocs', 'plugins': ['sub_plugin']}
2071 conf = self.get_config(Schema, cfg)
2072
2073 self.assertEqual(set(conf.plugins), {'readthedocs/sub_plugin'})
2074 self.assertIsInstance(conf.plugins['readthedocs/sub_plugin'], ThemePlugin)
2075
2076 cfg = {'plugins': ['sub_plugin']}
2077 with self.expect_error(plugins='The "sub_plugin" plugin is not installed'):
2078 self.get_config(Schema, cfg)
2079
2080 def test_plugin_config_with_deduced_theme_namespace_overridden(self) -> None:
2081 class Schema(Config):
2082 theme = c.Theme(default='mkdocs')
2083 plugins = c.Plugins(theme_key='theme')
2084
2085 cfg = {'theme': 'readthedocs', 'plugins': ['overridden']}
2086 conf = self.get_config(Schema, cfg)
2087
2088 self.assertEqual(set(conf.plugins), {'readthedocs/overridden'})
2089 self.assertIsInstance(next(iter(conf.plugins.values())), ThemePlugin2)
2090
2091 cfg = {'plugins': ['overridden']}
2092 conf = self.get_config(Schema, cfg)
2093
2094 self.assertEqual(set(conf.plugins), {'overridden'})
2095 self.assertIsInstance(conf.plugins['overridden'], FakePlugin2)
2096
2097 def test_plugin_config_with_explicit_empty_namespace(self) -> None:
2098 class Schema(Config):
2099 theme = c.Theme(default='mkdocs')
2100 plugins = c.Plugins(theme_key='theme')
2101
2102 cfg = {'theme': 'readthedocs', 'plugins': ['/overridden']}
2103 conf = self.get_config(Schema, cfg)
2104
2105 self.assertEqual(set(conf.plugins), {'overridden'})
2106 self.assertIsInstance(next(iter(conf.plugins.values())), FakePlugin2)
2107
2108 cfg = {'plugins': ['/overridden']}
2109 conf = self.get_config(Schema, cfg)
2110
2111 self.assertEqual(set(conf.plugins), {'overridden'})
2112 self.assertIsInstance(conf.plugins['overridden'], FakePlugin2)
2113
2114 def test_plugin_config_enabled_for_any_plugin(self) -> None:
2115 class Schema(Config):
2116 theme = c.Theme(default='mkdocs')
2117 plugins = c.Plugins(theme_key='theme')
2118
2119 cfg = {'theme': 'readthedocs', 'plugins': {'sample': {'enabled': False, 'bar': 3}}}
2120 conf = self.get_config(Schema, cfg)
2121 self.assertEqual(set(conf.plugins), set())
2122
2123 cfg = {'theme': 'readthedocs', 'plugins': {'sample': {'enabled': True, 'bar': 3}}}
2124 conf = self.get_config(Schema, cfg)
2125 self.assertEqual(set(conf.plugins), {'sample'})
2126 self.assertEqual(conf.plugins['sample'].config.bar, 3)
2127
2128 cfg = {'theme': 'readthedocs', 'plugins': {'sample': {'enabled': 5}}}
2129 with self.expect_error(
2130 plugins="Plugin 'sample' option 'enabled': Expected boolean but received: <class 'int'>"
2131 ):
2132 self.get_config(Schema, cfg)
2133
2134 def test_plugin_config_enabled_for_plugin_with_setting(self) -> None:
2135 class Schema(Config):
2136 theme = c.Theme(default='mkdocs')
2137 plugins = c.Plugins(theme_key='theme')
2138
2139 cfg = {'theme': 'readthedocs', 'plugins': {'sample-e': {'enabled': False, 'bar': 3}}}
2140 conf = self.get_config(Schema, cfg)
2141 self.assertEqual(set(conf.plugins), {'sample-e'})
2142 self.assertEqual(conf.plugins['sample-e'].config.enabled, False)
2143 self.assertEqual(conf.plugins['sample-e'].config.bar, 3)
2144
2145 cfg = {'theme': 'readthedocs', 'plugins': {'sample-e': {'enabled': True, 'bar': 3}}}
2146 conf = self.get_config(Schema, cfg)
2147 self.assertEqual(set(conf.plugins), {'sample-e'})
2148 self.assertEqual(conf.plugins['sample-e'].config.enabled, True)
2149 self.assertEqual(conf.plugins['sample-e'].config.bar, 3)
2150
2151 cfg = {'theme': 'readthedocs', 'plugins': {'sample-e': {'enabled': 5}}}
2152 with self.expect_error(
2153 plugins="Plugin 'sample-e' option 'enabled': Expected type: <class 'bool'> but received: <class 'int'>"
2154 ):
2155 self.get_config(Schema, cfg)
2156
2157 def test_plugin_config_with_multiple_instances(self) -> None:
2158 class Schema(Config):
2159 theme = c.Theme(default='mkdocs')
2160 plugins = c.Plugins(theme_key='theme')
2161
2162 cfg = {
2163 'plugins': [
2164 {'sample2': {'foo': 'foo value', 'bar': 42}},
2165 {'sample2': {'foo': 'foo2 value'}},
2166 ],
2167 }
2168 conf = self.get_config(Schema, cfg)
2169
2170 self.assertEqual(
2171 set(conf.plugins),
2172 {'sample2', 'sample2 #2'},
2173 )
2174 self.assertEqual(conf.plugins['sample2'].config['bar'], 42)
2175 self.assertEqual(conf.plugins['sample2 #2'].config['bar'], 0)
2176
2177 def test_plugin_config_with_multiple_instances_and_warning(self) -> None:
2178 class Schema(Config):
2179 theme = c.Theme(default='mkdocs')
2180 plugins = c.Plugins(theme_key='theme')
2181
2182 test_cfgs: list[dict[str, Any]] = [
2183 {
2184 'theme': 'readthedocs',
2185 'plugins': [{'sub_plugin': {}}, {'sample2': {}}, {'sub_plugin': {}}, 'sample2'],
2186 },
2187 {
2188 'theme': 'readthedocs',
2189 'plugins': ['sub_plugin', 'sample2', 'sample2', 'sub_plugin'],
2190 },
2191 ]
2192
2193 for cfg in test_cfgs:
2194 conf = self.get_config(
2195 Schema,
2196 cfg,
2197 warnings=dict(
2198 plugins="Plugin 'readthedocs/sub_plugin' was specified multiple times - "
2199 "this is likely a mistake, because the plugin doesn't declare "
2200 "`supports_multiple_instances`."
2201 ),
2202 )
2203 self.assertEqual(
2204 set(conf.plugins),
2205 {'readthedocs/sub_plugin', 'readthedocs/sub_plugin #2', 'sample2', 'sample2 #2'},
2206 )
2207
2208 def test_plugin_config_empty_list_with_empty_default(self) -> None:
2209 class Schema(Config):
2210 plugins = c.Plugins(default=[])
2211
2212 cfg: dict[str, Any] = {'plugins': []}
2213 conf = self.get_config(Schema, cfg)
2214
2215 self.assertIsInstance(conf.plugins, PluginCollection)
2216 self.assertEqual(len(conf.plugins), 0)
2217
2218 def test_plugin_config_empty_list_with_default(self) -> None:
2219 class Schema(Config):
2220 plugins = c.Plugins(default=['sample'])
2221
2222 # Default is ignored
2223 cfg: dict[str, Any] = {'plugins': []}
2224 conf = self.get_config(Schema, cfg)
2225
2226 self.assertIsInstance(conf.plugins, PluginCollection)
2227 self.assertEqual(len(conf.plugins), 0)
2228
2229 def test_plugin_config_none_with_empty_default(self) -> None:
2230 class Schema(Config):
2231 plugins = c.Plugins(default=[])
2232
2233 cfg = {'plugins': None}
2234 conf = self.get_config(Schema, cfg)
2235
2236 self.assertIsInstance(conf.plugins, PluginCollection)
2237 self.assertEqual(len(conf.plugins), 0)
2238
2239 def test_plugin_config_none_with_default(self) -> None:
2240 class Schema(Config):
2241 plugins = c.Plugins(default=['sample'])
2242
2243 # Default is used.
2244 cfg = {'plugins': None}
2245 conf = self.get_config(Schema, cfg)
2246
2247 self.assertIsInstance(conf.plugins, PluginCollection)
2248 self.assertIn('sample', conf.plugins)
2249 self.assertIsInstance(conf.plugins['sample'], BasePlugin)
2250 expected = {
2251 'foo': 'default foo',
2252 'bar': 0,
2253 'dir': None,
2254 }
2255 self.assertEqual(conf.plugins['sample'].config, expected)
2256
2257 def test_plugin_config_uninstalled(self) -> None:
2258 class Schema(Config):
2259 plugins = c.Plugins()
2260
2261 cfg = {'plugins': ['uninstalled']}
2262 with self.expect_error(plugins='The "uninstalled" plugin is not installed'):
2263 self.get_config(Schema, cfg)
2264
2265 def test_plugin_config_not_list(self) -> None:
2266 class Schema(Config):
2267 plugins = c.Plugins()
2268
2269 cfg = {'plugins': 'sample'}
2270 with self.expect_error(plugins="Invalid Plugins configuration. Expected a list or dict."):
2271 self.get_config(Schema, cfg)
2272
2273 def test_plugin_config_multivalue_dict(self) -> None:
2274 class Schema(Config):
2275 plugins = c.Plugins()
2276
2277 cfg = {
2278 'plugins': [
2279 {
2280 'sample': {
2281 'foo': 'foo value',
2282 'bar': 42,
2283 },
2284 'extra_key': 'baz',
2285 }
2286 ],
2287 }
2288 with self.expect_error(plugins="Invalid Plugins configuration"):
2289 self.get_config(Schema, cfg)
2290
2291 cfg = {
2292 'plugins': [
2293 {},
2294 ],
2295 }
2296 with self.expect_error(plugins="Invalid Plugins configuration"):
2297 self.get_config(Schema, cfg)
2298
2299 def test_plugin_config_not_string_or_dict(self) -> None:
2300 class Schema(Config):
2301 plugins = c.Plugins()
2302
2303 cfg = {
2304 'plugins': [('not a string or dict',)],
2305 }
2306 with self.expect_error(plugins="'('not a string or dict',)' is not a valid plugin name."):
2307 self.get_config(Schema, cfg)
2308
2309 def test_plugin_config_options_not_dict(self) -> None:
2310 class Schema(Config):
2311 plugins = c.Plugins()
2312
2313 cfg = {
2314 'plugins': [{'sample': 'not a dict'}],
2315 }
2316 with self.expect_error(plugins="Invalid config options for the 'sample' plugin."):
2317 self.get_config(Schema, cfg)
2318
2319 def test_plugin_config_sub_error(self) -> None:
2320 class Schema(Config):
2321 plugins = c.Plugins(default=['sample'])
2322
2323 cfg = {
2324 'plugins': {
2325 'sample': {'bar': 'not an int'},
2326 }
2327 }
2328 with self.expect_error(
2329 plugins="Plugin 'sample' option 'bar': Expected type: <class 'int'> but received: <class 'str'>"
2330 ):
2331 self.get_config(Schema, cfg)
2332
2333 def test_plugin_config_sub_warning(self) -> None:
2334 class Schema(Config):
2335 plugins = c.Plugins()
2336
2337 cfg = {
2338 'plugins': {
2339 'sample2': {'depr': 'deprecated value'},
2340 }
2341 }
2342 conf = self.get_config(
2343 Schema,
2344 cfg,
2345 warnings=dict(
2346 plugins="Plugin 'sample2' option 'depr': The configuration option "
2347 "'depr' has been deprecated and will be removed in a future release."
2348 ),
2349 )
2350
2351 self.assertIsInstance(conf.plugins, PluginCollection)
2352 self.assertIn('sample2', conf.plugins)
2353
2354
2355 class HooksTest(TestCase):
2356 class Schema(Config):
2357 plugins = c.Plugins(default=[])
2358 hooks = c.Hooks('plugins')
2359
2360 @tempdir()
2361 def test_hooks(self, src_dir) -> None:
2362 write_file(
2363 b'def on_page_markdown(markdown, **kwargs): return markdown.replace("f", "z")',
2364 os.path.join(src_dir, 'hooks', 'my_hook.py'),
2365 )
2366 write_file(
2367 b'foo foo',
2368 os.path.join(src_dir, 'docs', 'index.md'),
2369 )
2370 conf = self.get_config(
2371 self.Schema,
2372 {'hooks': ['hooks/my_hook.py']},
2373 config_file_path=os.path.join(src_dir, 'mkdocs.yml'),
2374 )
2375 self.assertIn('hooks/my_hook.py', conf.plugins)
2376 hook = conf.plugins['hooks/my_hook.py']
2377 self.assertTrue(hasattr(hook, 'on_page_markdown'))
2378 self.assertEqual(
2379 {**conf.plugins.events, 'page_markdown': [hook.on_page_markdown]},
2380 conf.plugins.events,
2381 )
2382 self.assertEqual(hook.on_page_markdown('foo foo'), 'zoo zoo') # type: ignore[call-arg]
2383 self.assertFalse(hasattr(hook, 'on_nav'))
2384
2385 def test_hooks_wrong_type(self) -> None:
2386 with self.expect_error(hooks="Expected a list of items, but a <class 'int'> was given."):
2387 self.get_config(self.Schema, {'hooks': 6})
2388
2389 with self.expect_error(hooks="Expected type: <class 'str'> but received: <class 'int'>"):
2390 self.get_config(self.Schema, {'hooks': [7]})
2391
2392
2393 class SchemaTest(TestCase):
2394 def test_copy(self) -> None:
2395 class Schema(Config):
2396 foo = c.MarkdownExtensions()
2397
2398 copy.deepcopy(Schema())
2399
2400 copy.deepcopy(self.get_config(IpAddressTest.Schema, {'option': '1.2.3.4:5678'}))
2401 copy.deepcopy(IpAddressTest.Schema)
2402 copy.deepcopy(IpAddressTest.Schema())
2403
2404 copy.deepcopy(self.get_config(EditURITest.Schema, {}))
2405 copy.deepcopy(EditURITest.Schema)
2406 copy.deepcopy(EditURITest.Schema())
2407
2408 def test_subclass(self) -> None:
2409 class A(Config):
2410 foo = c.Type(int)
2411 bar = c.Optional(c.Type(str))
2412
2413 class B(A):
2414 baz = c.ListOfItems(c.Type(str))
2415
2416 conf = self.get_config(B, {'foo': 1, 'baz': ['b']})
2417 assert_type(conf.foo, int)
2418 self.assertEqual(conf.foo, 1)
2419 assert_type(conf.bar, Optional[str])
2420 self.assertEqual(conf.bar, None)
2421 assert_type(conf.baz, List[str])
2422 self.assertEqual(conf.baz, ['b'])
2423
2424 with self.expect_error(baz="Required configuration not provided."):
2425 self.get_config(B, {'foo': 1})
2426 with self.expect_error(foo="Required configuration not provided."):
2427 self.get_config(B, {'baz': ['b']})
2428
2429 bconf = self.get_config(A, {'foo': 2, 'bar': 'a'})
2430 assert_type(bconf.foo, int)
2431 self.assertEqual(bconf.foo, 2)
2432 self.assertEqual(bconf.bar, 'a')