From 95b9f1b73487e5351b50e9d164c3ac5d215c5f2b Mon Sep 17 00:00:00 2001 From: Garulf <535299+Garulf@users.noreply.github.com> Date: Thu, 25 Jan 2024 12:41:10 -0500 Subject: [PATCH] Add method for registering a method and returning a JSONRPCAction --- pyflowlauncher/event.py | 6 ++++-- pyflowlauncher/plugin.py | 11 ++++++++--- tests/test_plugin.py | 6 ++++++ 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/pyflowlauncher/event.py b/pyflowlauncher/event.py index 444a3a1..bd4879a 100644 --- a/pyflowlauncher/event.py +++ b/pyflowlauncher/event.py @@ -12,8 +12,10 @@ def __init__(self): def _get_callable_name(self, method: Callable[..., Any]): return getattr(method, '__name__', method.__class__.__name__).lower() - def add_method(self, method: Callable[..., Any], *, name=None): - self._methods[name or self._get_callable_name(method)] = method + def add_method(self, method: Callable[..., Any], *, name=None) -> str: + key = name or self._get_callable_name(method) + self._methods[key] = method + return key def add_methods(self, methods: Iterable[Callable[..., Any]]): for method in methods: diff --git a/pyflowlauncher/plugin.py b/pyflowlauncher/plugin.py index 3f4859b..ba488d5 100644 --- a/pyflowlauncher/plugin.py +++ b/pyflowlauncher/plugin.py @@ -2,7 +2,7 @@ import sys from functools import wraps -from typing import Any, Callable, Iterable, Union +from typing import Any, Callable, Iterable, Optional, Union from pathlib import Path import json @@ -26,9 +26,9 @@ def __init__(self, methods: list[Method] | None = None) -> None: if methods: self.add_methods(methods) - def add_method(self, method: Method) -> None: + def add_method(self, method: Method) -> str: """Add a method to the event handler.""" - self._event_handler.add_method(method) + return self._event_handler.add_method(method) def add_methods(self, methods: Iterable[Method]) -> None: self._event_handler.add_methods(methods) @@ -48,6 +48,11 @@ def add_exception_handler(self, exception: Exception, handler: Callable[..., Any """Add exception handler to be called when an exception is raised in a method.""" self._event_handler.add_exception_handler(exception, handler) + def action(self, method: Method, parameters: Optional[Iterable] = None) -> JsonRPCAction: + """Register a method and return a JsonRPCAction that calls it.""" + method_name = self.add_method(method) + return {"method": method_name, "parameters": parameters or []} + @property def settings(self) -> dict: if self._settings is None: diff --git a/tests/test_plugin.py b/tests/test_plugin.py index fca7cde..853ca47 100644 --- a/tests/test_plugin.py +++ b/tests/test_plugin.py @@ -51,3 +51,9 @@ def test_root_dir_not_found(tmp_path, monkeypatch): plugin = Plugin() with pytest.raises(FileNotFoundError): assert plugin.root_dir() == tmp_path + + +def test_action(): + plugin = Plugin() + action = plugin.action(query) + assert action == {'method': 'query', 'parameters': []} \ No newline at end of file