amqtt/tests/plugins/test_plugins.py

62 wiersze
1.6 KiB
Python
Czysty Zwykły widok Historia

from glob import glob
2022-02-05 19:44:30 +00:00
import inspect
from logging import getLogger
from os.path import dirname, isfile, join
2022-02-05 19:44:30 +00:00
import pytest
import amqtt.plugins
from amqtt.plugins.manager import BaseContext
_INVALID_METHOD = "invalid_foo"
_PLUGIN = "Plugin"
class _TestContext(BaseContext):
def __init__(self) -> None:
2022-02-05 19:44:30 +00:00
super().__init__()
self.config = {"auth": {}}
self.logger = getLogger(__name__)
2022-02-05 19:44:30 +00:00
def _verify_module(module, plugin_module_name) -> None:
2022-02-05 19:44:30 +00:00
if not module.__name__.startswith(plugin_module_name):
return
for name, clazz in inspect.getmembers(module, inspect.isclass):
if not name.endswith(_PLUGIN) or name == _PLUGIN:
continue
obj = clazz(_TestContext())
2022-02-05 20:08:17 +00:00
with pytest.raises(
AttributeError,
match=f"'{name}' object has no attribute '{_INVALID_METHOD}'",
):
2022-02-05 19:44:30 +00:00
getattr(obj, _INVALID_METHOD)
assert hasattr(obj, _INVALID_METHOD) is False
for name, obj in inspect.getmembers(module, inspect.ismodule):
_verify_module(obj, plugin_module_name)
2022-02-06 13:39:05 +00:00
def removesuffix(self: str, suffix: str) -> str:
# compatibility for pre 3.9
if suffix and self.endswith(suffix):
return self[: -len(suffix)]
return self[:]
2022-02-06 13:39:05 +00:00
2022-02-05 19:44:30 +00:00
def test_plugins_correct_has_attr():
module = amqtt.plugins
for file in glob(join(dirname(module.__file__), "**/*.py"), recursive=True):
if not isfile(file):
continue
name = file.replace("/", ".")
2022-02-06 13:39:05 +00:00
name = name[name.find(module.__name__) : -3]
name = removesuffix(name, ".__init__")
2022-02-05 19:44:30 +00:00
__import__(name)
_verify_module(module, module.__name__)