Debian Codegraph @

mkdocs/tests/base.py

raw
1 from __future__ import annotations
2
3 import contextlib
4 import os
5 import textwrap
6 from functools import wraps
7 from tempfile import TemporaryDirectory
8
9 import markdown
10
11 from mkdocs import utils
12 from mkdocs.config.defaults import MkDocsConfig
13
14
15 def dedent(text):
16 return textwrap.dedent(text).strip()
17
18
19 def get_markdown_toc(markdown_source):
20 """Return TOC generated by Markdown parser from Markdown source text."""
21 md = markdown.Markdown(extensions=['toc'])
22 md.convert(markdown_source)
23 return md.toc_tokens
24
25
26 def load_config(config_file_path: str | None = None, **cfg) -> MkDocsConfig:
27 """Helper to build a simple config for testing."""
28 path_base = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'integration', 'minimal')
29 if 'site_name' not in cfg:
30 cfg['site_name'] = 'Example'
31 if 'docs_dir' not in cfg:
32 # Point to an actual dir to avoid a 'does not exist' error on validation.
33 cfg['docs_dir'] = os.path.join(path_base, 'docs')
34 if 'plugins' not in cfg:
35 cfg['plugins'] = []
36 conf = MkDocsConfig(config_file_path=config_file_path or os.path.join(path_base, 'mkdocs.yml'))
37 conf.load_dict(cfg)
38
39 errors_warnings = conf.validate()
40 assert errors_warnings == ([], []), errors_warnings
41 return conf
42
43
44 def tempdir(files=None, **kw):
45 """
46 A decorator for building a temporary directory with prepopulated files.
47
48 The temporary directory and files are created just before the wrapped function is called and are destroyed
49 immediately after the wrapped function returns.
50
51 The `files` keyword should be a dict of file paths as keys and strings of file content as values.
52 If `files` is a list, then each item is assumed to be a path of an empty file. All other
53 keywords are passed to `tempfile.TemporaryDirectory` to create the parent directory.
54
55 In the following example, two files are created in the temporary directory and then are destroyed when
56 the function exits:
57
58 @tempdir(files={
59 'foo.txt': 'foo content',
60 'bar.txt': 'bar content'
61 })
62 def example(self, tdir):
63 assert os.path.isfile(os.path.join(tdir, 'foo.txt'))
64 pth = os.path.join(tdir, 'bar.txt')
65 assert os.path.isfile(pth)
66 with open(pth, 'r', encoding='utf-8') as f:
67 assert f.read() == 'bar content'
68 """
69 files = {f: '' for f in files} if isinstance(files, (list, tuple)) else files or {}
70
71 kw['prefix'] = 'mkdocs_test-' + kw.get('prefix', '')
72
73 def decorator(fn):
74 @wraps(fn)
75 def wrapper(self, *args):
76 with TemporaryDirectory(**kw) as td:
77 for path, content in files.items():
78 pth = os.path.join(td, path)
79 utils.write_file(content.encode(encoding='utf-8'), pth)
80 return fn(self, td, *args)
81
82 return wrapper
83
84 return decorator
85
86
87 @contextlib.contextmanager
88 def change_dir(path):
89 old_cwd = os.getcwd()
90 os.chdir(path)
91 try:
92 yield
93 finally:
94 os.chdir(old_cwd)
95
96
97 class PathAssertionMixin:
98 """
99 Assertion methods for testing paths.
100
101 Each method accepts one or more strings, which are first joined using os.path.join.
102 """
103
104 def assertPathsEqual(self, a, b, msg=None):
105 self.assertEqual(a.replace(os.sep, '/'), b.replace(os.sep, '/'), msg=msg)
106
107 def assertPathExists(self, *parts):
108 path = os.path.join(*parts)
109 if not os.path.exists(path):
110 msg = self._formatMessage(None, f"The path '{path}' does not exist")
111 raise self.failureException(msg)
112
113 def assertPathNotExists(self, *parts):
114 path = os.path.join(*parts)
115 if os.path.exists(path):
116 msg = self._formatMessage(None, f"The path '{path}' does exist")
117 raise self.failureException(msg)
118
119 def assertPathIsFile(self, *parts):
120 path = os.path.join(*parts)
121 if not os.path.isfile(path):
122 msg = self._formatMessage(None, f"The path '{path}' is not a file that exists")
123 raise self.failureException(msg)
124
125 def assertPathIsDir(self, *parts):
126 path = os.path.join(*parts)
127 if not os.path.isdir(path):
128 msg = self._formatMessage(None, f"The path '{path}' is not a directory that exists")
129 raise self.failureException(msg)