| 1 |
#!/usr/bin/env python |
| 2 |
from __future__ import annotations |
| 3 |
|
| 4 |
import os |
| 5 |
import unittest |
| 6 |
from typing import TYPE_CHECKING, Optional |
| 7 |
|
| 8 |
if TYPE_CHECKING: |
| 9 |
from typing_extensions import assert_type |
| 10 |
|
| 11 |
from mkdocs.structure.nav import Navigation |
| 12 |
else: |
| 13 |
|
| 14 |
def assert_type(val, typ): |
| 15 |
return None |
| 16 |
|
| 17 |
|
| 18 |
from mkdocs import plugins |
| 19 |
from mkdocs.commands import build |
| 20 |
from mkdocs.config import base |
| 21 |
from mkdocs.config import config_options as c |
| 22 |
from mkdocs.config.base import ValidationError |
| 23 |
from mkdocs.exceptions import Abort, BuildError, PluginError |
| 24 |
from mkdocs.tests.base import load_config, tempdir |
| 25 |
|
| 26 |
|
| 27 |
class _DummyPluginConfig(base.Config): |
| 28 |
foo = c.Type(str, default='default foo') |
| 29 |
bar = c.Type(int, default=0) |
| 30 |
dir = c.Optional(c.Dir(exists=False)) |
| 31 |
|
| 32 |
|
| 33 |
class DummyPlugin(plugins.BasePlugin[_DummyPluginConfig]): |
| 34 |
def on_page_content(self, html, **kwargs) -> str: |
| 35 |
"""Modify page content by prepending `foo` config value.""" |
| 36 |
return f'{self.config.foo} {html}' |
| 37 |
|
| 38 |
def on_nav(self, nav, **kwargs) -> None: |
| 39 |
"""Do nothing (return None) to not modify item.""" |
| 40 |
return None |
| 41 |
|
| 42 |
def on_page_read_source(self, **kwargs) -> str: |
| 43 |
"""Create new source by prepending `foo` config value to 'source'.""" |
| 44 |
return f'{self.config.foo} source' |
| 45 |
|
| 46 |
def on_pre_build(self, **kwargs) -> None: |
| 47 |
"""Do nothing (return None).""" |
| 48 |
return None |
| 49 |
|
| 50 |
|
| 51 |
class TestPluginClass(unittest.TestCase): |
| 52 |
def test_valid_plugin_options(self) -> None: |
| 53 |
test_dir = 'test' |
| 54 |
|
| 55 |
options = { |
| 56 |
'foo': 'some value', |
| 57 |
'dir': test_dir, |
| 58 |
} |
| 59 |
|
| 60 |
cfg_fname = os.path.join('tmp', 'test', 'fname.yml') |
| 61 |
cfg_fname = os.path.abspath(cfg_fname) |
| 62 |
|
| 63 |
cfg_dirname = os.path.dirname(cfg_fname) |
| 64 |
expected = { |
| 65 |
'foo': 'some value', |
| 66 |
'bar': 0, |
| 67 |
'dir': os.path.join(cfg_dirname, test_dir), |
| 68 |
} |
| 69 |
|
| 70 |
plugin = DummyPlugin() |
| 71 |
errors, warnings = plugin.load_config(options, config_file_path=cfg_fname) |
| 72 |
self.assertEqual(errors, []) |
| 73 |
self.assertEqual(warnings, []) |
| 74 |
|
| 75 |
assert_type(plugin.config, _DummyPluginConfig) |
| 76 |
self.assertEqual(plugin.config, expected) |
| 77 |
|
| 78 |
assert_type(plugin.config.bar, int) |
| 79 |
self.assertEqual(plugin.config.bar, 0) |
| 80 |
assert_type(plugin.config.dir, Optional[str]) |
| 81 |
|
| 82 |
def test_invalid_plugin_options(self): |
| 83 |
plugin = DummyPlugin() |
| 84 |
errors, warnings = plugin.load_config({'foo': 42}) |
| 85 |
self.assertEqual( |
| 86 |
errors, |
| 87 |
[('foo', ValidationError("Expected type: <class 'str'> but received: <class 'int'>"))], |
| 88 |
) |
| 89 |
self.assertEqual(warnings, []) |
| 90 |
|
| 91 |
errors, warnings = plugin.load_config({'bar': 'a string'}) |
| 92 |
self.assertEqual( |
| 93 |
errors, |
| 94 |
[('bar', ValidationError("Expected type: <class 'int'> but received: <class 'str'>"))], |
| 95 |
) |
| 96 |
self.assertEqual(warnings, []) |
| 97 |
|
| 98 |
errors, warnings = plugin.load_config({'invalid_key': 'value'}) |
| 99 |
self.assertEqual(errors, []) |
| 100 |
self.assertEqual( |
| 101 |
warnings, [('invalid_key', "Unrecognised configuration name: invalid_key")] |
| 102 |
) |
| 103 |
|
| 104 |
|
| 105 |
class TestPluginCollection(unittest.TestCase): |
| 106 |
def test_correct_events_registered(self): |
| 107 |
collection = plugins.PluginCollection() |
| 108 |
plugin = DummyPlugin() |
| 109 |
collection['foo'] = plugin |
| 110 |
self.assertEqual( |
| 111 |
collection.events, |
| 112 |
{ |
| 113 |
'startup': [], |
| 114 |
'shutdown': [], |
| 115 |
'serve': [], |
| 116 |
'config': [], |
| 117 |
'pre_build': [plugin.on_pre_build], |
| 118 |
'files': [], |
| 119 |
'nav': [plugin.on_nav], |
| 120 |
'env': [], |
| 121 |
'post_build': [], |
| 122 |
'build_error': [], |
| 123 |
'pre_template': [], |
| 124 |
'template_context': [], |
| 125 |
'post_template': [], |
| 126 |
'pre_page': [], |
| 127 |
'page_read_source': [plugin.on_page_read_source], |
| 128 |
'page_markdown': [], |
| 129 |
'page_content': [plugin.on_page_content], |
| 130 |
'page_context': [], |
| 131 |
'post_page': [], |
| 132 |
}, |
| 133 |
) |
| 134 |
|
| 135 |
def test_event_priorities(self) -> None: |
| 136 |
class PrioPlugin(plugins.BasePlugin): |
| 137 |
config_scheme = base.get_schema(_DummyPluginConfig) |
| 138 |
|
| 139 |
@plugins.event_priority(100) |
| 140 |
def on_page_content(self, html, **kwargs) -> None: |
| 141 |
pass |
| 142 |
|
| 143 |
@plugins.event_priority(50) |
| 144 |
def _on_nav_1(self, nav: Navigation, **kwargs) -> None: |
| 145 |
pass |
| 146 |
|
| 147 |
@plugins.event_priority(-100) |
| 148 |
def _on_nav_2(self, nav, **kwargs) -> None: |
| 149 |
pass |
| 150 |
|
| 151 |
on_nav = plugins.CombinedEvent(_on_nav_1, _on_nav_2) |
| 152 |
|
| 153 |
def on_page_read_source(self, **kwargs) -> None: |
| 154 |
pass |
| 155 |
|
| 156 |
@plugins.event_priority(-50) |
| 157 |
def on_post_build(self, **kwargs) -> None: |
| 158 |
pass |
| 159 |
|
| 160 |
collection = plugins.PluginCollection() |
| 161 |
collection['dummy'] = dummy = DummyPlugin() |
| 162 |
with self.assertLogs('mkdocs', level='WARNING') as cm: |
| 163 |
collection['prio'] = prio = PrioPlugin() |
| 164 |
self.assertEqual( |
| 165 |
'\n'.join(cm.output), |
| 166 |
"WARNING:mkdocs.plugins:Multiple 'on_page_read_source' handlers can't work (both plugins 'dummy' and 'prio' registered one).", |
| 167 |
) |
| 168 |
|
| 169 |
self.assertEqual( |
| 170 |
collection.events['page_content'], |
| 171 |
[prio.on_page_content, dummy.on_page_content], |
| 172 |
) |
| 173 |
self.assertEqual( |
| 174 |
collection.events['nav'], |
| 175 |
[prio._on_nav_1, dummy.on_nav, prio._on_nav_2], |
| 176 |
) |
| 177 |
self.assertEqual( |
| 178 |
collection.events['page_read_source'], |
| 179 |
[dummy.on_page_read_source, prio.on_page_read_source], |
| 180 |
) |
| 181 |
self.assertEqual( |
| 182 |
collection.events['post_build'], |
| 183 |
[prio.on_post_build], |
| 184 |
) |
| 185 |
|
| 186 |
def test_set_plugin_on_collection(self): |
| 187 |
collection = plugins.PluginCollection() |
| 188 |
plugin = DummyPlugin() |
| 189 |
collection['foo'] = plugin |
| 190 |
self.assertEqual(list(collection.items()), [('foo', plugin)]) |
| 191 |
|
| 192 |
def test_set_multiple_plugins_on_collection(self): |
| 193 |
collection = plugins.PluginCollection() |
| 194 |
plugin1 = DummyPlugin() |
| 195 |
collection['foo'] = plugin1 |
| 196 |
plugin2 = DummyPlugin() |
| 197 |
with self.assertLogs('mkdocs', level='WARNING') as cm: |
| 198 |
collection['bar'] = plugin2 |
| 199 |
self.assertEqual( |
| 200 |
'\n'.join(cm.output), |
| 201 |
"WARNING:mkdocs.plugins:Multiple 'on_page_read_source' handlers can't work (both plugins 'foo' and 'bar' registered one).", |
| 202 |
) |
| 203 |
self.assertEqual(list(collection.items()), [('foo', plugin1), ('bar', plugin2)]) |
| 204 |
|
| 205 |
def test_run_event_on_collection(self): |
| 206 |
collection = plugins.PluginCollection() |
| 207 |
plugin = DummyPlugin() |
| 208 |
plugin.load_config({'foo': 'new'}) |
| 209 |
collection['foo'] = plugin |
| 210 |
self.assertEqual( |
| 211 |
collection.on_page_content('page content', page=None, config={}, files=[]), |
| 212 |
'new page content', |
| 213 |
) |
| 214 |
|
| 215 |
def test_run_event_twice_on_collection(self): |
| 216 |
collection = plugins.PluginCollection() |
| 217 |
plugin1 = DummyPlugin() |
| 218 |
plugin1.load_config({'foo': 'new'}) |
| 219 |
collection['foo'] = plugin1 |
| 220 |
plugin2 = DummyPlugin() |
| 221 |
plugin2.load_config({'foo': 'second'}) |
| 222 |
with self.assertLogs('mkdocs', level='WARNING') as cm: |
| 223 |
collection['bar'] = plugin2 |
| 224 |
self.assertEqual( |
| 225 |
'\n'.join(cm.output), |
| 226 |
"WARNING:mkdocs.plugins:Multiple 'on_page_read_source' handlers can't work (both plugins 'foo' and 'bar' registered one).", |
| 227 |
) |
| 228 |
self.assertEqual( |
| 229 |
collection.on_page_content('page content', page=None, config={}, files=[]), |
| 230 |
'second new page content', |
| 231 |
) |
| 232 |
|
| 233 |
def test_event_returns_None(self): |
| 234 |
collection = plugins.PluginCollection() |
| 235 |
plugin = DummyPlugin() |
| 236 |
plugin.load_config({'foo': 'new'}) |
| 237 |
collection['foo'] = plugin |
| 238 |
self.assertEqual(collection.on_nav(['nav item'], config={}, files=[]), ['nav item']) |
| 239 |
|
| 240 |
def test_event_empty_item(self): |
| 241 |
collection = plugins.PluginCollection() |
| 242 |
plugin = DummyPlugin() |
| 243 |
plugin.load_config({'foo': 'new'}) |
| 244 |
collection['foo'] = plugin |
| 245 |
self.assertEqual(collection.on_page_read_source(page=None, config={}), 'new source') |
| 246 |
|
| 247 |
def test_event_empty_item_returns_None(self): |
| 248 |
collection = plugins.PluginCollection() |
| 249 |
plugin = DummyPlugin() |
| 250 |
plugin.load_config({'foo': 'new'}) |
| 251 |
collection['foo'] = plugin |
| 252 |
self.assertEqual(collection.on_pre_build(config={}), None) |
| 253 |
|
| 254 |
def test_run_undefined_event_on_collection(self): |
| 255 |
collection = plugins.PluginCollection() |
| 256 |
self.assertEqual( |
| 257 |
collection.on_page_markdown('page markdown', page=None, config={}, files=[]), |
| 258 |
'page markdown', |
| 259 |
) |
| 260 |
|
| 261 |
def test_run_unknown_event_on_collection(self): |
| 262 |
collection = plugins.PluginCollection() |
| 263 |
with self.assertRaises(KeyError): |
| 264 |
collection.run_event('unknown', 'page content') |
| 265 |
|
| 266 |
@tempdir() |
| 267 |
def test_run_build_error_event(self, site_dir): |
| 268 |
build_errors = [] |
| 269 |
|
| 270 |
class PluginRaisingError(plugins.BasePlugin): |
| 271 |
def __init__(self, error_on): |
| 272 |
self.error_on = error_on |
| 273 |
|
| 274 |
def on_pre_page(self, page, **kwargs): |
| 275 |
if self.error_on == 'pre_page': |
| 276 |
raise BuildError('pre page error') |
| 277 |
return page |
| 278 |
|
| 279 |
def on_page_markdown(self, markdown, **kwargs): |
| 280 |
if self.error_on == 'page_markdown': |
| 281 |
raise BuildError('page markdown error') |
| 282 |
return markdown |
| 283 |
|
| 284 |
def on_page_content(self, html, **kwargs): |
| 285 |
if self.error_on == 'page_content': |
| 286 |
raise PluginError('page content error') |
| 287 |
return html |
| 288 |
|
| 289 |
def on_post_page(self, html, **kwargs): |
| 290 |
if self.error_on == 'post_page': |
| 291 |
raise ValueError('post page error') |
| 292 |
|
| 293 |
def on_build_error(self, error, **kwargs): |
| 294 |
build_errors.append(error) |
| 295 |
|
| 296 |
cfg = load_config(site_dir=site_dir) |
| 297 |
cfg.plugins['errorplugin'] = PluginRaisingError(error_on='pre_page') |
| 298 |
with self.assertLogs('mkdocs', level='ERROR'): |
| 299 |
self.assertRaises(Abort, build.build, cfg) |
| 300 |
|
| 301 |
cfg = load_config(site_dir=site_dir) |
| 302 |
cfg.plugins['errorplugin'] = PluginRaisingError(error_on='page_markdown') |
| 303 |
with self.assertLogs('mkdocs', level='ERROR'): |
| 304 |
self.assertRaises(Abort, build.build, cfg) |
| 305 |
|
| 306 |
cfg = load_config(site_dir=site_dir) |
| 307 |
cfg.plugins['errorplugin'] = PluginRaisingError(error_on='page_content') |
| 308 |
with self.assertLogs('mkdocs', level='ERROR'): |
| 309 |
self.assertRaises(Abort, build.build, cfg) |
| 310 |
|
| 311 |
cfg = load_config(site_dir=site_dir) |
| 312 |
cfg.plugins['errorplugin'] = PluginRaisingError(error_on='post_page') |
| 313 |
with self.assertLogs('mkdocs', level='ERROR'): |
| 314 |
self.assertRaises(ValueError, build.build, cfg) |
| 315 |
|
| 316 |
cfg = load_config(site_dir=site_dir) |
| 317 |
cfg.plugins['errorplugin'] = PluginRaisingError(error_on='') |
| 318 |
build.build(cfg) |
| 319 |
|
| 320 |
self.assertEqual(len(build_errors), 4) |
| 321 |
self.assertIs(build_errors[0].__class__, BuildError) |
| 322 |
self.assertEqual(str(build_errors[0]), 'pre page error') |
| 323 |
self.assertIs(build_errors[1].__class__, BuildError) |
| 324 |
self.assertEqual(str(build_errors[1]), 'page markdown error') |
| 325 |
self.assertIs(build_errors[2].__class__, PluginError) |
| 326 |
self.assertEqual(str(build_errors[2]), 'page content error') |
| 327 |
self.assertIs(build_errors[3].__class__, ValueError) |
| 328 |
self.assertEqual(str(build_errors[3]), 'post page error') |