Testing¶
Testing a plugin¶
A plugin is an ordinary class. Test its hooks by calling them:
class Charts:
def render_block(self, block):
return "<figure/>" if block["type"] == "chart" else None
def test_renders_charts():
assert Charts().render_block({"type": "chart"}) == "<figure/>"
assert Charts().render_block({"type": "text"}) is None
To test it the way a host will use it, including its lifecycle, put it in a manager of its own, with discovery off:
from pluxeo import Plugin, PluginManager, PluginState
class Db(Plugin):
namespace = "acme.services"
name = "db"
def load(self):
conn = {"open": True}
yield conn
conn["open"] = False
def test_db_closes_on_unload():
pm = PluginManager("acme.services", discover=False)
pm.register(Db)
conn = pm.load("db")
pm.unload("db")
assert not conn["open"]
assert pm.state("db") is PluginState.DISCOVERED
Pass the host's hookspec as hookspec= to have Pluggy check that the plugin's hooks match it.
Testing a host with fake plugins¶
discover=False and register() give a test full control over which plugins a host sees. Register instances to give fake plugins constructor arguments:
from pluxeo import Plugin, PluginManager, hookimpl, hookspec
class Spec:
@hookspec
def greeting(self, name): ...
class Fake(Plugin):
namespace = "greeter.plugins"
name = "fake"
def __init__(self, answer):
self.answer = answer
@hookimpl
def greeting(self, name):
return self.answer
def test_host_prints_every_greeting():
pm = PluginManager("greeter.plugins", hookspec=Spec, discover=False)
pm.register(Fake("hello"))
pm.load_all()
assert pm.hook.greeting(name="x") == ["hello"]
If the host builds its manager in a function, have tests replace that function (with pytest's monkeypatch, for example) so the application under test uses the manager the test built.
Testing failure handling¶
A plugin that raises in load() is the simplest way to test what the host does with a broken plugin:
from pluxeo import Plugin, PluginManager
class Broken(Plugin):
namespace = "greeter.plugins"
name = "broken"
def load(self):
raise ImportError("no module named nothing")
def test_broken_plugin_is_contained():
pm = PluginManager("greeter.plugins", discover=False)
pm.register(Broken)
pm.load_all()
assert isinstance(pm.error("broken"), ImportError)