| 1 |
"""Test the EventManager class.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from types import SimpleNamespace |
| 6 |
from typing import TYPE_CHECKING |
| 7 |
|
| 8 |
import pytest |
| 9 |
|
| 10 |
from sphinx.errors import ExtensionError |
| 11 |
from sphinx.events import EventManager |
| 12 |
|
| 13 |
if TYPE_CHECKING: |
| 14 |
from typing import NoReturn |
| 15 |
|
| 16 |
from sphinx.application import Sphinx |
| 17 |
|
| 18 |
|
| 19 |
def test_event_priority() -> None: |
| 20 |
result = [] |
| 21 |
app = SimpleNamespace(pdb=False) # pass a dummy object as an app |
| 22 |
events = EventManager(app) # type: ignore[arg-type] |
| 23 |
events.connect('builder-inited', lambda app: result.append(1), priority=500) |
| 24 |
events.connect('builder-inited', lambda app: result.append(2), priority=500) |
| 25 |
# earlier |
| 26 |
events.connect('builder-inited', lambda app: result.append(3), priority=200) |
| 27 |
# later |
| 28 |
events.connect('builder-inited', lambda app: result.append(4), priority=700) |
| 29 |
events.connect('builder-inited', lambda app: result.append(5), priority=500) |
| 30 |
|
| 31 |
events.emit('builder-inited') |
| 32 |
assert result == [3, 1, 2, 5, 4] |
| 33 |
|
| 34 |
|
| 35 |
def test_event_allowed_exceptions() -> None: |
| 36 |
def raise_error(app: Sphinx) -> NoReturn: |
| 37 |
raise RuntimeError |
| 38 |
|
| 39 |
app = SimpleNamespace(pdb=False) # pass a dummy object as an app |
| 40 |
events = EventManager(app) # type: ignore[arg-type] |
| 41 |
events.connect('builder-inited', raise_error, priority=500) |
| 42 |
|
| 43 |
# all errors are converted to ExtensionError |
| 44 |
with pytest.raises(ExtensionError): |
| 45 |
events.emit('builder-inited') |
| 46 |
|
| 47 |
# Allow RuntimeError (pass-through) |
| 48 |
with pytest.raises(RuntimeError): |
| 49 |
events.emit('builder-inited', allowed_exceptions=(RuntimeError,)) |
| 50 |
|
| 51 |
|
| 52 |
def test_event_pdb() -> None: |
| 53 |
def raise_error(app: Sphinx) -> NoReturn: |
| 54 |
raise RuntimeError |
| 55 |
|
| 56 |
app = SimpleNamespace(pdb=True) # pass a dummy object as an app |
| 57 |
events = EventManager(app) # type: ignore[arg-type] |
| 58 |
events.connect('builder-inited', raise_error, priority=500) |
| 59 |
|
| 60 |
# errors aren't converted |
| 61 |
with pytest.raises(RuntimeError): |
| 62 |
events.emit('builder-inited') |
| 63 |
|
| 64 |
# Allow RuntimeError (pass-through) |
| 65 |
with pytest.raises(RuntimeError): |
| 66 |
events.emit('builder-inited', allowed_exceptions=(RuntimeError,)) |