Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add signal reservations #2060

Merged
merged 5 commits into from
Mar 14, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 23 additions & 10 deletions sanic/signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import asyncio

from inspect import isawaitable
from typing import Any, Dict, List, Optional, Union
from typing import Any, Dict, List, Optional, Tuple, Union

from sanic_routing import BaseRouter, Route # type: ignore
from sanic_routing.exceptions import NotFound # type: ignore
Expand All @@ -13,6 +13,12 @@
from sanic.models.handler_types import SignalHandler


RESERVED_NAMESPACES = (
"server",
"http",
)


class Signal(Route):
def get_handler(self, raw_path, method, _):
method = method or self.router.DEFAULT_METHOD
Expand Down Expand Up @@ -97,15 +103,7 @@ def add( # type: ignore
event: str,
condition: Optional[Dict[str, Any]] = None,
) -> Signal:
parts = path_to_parts(event, self.delimiter)

if (
len(parts) != 3
or parts[0].startswith("<")
or parts[1].startswith("<")
):
raise InvalidSignal(f"Invalid signal event: {event}")

parts = self._build_event_parts(event)
if parts[2].startswith("<"):
name = ".".join([*parts[:-1], "*"])
else:
Expand All @@ -131,3 +129,18 @@ def finalize(self, do_compile: bool = True):
signal.ctx.event = asyncio.Event()

return super().finalize(do_compile=do_compile)

def _build_event_parts(self, event: str) -> Tuple[str, str, str]:
parts = path_to_parts(event, self.delimiter)
if (
len(parts) != 3
or parts[0].startswith("<")
or parts[1].startswith("<")
):
raise InvalidSignal("Invalid signal event: %s" % event)

if parts[0] in RESERVED_NAMESPACES:
raise InvalidSignal(
"Cannot declare reserved signal event: %s" % event
)
return parts
20 changes: 20 additions & 0 deletions tests/test_signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,3 +280,23 @@ def bp_signal():
match="<Blueprint bp> has not yet been registered to an app",
):
bp.event("foo.bar.baz")


@pytest.mark.parametrize(
"event,expected",
(
("foo.bar.baz", True),
("server.init.before", False),
("http.request.start", False),
("sanic.notice.anything", True),
),
)
def test_signal_reservation(app, event, expected):
if not expected:
with pytest.raises(
InvalidSignal,
match=f"Cannot declare reserved signal event: {event}",
):
app.signal(event)(lambda: ...)
else:
app.signal(event)(lambda: ...)