Skip to content

Commit

Permalink
feat: use plugins as context manager
Browse files Browse the repository at this point in the history
  • Loading branch information
klen committed May 28, 2024
1 parent 6d5aab7 commit 948bb32
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
8 changes: 8 additions & 0 deletions muffin/plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,14 @@ def __repr__(self) -> str:
"""Human readable representation."""
return f"<muffin.Plugin: { self.name }>"

async def __aenter__(self):
if self.startup is not None:
await self.startup()

async def __aexit__(self, exc_type, exc, tb):
if self.shutdown is not None:
await self.shutdown()

@property
def app(self) -> Application:
"""Get the application."""
Expand Down
22 changes: 22 additions & 0 deletions tests/common/test_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,25 @@ class Plugin(BasePlugin):
"plugin1": p1,
"plugin2": p2,
}


async def test_plugin_as_context_manager():
from muffin.plugins import BasePlugin

events = []

class Plugin(BasePlugin):
name = "plugin"

async def startup(self):
events.append("start")

async def shutdown(self):
events.append("end")

plug = Plugin()
async with plug:
pass

assert "start" in events
assert "end" in events

0 comments on commit 948bb32

Please sign in to comment.