| 1 |
import contextlib |
| 2 |
import datetime |
| 3 |
import sys |
| 4 |
from typing import Any, Iterator |
| 5 |
|
| 6 |
import pytest |
| 7 |
from freezegun import freeze_time |
| 8 |
|
| 9 |
|
| 10 |
class ModuleWithError: |
| 11 |
""" |
| 12 |
A module that triggers an error on __dir__ access. |
| 13 |
|
| 14 |
This could happen with modules that overrides its __dir__ method and |
| 15 |
performing non standard operations. |
| 16 |
|
| 17 |
One such example is IPython which adds shim modules when certain packages |
| 18 |
are imported. (Eg. `import IPython.html`) This leads to errors upon |
| 19 |
activating freezegun if the modules being shimmed are not installed. |
| 20 |
|
| 21 |
See: https://github.com/ipython/ipython/blob/5.8.0/IPython/utils/shimmodule.py#L75 |
| 22 |
""" |
| 23 |
__name__ = 'module_with_error' |
| 24 |
__dict__ = {} |
| 25 |
|
| 26 |
def __init__(self, error_type: Any): |
| 27 |
self.error_triggered = False |
| 28 |
self.error_type = error_type |
| 29 |
|
| 30 |
def __dir__(self) -> Any: |
| 31 |
try: |
| 32 |
raise self.error_type() |
| 33 |
finally: |
| 34 |
self.error_triggered = True |
| 35 |
|
| 36 |
|
| 37 |
@contextlib.contextmanager |
| 38 |
def assert_module_with_raised_error(error_type: Any) -> Iterator[None]: |
| 39 |
"""Install a module into sys.modules that raises an error upon invoking |
| 40 |
__dir__.""" |
| 41 |
module = sys.modules['module_with_error'] = ModuleWithError(error_type) |
| 42 |
|
| 43 |
try: |
| 44 |
yield |
| 45 |
finally: |
| 46 |
del sys.modules['module_with_error'] |
| 47 |
|
| 48 |
assert module.error_triggered |
| 49 |
|
| 50 |
|
| 51 |
@pytest.mark.parametrize('error_type', [ImportError, TypeError]) |
| 52 |
def test_ignore_errors_in_start(error_type: Any) -> None: |
| 53 |
with assert_module_with_raised_error(error_type): |
| 54 |
freezer = freeze_time(datetime.datetime(2019, 1, 11, 9, 34)) |
| 55 |
|
| 56 |
try: |
| 57 |
freezer.start() |
| 58 |
finally: |
| 59 |
freezer.stop() |