diff --git a/phx_events/__init__.py b/phx_events/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..17c0d8a560cbaafbbe51be8c096b052e61e0735e --- /dev/null +++ b/phx_events/__init__.py @@ -0,0 +1,3 @@ +"""AsyncIO Phoenix Channels client for fast asynchronous message handling""" + +__version__ = '0.4.1' diff --git a/phx_events/async_logger.py b/phx_events/async_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..485dcac3b624732331ad82ad89a17ef5ac0b7590 --- /dev/null +++ b/phx_events/async_logger.py @@ -0,0 +1,46 @@ +import asyncio +import logging +from logging.handlers import QueueHandler, QueueListener +from queue import SimpleQueue + + +class LocalQueueHandler(QueueHandler): + def emit(self, record: logging.LogRecord) -> None: + try: + self.enqueue(record) + except asyncio.CancelledError: + raise + except Exception: + self.handleError(record) + + +def setup_queue_logging() -> tuple[logging.Logger, QueueListener]: + """Move log handlers to a separate thread. + + Replace handlers on the root logger with a LocalQueueHandler, + and start a logging.QueueListener holding the original + handlers. + """ + queue: SimpleQueue = SimpleQueue() + queue_logger = logging.getLogger(__name__) + + handlers: list[logging.Handler] = [] + # Last resort handler if no logging is configured + if logging.lastResort is not None: + handlers.append(logging.lastResort) + + local_queue_handler = LocalQueueHandler(queue) + queue_logger.addHandler(local_queue_handler) + + for handler in queue_logger.handlers: + if handler is not local_queue_handler: + queue_logger.removeHandler(handler) + handlers.append(handler) + + listener = QueueListener(queue, *handlers, respect_handler_level=True) + listener.start() + + return queue_logger, listener + + +async_logger, queue_listener = setup_queue_logging() diff --git a/phx_events/client.py b/phx_events/client.py new file mode 100644 index 0000000000000000000000000000000000000000..fe63afde37beb46d583aa4e4a2e3350528482550 --- /dev/null +++ b/phx_events/client.py @@ -0,0 +1,304 @@ +import asyncio +from asyncio import AbstractEventLoop, Event, Queue, Task +from concurrent.futures import Executor, ThreadPoolExecutor +from functools import partial +import inspect +from logging import Logger +import signal +from types import TracebackType +from typing import Awaitable, cast, Optional, Type, Union +from urllib.parse import urlencode + +from websockets import client + +from phx_events import json_handler +from phx_events.async_logger import async_logger +from phx_events.exceptions import PHXTopicTooManyRegistrationsError, TopicClosedError +from phx_events.phx_messages import ( + ChannelEvent, + ChannelHandlerFunction, + ChannelMessage, + CoroutineHandler, + EventHandlerConfig, + ExecutorHandler, + PHXEvent, + Topic, +) +from phx_events.topic_subscription import SubscriptionStatus, TopicRegistration, TopicSubscribeResult +from phx_events.utils import make_message + + +class PHXChannelsClient: + """Provides the main functionality for running a client with asynchronous handlers + + This class should generally be initialised and used as an asynchronous context manager. + + Inside the `async with` block you should register for topics using `PHXChannelsClient.register_topic_subscription` + and register event handlers using `PHXChannelsClient.register_event_handler`. + + Event handler functions can be `async` or normal functions. + * Async functions are run in the event loop `PHXChannelsClient._loop` + * Normal functions are run using the provided executor pool (`ThreadPoolExecutor` by default) + + """ + channel_socket_url: str + logger: Logger + + _client_start_event: Event + _event_handler_config: dict[ChannelEvent, EventHandlerConfig] + _topic_registration_status: dict[Topic, TopicRegistration] + _loop: AbstractEventLoop + _executor_pool: Optional[Executor] + _registration_queue: Queue + _topic_registration_task: Optional[Task] + + def __init__( + self, + channel_socket_url: str, + channel_auth_token: Optional[str] = None, + event_loop: Optional[AbstractEventLoop] = None, + ): + self.logger = async_logger.getChild(__name__) + self.channel_socket_url = channel_socket_url + # Set up auth if it's required + if channel_auth_token is not None: + self.channel_socket_url += f'?{urlencode({"token": channel_auth_token})}' + + self._event_handler_config = {} + self._topic_registration_status = {} + # Create the Event that will prevent handlers from being run before the client is started + self._client_start_event = Event() + self._registration_queue = Queue() + self._topic_registration_task = None + + self._executor_pool = None + # Get the default event loop or use the user-provided one if it exists + self._loop = event_loop or asyncio.get_event_loop() + + async def __aenter__(self) -> 'PHXChannelsClient': + self.logger.debug('Entering PHXChannelsClient context') + return self + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]] = None, + exc_value: Optional[BaseException] = None, + traceback: Optional[TracebackType] = None, + ) -> None: + self.logger.debug('Leaving PHXChannelsClient context') + self.shutdown('Leaving PHXChannelsClient context') + + async def _send_message(self, websocket: client.WebSocketClientProtocol, message: ChannelMessage) -> None: + self.logger.debug(f'Serialising {message=} to JSON') + json_message = json_handler.dumps(message) + + self.logger.debug(f'Sending {json_message=}') + await websocket.send(json_message) + + def _parse_message(self, socket_message: Union[str, bytes]) -> ChannelMessage: + self.logger.debug(f'Got message - {socket_message=}') + message_dict = json_handler.loads(socket_message) + + self.logger.debug(f'Decoding message dict - {message_dict=}') + return make_message(**message_dict) + + async def _event_processor(self, event: ChannelEvent) -> None: + """Coroutine used to create tasks that process the given event + + Runs all the handlers in the thread_pool and logs any exceptions. + """ + # Make all tasks wait until the _client_start_event is set + # This prevents trying to do any processing until we want the "workers" to start + self.logger.debug(f'{event} Worker - Waiting for client start!') + await self._client_start_event.wait() + + self.logger.debug(f'{event} Worker - Started!') + event_handler_config = self._event_handler_config[event] + + # Keep running until we ask all the tasks to stop + while True: + # wait until there's a message on the queue to process + message = await event_handler_config.queue.get() + self.logger.debug(f'{event} Worker - Got {message=}') + + # We run all the default handlers as well as the specific topic handlers + event_handlers: list[ChannelHandlerFunction] = event_handler_config.default_handlers.copy() + if topic_handlers := event_handler_config.topic_handlers.get(message.topic): + event_handlers.extend(topic_handlers) + + event_tasks = [] + task: Union[Task[None], Awaitable[None]] + # Run all the event handlers in self.thread_pool managed by AsyncIO or as tasks + for event_handler in event_handlers: + if inspect.iscoroutinefunction(event_handler): + event_handler = cast(CoroutineHandler, event_handler) + task = self._loop.create_task(event_handler(message, self)) + else: + event_handler = cast(ExecutorHandler, event_handler) + handler_task = partial(event_handler, message, self) + task = self._loop.run_in_executor(self._executor_pool, handler_task) + + event_tasks.append(task) + + # Wait until the handlers finish running & await the results to handle errors + for handler_future in asyncio.as_completed(event_tasks): + try: + await handler_future + except Exception as exception: + self.logger.exception(f'Error executing handler - {exception=}') + + # Let the queue know the task is done being processed + event_handler_config.queue.task_done() + + def shutdown( + self, + reason: str, + websocket: Optional[client.WebSocketClientProtocol] = None, + executor_pool: Optional[Executor] = None, + wait_for_completion: bool = True, + ) -> None: + self.logger.info(f'Event loop shutting down! {reason=}') + + if websocket is not None: + self._loop.create_task(websocket.close()) + + if self._topic_registration_task is not None: + self._topic_registration_task.cancel() + + for handler_config in self._event_handler_config.values(): + handler_config.task.cancel() + + if executor_pool is not None: + executor_pool.shutdown(wait=wait_for_completion, cancel_futures=not wait_for_completion) + + def register_event_handler( + self, + event: ChannelEvent, + handlers: list[ChannelHandlerFunction], + topic: Optional[Topic] = None, + ) -> None: + if event not in self._event_handler_config: + # Create the coroutine that will become a task + event_coroutine = self._event_processor(event) + + # Create the default EventHandlerConfig + self._event_handler_config[event] = EventHandlerConfig( + queue=Queue(), + default_handlers=[], + topic_handlers={}, + task=self._loop.create_task(event_coroutine), + ) + + handler_config = self._event_handler_config[event] + # If there is a topic to be registered for - add the handlers to the topic handler + if topic is not None: + handler_config.topic_handlers.setdefault(topic, []).extend(handlers) + else: + # otherwise, add them to the default handlers + handler_config.default_handlers.extend(handlers) + + async def process_topic_registration_responses(self) -> None: + while True: + phx_message = await self._registration_queue.get() + + topic = phx_message.topic + self.logger.info(f'Got topic {topic} join reply {phx_message=}') + + status = SubscriptionStatus.SUCCESS if phx_message.payload['status'] == 'ok' else SubscriptionStatus.FAILED + status_message = 'SUCCEEDED' if status == SubscriptionStatus.SUCCESS else 'FAILED' + self.logger.info(f'Topic registration {status_message} - {phx_message=}') + + # Set the topic status map + topic_registration = self._topic_registration_status[topic] + # Set topic status with the message + topic_registration.result = TopicSubscribeResult(status, phx_message) + # Notify any waiting tasks that the registration has been finalised and the status can be checked + topic_registration.status_updated_event.set() + # Tell the queue we've finished processing the current task + self._registration_queue.task_done() + + def register_topic_subscription(self, topic: Topic) -> Event: + if topic_status := self._topic_registration_status.get(topic): + topic_ref = topic_status.connection_ref + raise PHXTopicTooManyRegistrationsError(f'Topic {topic} already registered with {topic_ref=}') + + # Create an event to indicate when the reply has been processed + status_updated_event = Event() + + self._topic_registration_status[topic] = TopicRegistration(status_updated_event=status_updated_event) + + return status_updated_event + + async def process_websocket_messages(self, websocket: client.WebSocketClientProtocol) -> None: + self.logger.debug('Starting websocket message loop') + + async for socket_message in websocket: + phx_message = self._parse_message(socket_message) + self.logger.debug(f'Processing message - {phx_message=}') + event = phx_message.event + + if event == PHXEvent.close: + self.logger.info(f'Got Phoenix event {event} shutting down - {phx_message=}') + raise TopicClosedError(topic=phx_message.topic, reason='Upstream closed') + + if event == PHXEvent.error: + # Error happened in Elixir + self.logger.error(f'Got Phoenix event {event} shutting down - {phx_message=}') + # Hard exit if the server closes or errors + raise TopicClosedError(topic=phx_message.topic, reason='Upstream error') + + # Push message into registration queue if appropriate + if topic_registration_config := self._topic_registration_status.get(phx_message.topic): # noqa: SIM102 + if event == PHXEvent.reply and not topic_registration_config.status_updated_event.is_set(): + await self._registration_queue.put(phx_message) + + event_handler_config = self._event_handler_config.get(event) + if event_handler_config is None: + self.logger.debug(f'Ignoring {phx_message=} - no event handlers registered') + continue + + self.logger.debug(f'Submitting message to {event=} queue - {phx_message=}') + await event_handler_config.queue.put(phx_message) + + async def _subscribe_to_registered_topics(self, websocket: client.WebSocketClientProtocol) -> None: + self._topic_registration_task = self._loop.create_task(self.process_topic_registration_responses()) + + registration_messages = [] + for topic, topic_registration_config in self._topic_registration_status.items(): + self.logger.info(f'Creating subscribe message for {topic=}') + topic_join_message = make_message(event=PHXEvent.join, topic=topic) + + topic_registration_config.connection_ref = topic_join_message.ref + registration_messages.append(topic_join_message) + + # Send the topic join message + send_websocket_message = partial(self._send_message, websocket) + self.logger.info('Sending all topic subscribe messages!') + await asyncio.gather(*map(send_websocket_message, registration_messages)) + + async def start_processing(self, executor_pool: Optional[Executor] = None) -> None: + if not self._topic_registration_status: + self.logger.error('No subscribed topics nothing to do here - ending processing!') + return + + self.logger.debug('Creating the executor pool to use for processing registered handlers') + self._executor_pool = executor_pool or ThreadPoolExecutor() + + with self._executor_pool as pool: + self.logger.debug('Connecting to websocket') + + async with client.connect(self.channel_socket_url) as websocket: + # Close the connection when receiving SIGTERM + shutdown_handler = partial( + self.shutdown, + websocket=websocket, + executor_pool=pool, + wait_for_completion=False, + ) + self._loop.add_signal_handler(signal.SIGTERM, partial(shutdown_handler, reason='SIGTERM')) + self._loop.add_signal_handler(signal.SIGINT, partial(shutdown_handler, reason='Keyboard Interrupt')) + + await self._subscribe_to_registered_topics(websocket) + + self._client_start_event.set() + await self.process_websocket_messages(websocket) diff --git a/phx_events/exceptions.py b/phx_events/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..f505f163e487e72d1c72188feee88c4346a717f2 --- /dev/null +++ b/phx_events/exceptions.py @@ -0,0 +1,16 @@ +from phx_events.phx_messages import Topic + + +class PHXClientError(Exception): + pass + + +class PHXTopicTooManyRegistrationsError(PHXClientError): + pass + + +class TopicClosedError(PHXClientError): + def __init__(self, topic: Topic, reason: str): + self.topic = topic + self.reason = reason + super().__init__(topic, reason) diff --git a/phx_events/json_handler.py b/phx_events/json_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..9128cdf00ba22f1b0996377ba6ff692da13c6fc2 --- /dev/null +++ b/phx_events/json_handler.py @@ -0,0 +1,35 @@ +from decimal import Decimal +from typing import Any, Union + +import orjson + + +def decimal_serialiser(_obj: Any) -> float: + if isinstance(_obj, Decimal): + return float(str(_obj)) + + raise TypeError + + +def deep_float_replace(obj: Any) -> Any: + if isinstance(obj, float): + return Decimal(str(obj)) + elif isinstance(obj, dict): + return {key: deep_float_replace(value) for key, value in obj.items()} + elif isinstance(obj, list): + return [deep_float_replace(value) for value in obj] + else: + return obj + + +def dumps(obj: Any) -> bytes: + return orjson.dumps(obj, default=decimal_serialiser) + + +def loads(json: Union[bytes, bytearray, memoryview, str], floats_to_decimal: bool = True) -> Any: + parsed_json = orjson.loads(json) + + if not floats_to_decimal: + return parsed_json + + return deep_float_replace(parsed_json) diff --git a/phx_events/phx_messages.py b/phx_events/phx_messages.py new file mode 100644 index 0000000000000000000000000000000000000000..a0359739c8a4dac57b9d6660c4d0ed5fb4c5ad69 --- /dev/null +++ b/phx_events/phx_messages.py @@ -0,0 +1,101 @@ +import asyncio +from dataclasses import dataclass +from enum import Enum, unique +from functools import cached_property +from typing import Any, NewType, Optional, Protocol, TYPE_CHECKING, Union + + +if TYPE_CHECKING: + from phx_events.client import PHXChannelsClient + + +Topic = NewType('Topic', str) +Event = NewType('Event', str) +ChannelEvent = Union['PHXEvent', Event] +ChannelMessage = Union['PHXMessage', 'PHXEventMessage'] + + +class ExecutorHandler(Protocol): + """Protocol describing a handler that will be called using the provided executor pool""" + + def __call__(self, __message: Union['PHXMessage', 'PHXEventMessage'], __client: 'PHXChannelsClient') -> None: + """ + Args: + __message (Union[PHXMessage, PHXEventMessage]): The message the handler should process + __client (PHXChannelsClient): The client instance + """ + ... # pragma: no cover + + +class CoroutineHandler(Protocol): + """Protocol describing a handler that will be run as a task in the event loop""" + + async def __call__(self, __message: Union['PHXMessage', 'PHXEventMessage'], __client: 'PHXChannelsClient') -> None: + """ + Args: + __message (Union[PHXMessage, PHXEventMessage]): The message the handler should process + __client (PHXChannelsClient): The client instance + """ + ... # pragma: no cover + + +ChannelHandlerFunction = Union[ExecutorHandler, CoroutineHandler] + + +@dataclass() +class EventHandlerConfig: + """ + Args: + queue (asyncio.Queue): The queue that messages are passed into and the event handlers are fed from + default_handlers (list[ChannelHandlerFunction]): Handler functions that should always be run for the specified + event. + topic_handlers (dict[Topic, list[ChannelHandlerFunction]]): Handler functions that should be run only for the + topics specified in the mapping. + task (asyncio.Task): The task that consumes off the `queue` and determines which `default_handlers` and + `topic_handlers` to run. + """ + queue: asyncio.Queue[ChannelMessage] + default_handlers: list[ChannelHandlerFunction] + topic_handlers: dict[Topic, list[ChannelHandlerFunction]] + task: asyncio.Task[None] + + +@unique +class PHXEvent(Enum): + """Phoenix Channels admin events""" + close = 'phx_close' + error = 'phx_error' + join = 'phx_join' + reply = 'phx_reply' + leave = 'phx_leave' + + # hack for typing + value: str + + def __str__(self) -> str: + return self.value + + +@dataclass(frozen=True) +class BasePHXMessage: + topic: Topic + ref: Optional[str] + payload: dict[str, Any] + + @cached_property + def subtopic(self) -> Optional[str]: + if ':' not in self.topic: + return None + + _, subtopic = self.topic.split(':', 1) + return subtopic + + +@dataclass(frozen=True) +class PHXMessage(BasePHXMessage): + event: Event + + +@dataclass(frozen=True) +class PHXEventMessage(BasePHXMessage): + event: PHXEvent diff --git a/phx_events/topic_subscription.py b/phx_events/topic_subscription.py new file mode 100644 index 0000000000000000000000000000000000000000..69b18f77ee0f8cc00345804066f3b694c77143fa --- /dev/null +++ b/phx_events/topic_subscription.py @@ -0,0 +1,25 @@ +from asyncio import Event +from dataclasses import dataclass +from enum import IntEnum, unique +from typing import Optional + +from phx_events.phx_messages import PHXEventMessage + + +@unique +class SubscriptionStatus(IntEnum): + FAILED = 0 + SUCCESS = 1 + + +@dataclass(frozen=True) +class TopicSubscribeResult: + status: SubscriptionStatus + result_message: PHXEventMessage + + +@dataclass() +class TopicRegistration: + status_updated_event: Event + connection_ref: Optional[str] = None + result: Optional[TopicSubscribeResult] = None diff --git a/phx_events/utils.py b/phx_events/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b261e246af53bc96fd3817ef909203b7621970fb --- /dev/null +++ b/phx_events/utils.py @@ -0,0 +1,31 @@ +from datetime import datetime +from typing import Any, Optional + +from phx_events.phx_messages import ChannelEvent, ChannelMessage, PHXEvent, PHXEventMessage, PHXMessage, Topic + + +def parse_event(event: ChannelEvent) -> ChannelEvent: + try: + return PHXEvent(event) + except ValueError: + return event + + +def make_message( + event: ChannelEvent, + topic: Topic, + ref: Optional[str] = None, + payload: Optional[dict[str, Any]] = None, +) -> ChannelMessage: + if payload is None: + payload = {} + + processed_event = parse_event(event) + if isinstance(processed_event, PHXEvent): + return PHXEventMessage(event=processed_event, topic=topic, ref=ref, payload=payload) + else: + return PHXMessage(event=processed_event, topic=topic, ref=ref, payload=payload) + + +def generate_reference(event: ChannelEvent) -> str: + return f'{datetime.now():%Y%m%d%H%M%S}:{event}' diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..290d0ad2c4e31bcef81689207fab65b4d0050481 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,34 @@ +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + + +# If this is removed then remove the additional options in +# the pytest.ini file +pytest_plugins = ['hypothesis.extra.pytestplugin'] + + +@pytest.fixture() +def mock_websocket_client() -> MagicMock: # type: ignore[misc] + with patch('phx_events.client.client', autospec=True) as mocked_websocket: + yield mocked_websocket + + +@pytest.fixture() +async def mock_websocket_connection(mock_websocket_client) -> AsyncMock: # type: ignore[misc] + async with mock_websocket_client.connect('ws://test') as client_connection: + yield client_connection + + +@pytest.fixture() +def mock_executor_pool() -> MagicMock: # type: ignore[misc] + from concurrent.futures import ThreadPoolExecutor + + mock_executor = MagicMock(ThreadPoolExecutor, autospec=True) + yield mock_executor + + +@pytest.fixture() +def mock_executor_contextmanager(mock_executor_pool) -> MagicMock: # type: ignore[misc] + with mock_executor_pool as mock_pool: + yield mock_pool diff --git a/tests/strategy_utils.py b/tests/strategy_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..47e7981dafdd66e569207f184ab147e414a89740 --- /dev/null +++ b/tests/strategy_utils.py @@ -0,0 +1,77 @@ +from typing import Any, Optional, TypedDict + +from hypothesis import strategies as st +from hypothesis.strategies import composite, DrawFn, SearchStrategy + + +PHX_EVENTS = ['phx_close', 'phx_error', 'phx_join', 'phx_reply', 'phx_leave'] + +safe_float_strategy = st.floats(allow_nan=False, allow_infinity=False) +safe_decimal_strategy = st.decimals(allow_nan=False, allow_infinity=False) +# These are the min and max values for a 64bit integer - orjson can't handle bigger ints +# See here: https://github.com/ijl/orjson#int +safe_int_strategy = st.integers(min_value=-9223372036854775807, max_value=18446744073709551615) + +message_payload = st.dictionaries( + keys=st.text(), + values=st.text() | st.booleans() | safe_float_strategy | safe_int_strategy | safe_decimal_strategy | st.datetimes(), +) + + +class EventDict(TypedDict): + topic: str + event: str + ref: Optional[str] + payload: Optional[dict[str, Any]] + + +@composite +def channel_event_strategy( + draw: DrawFn, + topic: Optional[SearchStrategy[str]] = None, + event: Optional[SearchStrategy[str]] = None, + ref: Optional[SearchStrategy[str]] = None, + payload: Optional[SearchStrategy[Optional[dict[str, Any]]]] = None, +) -> EventDict: + if topic is None: + topic = st.text() + + if event is None: + event = st.sampled_from(PHX_EVENTS) | st.text() + + if ref is None: + ref = st.text() | st.none() # type: ignore[operator] + + if payload is None: + payload = st.none() | message_payload + + return { + 'topic': draw(topic), + 'event': draw(event), + 'ref': draw(ref), + 'payload': draw(payload), + } + + +def phx_event_strategy( + topic: Optional[SearchStrategy[str]] = None, + event: Optional[SearchStrategy[str]] = None, + ref: Optional[SearchStrategy[str]] = None, + payload: Optional[SearchStrategy[Optional[dict[str, Any]]]] = None, +) -> SearchStrategy[EventDict]: + if event is None: + event = st.sampled_from(PHX_EVENTS) + + return channel_event_strategy(topic, event, ref, payload) + + +def event_strategy( + topic: Optional[SearchStrategy[str]] = None, + event: Optional[SearchStrategy[str]] = None, + ref: Optional[SearchStrategy[str]] = None, + payload: Optional[SearchStrategy[Optional[dict[str, Any]]]] = None, +) -> SearchStrategy[EventDict]: + if event is None: + event = st.text() + + return channel_event_strategy(topic, event, ref, payload) diff --git a/tests/test_client/__init__.py b/tests/test_client/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/test_client/test_context_manager.py b/tests/test_client/test_context_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..e7ffe279d9ae4d2a667fdc3e09a85b35942ab5fa --- /dev/null +++ b/tests/test_client/test_context_manager.py @@ -0,0 +1,27 @@ +from unittest.mock import patch + +import pytest + +from phx_events.client import PHXChannelsClient + + +pytestmark = pytest.mark.asyncio + + +class TestPHXChannelsClientAEnter: + async def test_returns_self_when_using_as_with_context_manager(self): + phx_client = PHXChannelsClient('ws://web.socket/url/') + + async with phx_client as test_phx_client: + assert isinstance(test_phx_client, PHXChannelsClient) + assert phx_client == test_phx_client + + +class TestPHXChannelsClientAExit: + async def test_calls_shutdown_with_correct_reason(self): + phx_client = PHXChannelsClient('ws://web.socket/url/') + + with patch.object(phx_client, 'shutdown') as mock_shutdown: + await phx_client.__aexit__() + + mock_shutdown.assert_called_with('Leaving PHXChannelsClient context') diff --git a/tests/test_client/test_event_processor.py b/tests/test_client/test_event_processor.py new file mode 100644 index 0000000000000000000000000000000000000000..38347302fe1c01ba68efd6aeb3ff8fe487ba54b4 --- /dev/null +++ b/tests/test_client/test_event_processor.py @@ -0,0 +1,157 @@ +import asyncio +from concurrent.futures import ThreadPoolExecutor +import logging +from unittest.mock import Mock + +import pytest + +from phx_events.client import PHXChannelsClient +from phx_events.phx_messages import ChannelMessage, Event, Topic +from phx_events.utils import make_message + + +pytestmark = pytest.mark.asyncio + + +class TestPHXChannelsClientEventProcessor: + def setup(self): + self.phx_client = PHXChannelsClient('ws://url/') + self.event = Event('event_name') + self.other_event = Event('other_event_name') + self.topic = Topic('topic:subtopic') + + self.event_handler_event = asyncio.Event() + self.other_event_handler_event = asyncio.Event() + self.event_topic_handler_event = asyncio.Event() + + async def event_handler(message: ChannelMessage, client: PHXChannelsClient) -> None: + client.logger.info(f'{event_handler.__name__} {message=}') + self.event_handler_event.set() + + async def other_event_handler(message: ChannelMessage, client: PHXChannelsClient) -> None: + client.logger.info(f'{other_event_handler.__name__} {message=}') + self.other_event_handler_event.set() + + def event_topic_handler(message: ChannelMessage, client: PHXChannelsClient) -> None: + client.logger.info(f'{event_topic_handler.__name__} {message=}') + self.event_topic_handler_event.set() + + self.event_handler = event_handler + self.other_event_handler = other_event_handler + self.event_topic_handler = event_topic_handler + # Register the first event handler + self.phx_client.register_event_handler(self.event, handlers=[event_handler]) + # Register the second event handler + self.phx_client.register_event_handler(self.other_event, handlers=[other_event_handler]) + # and topic event handler + self.phx_client.register_event_handler(self.event, handlers=[event_topic_handler], topic=self.topic) + + # Cancel all the tasks started during registration + for event_handler_config in self.phx_client._event_handler_config.values(): + event_handler_config.task.cancel() + + # Set the client start event so the task doesn't wait in any of the tests + self.phx_client._client_start_event.set() + + async def test_waits_on_client_start_event(self, caplog): + self.phx_client._client_start_event.clear() + + with pytest.raises(asyncio.TimeoutError), caplog.at_level(logging.DEBUG): + await asyncio.wait_for(self.phx_client._event_processor(self.event), timeout=0.2) + + _, log_level, message = caplog.record_tuples[0] + + assert len(caplog.record_tuples) == 1 + assert log_level == logging.DEBUG + assert message == f'{self.event} Worker - Waiting for client start!' + + async def test_only_event_handlers_used_for_event_no_topic(self, event_loop, caplog): + event_handler_config = self.phx_client._event_handler_config[self.event] + event_message = make_message(self.event, Topic('random_topic')) + await event_handler_config.queue.put(event_message) + + mock_loop = Mock(event_loop, autospec=True, wraps=event_loop) + self.phx_client._loop = mock_loop + + # Set log level + caplog.set_level(logging.INFO) + event_loop.create_task(self.phx_client._event_processor(self.event)) + + # Wait for task to process messages + await event_handler_config.queue.join() + + assert event_handler_config.queue.empty() + # The event handler is called with the message and client + assert self.event_handler_event.is_set() + assert caplog.messages[0] == f'{self.event_handler.__name__} message={event_message}' + # We only expect the coroutine to have been called + mock_loop.create_task.assert_called() + # We don't expect the event_topic_handler to have been called + mock_loop.run_in_executor.assert_not_called() + + async def test_all_event_handlers_used_for_event_with_topic(self, event_loop, caplog): + event_handler_config = self.phx_client._event_handler_config[self.event] + event_message = make_message(self.event, self.topic) + await event_handler_config.queue.put(event_message) + + mock_loop = Mock(event_loop, wraps=event_loop) + self.phx_client._loop = mock_loop + self.phx_client._executor_pool = ThreadPoolExecutor() + + caplog.set_level(logging.INFO) + event_loop.create_task(self.phx_client._event_processor(self.event)) + + # Wait for task to process messages + await event_handler_config.queue.join() + + assert event_handler_config.queue.empty() + # The event handler is called with the message and client + assert self.event_handler_event.is_set() + assert self.event_topic_handler_event.is_set() + assert len(caplog.messages) == 2 + assert f'{self.event_handler.__name__} message={event_message}' in caplog.messages + assert f'{self.event_topic_handler.__name__} message={event_message}' in caplog.messages + # We only expect the coroutine to have been called + mock_loop.create_task.assert_called() + # We don't expect the event_topic_handler to have been called + mock_loop.run_in_executor.assert_called() + + async def test_event_handler_errors_intercepted_and_logged(self, event_loop, caplog): + async def coro_erroring_event_handler(message, client): + raise Exception(coro_erroring_event_handler.__name__) + + def erroring_event_handler(message, client): + raise Exception(erroring_event_handler.__name__) + + event = Event('new_event') + self.phx_client.register_event_handler( + event, + handlers=[erroring_event_handler, coro_erroring_event_handler], + ) + event_handler_config = self.phx_client._event_handler_config[event] + event_handler_config.task.cancel() + + event_message = make_message(event, self.topic) + await event_handler_config.queue.put(event_message) + + mock_loop = Mock(event_loop, wraps=event_loop) + self.phx_client._loop = mock_loop + self.phx_client._executor_pool = ThreadPoolExecutor() + + caplog.set_level(logging.INFO) + event_loop.create_task(self.phx_client._event_processor(event)) + + # Wait for task to process messages + await event_handler_config.queue.join() + expected_exception_logs = [ + f"Error executing handler - exception=Exception('{erroring_event_handler.__name__}')", + f"Error executing handler - exception=Exception('{coro_erroring_event_handler.__name__}')", + ] + + assert event_handler_config.queue.empty() + assert len(caplog.messages) == 2 + assert all(error_log in caplog.messages for error_log in expected_exception_logs) + # We only expect the coroutine to have been called + mock_loop.create_task.assert_called() + # We don't expect the event_topic_handler to have been called + mock_loop.run_in_executor.assert_called() diff --git a/tests/test_client/test_init.py b/tests/test_client/test_init.py new file mode 100644 index 0000000000000000000000000000000000000000..2be9d899799e3c02f9fadfcdefc520e04e7a32d0 --- /dev/null +++ b/tests/test_client/test_init.py @@ -0,0 +1,46 @@ +import asyncio +from urllib.parse import urlencode + +import pytest + +from phx_events.client import PHXChannelsClient + + +pytestmark = pytest.mark.asyncio + + +class TestPHXChannelsClientInit: + def setup(self): + self.socket_url = 'ws://test.socket/url/' + self.channel_auth_token = 'test_token' + + self.phx_channels_client = PHXChannelsClient(self.socket_url, self.channel_auth_token) + + def test_async_logger_child_set_as_logger_on_client(self): + from phx_events.async_logger import async_logger + + assert self.phx_channels_client.logger.parent == async_logger + + def test_channel_socket_url_has_token_if_specified(self): + no_token_client = PHXChannelsClient(self.socket_url) + + assert no_token_client.channel_socket_url == self.socket_url + assert self.phx_channels_client.channel_socket_url == f'{self.socket_url}?token={self.channel_auth_token}' + + def test_channel_socket_url_token_is_made_url_safe(self): + unsafe_token = '==??==' + safe_token_client = PHXChannelsClient(self.socket_url, channel_auth_token=unsafe_token) + + assert safe_token_client.channel_socket_url != f'{self.socket_url}?token={unsafe_token}' + assert safe_token_client.channel_socket_url == f'{self.socket_url}?{urlencode({"token": unsafe_token})}' + + def test_event_loop_set_by_default_if_not_specified(self): + no_loop_specified_client = PHXChannelsClient(self.socket_url) + + assert isinstance(no_loop_specified_client._loop, asyncio.BaseEventLoop) + + def test_event_loop_set_to_argument_if_specified(self): + event_loop = asyncio.get_event_loop() + specified_loop_client = PHXChannelsClient(self.socket_url, event_loop=event_loop) + + assert specified_loop_client._loop == event_loop diff --git a/tests/test_client/test_parse_message.py b/tests/test_client/test_parse_message.py new file mode 100644 index 0000000000000000000000000000000000000000..8a2961135ed2dda093f9f0268303f721c9ce8bb8 --- /dev/null +++ b/tests/test_client/test_parse_message.py @@ -0,0 +1,39 @@ +from hypothesis import given + +from phx_events import json_handler +from phx_events.client import PHXChannelsClient +from phx_events.phx_messages import PHXEvent, PHXEventMessage, PHXMessage +from tests.strategy_utils import event_strategy, phx_event_strategy + + +class TestPHXChannelsClientParseMessage: + def setup(self): + self.phx_client = PHXChannelsClient('ws://url') + + @given(event_strategy()) + def test_returns_phx_message_for_event_socket_message(self, event_dict): + socket_message = json_handler.dumps(event_dict) + # This is done to convert any Python types in the event_dict payload to JSON-versions + reserialised_event_dict = json_handler.loads(socket_message) + + parsed_message = self.phx_client._parse_message(socket_message) + + assert isinstance(parsed_message, PHXMessage) + assert parsed_message.topic == reserialised_event_dict['topic'] == event_dict['topic'] + assert parsed_message.event == reserialised_event_dict['event'] == event_dict['event'] + assert parsed_message.ref == reserialised_event_dict['ref'] == event_dict['ref'] + assert parsed_message.payload == (reserialised_event_dict['payload'] or {}) + + @given(phx_event_strategy()) + def test_returns_phx_event_message_for_event_socket_message(self, event_dict): + socket_message = json_handler.dumps(event_dict) + # This is done to convert any Python types in the event_dict payload to JSON-versions + reserialised_event_dict = json_handler.loads(socket_message) + + parsed_message = self.phx_client._parse_message(socket_message) + + assert isinstance(parsed_message, PHXEventMessage) + assert parsed_message.topic == reserialised_event_dict['topic'] == event_dict['topic'] + assert parsed_message.event == PHXEvent(reserialised_event_dict['event']) == PHXEvent(event_dict['event']) + assert parsed_message.ref == reserialised_event_dict['ref'] == event_dict['ref'] + assert parsed_message.payload == (reserialised_event_dict['payload'] or {}) diff --git a/tests/test_client/test_process_topic_registration_responses.py b/tests/test_client/test_process_topic_registration_responses.py new file mode 100644 index 0000000000000000000000000000000000000000..ac7741fca7afa2ebed3b18c7e752993762f83304 --- /dev/null +++ b/tests/test_client/test_process_topic_registration_responses.py @@ -0,0 +1,44 @@ +import pytest + +from phx_events.client import PHXChannelsClient +from phx_events.phx_messages import PHXEvent, Topic +from phx_events.topic_subscription import SubscriptionStatus +from phx_events.utils import make_message + + +pytestmark = pytest.mark.asyncio + + +class TestPHXChannelsClientProcessTopicRegistrationResponses: + def setup(self): + self.phx_client = PHXChannelsClient('ws://url/') + self.topic = Topic('topic:subtopic') + self.topic_event = self.phx_client.register_topic_subscription(self.topic) + + async def test_updates_registration_status_for_success(self, event_loop): + registration_response = make_message(PHXEvent.reply, self.topic, payload={'status': 'ok'}) + await self.phx_client._registration_queue.put(registration_response) + + event_loop.create_task(self.phx_client.process_topic_registration_responses()) + + # Wait until the item is processed + await self.phx_client._registration_queue.join() + registration_status = self.phx_client._topic_registration_status[self.topic] + + assert self.topic_event.is_set() + assert registration_status.result.status == SubscriptionStatus.SUCCESS + assert registration_status.result.result_message == registration_response + + async def test_updates_registration_status_for_failed(self, event_loop): + negative_registration_response = make_message(PHXEvent.reply, self.topic, payload={'status': 'error'}) + await self.phx_client._registration_queue.put(negative_registration_response) + + event_loop.create_task(self.phx_client.process_topic_registration_responses()) + + # Wait until the item is processed + await self.phx_client._registration_queue.join() + registration_status = self.phx_client._topic_registration_status[self.topic] + + assert self.topic_event.is_set() + assert registration_status.result.status == SubscriptionStatus.FAILED + assert registration_status.result.result_message == negative_registration_response diff --git a/tests/test_client/test_process_websocket_messages.py b/tests/test_client/test_process_websocket_messages.py new file mode 100644 index 0000000000000000000000000000000000000000..ea54ed72f151a2bda28ef190034fe1498e5b640c --- /dev/null +++ b/tests/test_client/test_process_websocket_messages.py @@ -0,0 +1,104 @@ +import logging + +import pytest + +from phx_events import json_handler +from phx_events.client import PHXChannelsClient +from phx_events.exceptions import TopicClosedError +from phx_events.phx_messages import Event, PHXEvent, Topic +from phx_events.utils import make_message +from tests.utils import async_iter + +pytestmark = pytest.mark.asyncio + + +class TestPHXChannelsClientProcessWebsocketMessages: + def setup(self): + self.phx_client = PHXChannelsClient('ws://url/') + self.topic = Topic('topic:subtopic') + + async def test_raises_exception_on_phx_close_event(self, mock_websocket_connection): + close_message = json_handler.dumps(make_message(PHXEvent.close, self.topic)) + mock_websocket_connection.__aiter__.side_effect = lambda: async_iter(close_message) + + with pytest.raises(TopicClosedError, match=r"'topic:subtopic', 'Upstream closed'"): + await self.phx_client.process_websocket_messages(mock_websocket_connection) + + async def test_raises_exception_on_phx_error_event(self, mock_websocket_connection): + error_message = json_handler.dumps(make_message(PHXEvent.error, self.topic)) + mock_websocket_connection.__aiter__.side_effect = lambda: async_iter(error_message) + + with pytest.raises(TopicClosedError, match=r"'topic:subtopic', 'Upstream error'"): + await self.phx_client.process_websocket_messages(mock_websocket_connection) + + async def test_puts_message_in_topic_registration_queue_if_appropriate(self, mock_websocket_connection): + self.phx_client.register_topic_subscription(self.topic) + + topic_registration_message = make_message(PHXEvent.reply, self.topic) + topic_registration_socket_message = json_handler.dumps(topic_registration_message) + mock_websocket_connection.__aiter__.side_effect = lambda: async_iter(topic_registration_socket_message) + + await self.phx_client.process_websocket_messages(mock_websocket_connection) + + queued_registration_message = await self.phx_client._registration_queue.get() + + assert queued_registration_message == topic_registration_message + + async def test_does_not_put_message_in_topic_registration_queue_if_not_phx_reply(self, mock_websocket_connection): + self.phx_client.register_topic_subscription(self.topic) + + topic_registration_message = make_message(PHXEvent.join, self.topic) + topic_registration_socket_message = json_handler.dumps(topic_registration_message) + mock_websocket_connection.__aiter__.side_effect = lambda: async_iter(topic_registration_socket_message) + + await self.phx_client.process_websocket_messages(mock_websocket_connection) + + assert self.phx_client._registration_queue.empty() + + async def test_does_not_put_message_in_topic_registration_queue_if_registration_event_set( + self, + mock_websocket_connection, + ): + registration_event = self.phx_client.register_topic_subscription(self.topic) + + topic_registration_message = make_message(PHXEvent.reply, self.topic) + topic_registration_socket_message = json_handler.dumps(topic_registration_message) + mock_websocket_connection.__aiter__.side_effect = lambda: async_iter(topic_registration_socket_message) + + registration_event.set() + await self.phx_client.process_websocket_messages(mock_websocket_connection) + + assert self.phx_client._registration_queue.empty() + + async def test_event_ignored_if_no_event_handler_registered(self, mock_websocket_connection, caplog): + # Register a handler for a specific event + self.phx_client.register_event_handler(Event('specific_event'), handlers=[lambda x, y: None]) + # Create a message about a random_event + event_socket_message = json_handler.dumps(make_message(Event('random_event'), self.topic)) + mock_websocket_connection.__aiter__.side_effect = lambda: async_iter(event_socket_message) + + with caplog.at_level(logging.DEBUG): + await self.phx_client.process_websocket_messages(mock_websocket_connection) + + logger_name, log_level, message = caplog.record_tuples[-1] + + assert logger_name == 'phx_events.async_logger.phx_events.client' + assert log_level == logging.DEBUG + assert message == ( + "Ignoring phx_message=PHXMessage(topic='topic:subtopic', ref=None, payload={}, event='random_event') " + '- no event handlers registered' + ) + + async def test_put_message_in_event_handler_queue_handlers_exist(self, mock_websocket_connection): + event = Event('specific_event') + self.phx_client.register_event_handler(event, handlers=[lambda x, y: None]) + + event_message = make_message(event, self.topic) + event_socket_message = json_handler.dumps(event_message) + mock_websocket_connection.__aiter__.side_effect = lambda: async_iter(event_socket_message) + + await self.phx_client.process_websocket_messages(mock_websocket_connection) + + event_handler_config = self.phx_client._event_handler_config[event] + + assert event_handler_config.queue.get_nowait() == event_message diff --git a/tests/test_client/test_register_event_handler.py b/tests/test_client/test_register_event_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..898a23afd9762da90cb496be024fef31e404d966 --- /dev/null +++ b/tests/test_client/test_register_event_handler.py @@ -0,0 +1,69 @@ +import asyncio +from unittest.mock import Mock, patch + +from phx_events.client import PHXChannelsClient +from phx_events.phx_messages import Event, Topic + + +async def handler_function(message, client): + return None + + +class TestPHXChannelsClientRegisterEventHandler: + def setup(self): + self.phx_client = PHXChannelsClient('ws://url/') + self.event = Event('event_name') + + def test_event_added_to_event_handler_config(self): + mock_coroutine = Mock() + mock_event_processor = Mock(return_value=mock_coroutine) + self.phx_client._event_processor = mock_event_processor + + with patch.object(self.phx_client, '_loop') as mock_loop: + self.phx_client.register_event_handler(event=self.event, handlers=[handler_function]) + + handler_config = self.phx_client._event_handler_config[self.event] + # _event_process is called with passed in event + mock_event_processor.assert_called_with(self.event) + # _loop.create_task is called with mock_coroutine the result of mock_event_processor(self.event) + mock_loop.create_task.assert_called_with(mock_coroutine) + + assert isinstance(handler_config.queue, asyncio.Queue) + # Assert that the task is the result of calling _loop.create_task + assert handler_config.task == mock_loop.create_task.return_value + assert handler_config.default_handlers == [handler_function] + assert handler_config.topic_handlers == {} + + def test_handlers_add_to_topic_handlers_if_topic_is_passed_in(self): + topic = Topic('topic:subtopic') + + with patch.object(self.phx_client, '_loop'): + self.phx_client.register_event_handler( + event=self.event, + handlers=[handler_function], + topic=topic, + ) + + handler_config = self.phx_client._event_handler_config[self.event] + + assert len(handler_config.default_handlers) == 0 + assert handler_config.topic_handlers == {topic: [handler_function]} + + def test_events_with_the_same_name_are_grouped(self): + def second_handler_function(message, client): + return None + + topic = Topic('topic:subtopic') + + with patch.object(self.phx_client, '_loop'): + self.phx_client.register_event_handler(event=self.event, handlers=[handler_function]) + self.phx_client.register_event_handler(event=self.event, handlers=[second_handler_function]) + self.phx_client.register_event_handler(event=self.event, handlers=[second_handler_function], topic=topic) + + handler_config = self.phx_client._event_handler_config[self.event] + + assert len(handler_config.default_handlers) == 2 + assert handler_function in handler_config.default_handlers + assert second_handler_function in handler_config.default_handlers + assert len(handler_config.topic_handlers) == 1 + assert handler_config.topic_handlers == {topic: [second_handler_function]} diff --git a/tests/test_client/test_register_topic_subscription.py b/tests/test_client/test_register_topic_subscription.py new file mode 100644 index 0000000000000000000000000000000000000000..5ebcfe840f87ff4f5eef22431dcbc2bcc3fe2cac --- /dev/null +++ b/tests/test_client/test_register_topic_subscription.py @@ -0,0 +1,27 @@ +import asyncio + +import pytest + +from phx_events.client import PHXChannelsClient +from phx_events.exceptions import PHXTopicTooManyRegistrationsError +from phx_events.phx_messages import Topic + + +class TestPHXChannelsClientRegisterTopicSubscription: + def setup(self): + self.phx_client = PHXChannelsClient('ws://url') + + def test_topic_registered_returns_event(self): + register_event = self.phx_client.register_topic_subscription(Topic('topic:subtopic')) + + assert isinstance(register_event, asyncio.Event) + + def test_registering_the_same_topic_multiple_times_raises_exception(self): + topic = Topic('topic:subtopic') + self.phx_client.register_topic_subscription(topic) + topic_ref = self.phx_client._topic_registration_status[topic].connection_ref + + expected_error = f'Topic {topic} already registered with {topic_ref=}' + + with pytest.raises(PHXTopicTooManyRegistrationsError, match=expected_error): + self.phx_client.register_topic_subscription(topic) diff --git a/tests/test_client/test_send_message.py b/tests/test_client/test_send_message.py new file mode 100644 index 0000000000000000000000000000000000000000..d0122ca8d31138c77c442f28323daedf62e5b2ae --- /dev/null +++ b/tests/test_client/test_send_message.py @@ -0,0 +1,25 @@ +from unittest.mock import AsyncMock + +from hypothesis import given +import pytest + +from phx_events import json_handler +from phx_events.client import PHXChannelsClient +from phx_events.utils import make_message +from tests.strategy_utils import channel_event_strategy + + +pytestmark = pytest.mark.asyncio + + +class TestPHXChannelsClientSendMessage: + @given(channel_event_strategy()) + async def test_correct_message_passed_to_websocket_send(self, event_dict): + mock_websocket = AsyncMock() + message = make_message(**event_dict) + + async with PHXChannelsClient('ws://test.websocket/') as client: + await client._send_message(mock_websocket, message) + + mock_websocket.send.assert_called_with(json_handler.dumps(message)) + mock_websocket.send.assert_awaited() diff --git a/tests/test_client/test_shutdown.py b/tests/test_client/test_shutdown.py new file mode 100644 index 0000000000000000000000000000000000000000..26d58330c460ddb4df78f1e02fe85313d7aaa0dd --- /dev/null +++ b/tests/test_client/test_shutdown.py @@ -0,0 +1,67 @@ +from asyncio import Queue +from unittest.mock import AsyncMock, Mock + +from phx_events.client import PHXChannelsClient +from phx_events.phx_messages import EventHandlerConfig + + +class TestPHXChannelsClientShutdown: + def setup(self): + self.event_loop = AsyncMock() + self.phx_client = PHXChannelsClient('ws://url', event_loop=self.event_loop) + + def test_if_websocket_is_not_none_close_task_queued(self): + close_coroutine = Mock() + websocket = Mock() + websocket.close.return_value = close_coroutine + + self.phx_client.shutdown('test', websocket=websocket) + + websocket.close.assert_called() + self.event_loop.create_task.assert_called_with(close_coroutine) + + def test_if_topic_registration_task_is_not_none_cancel_task(self): + topic_registration_task = Mock() + self.phx_client._topic_registration_task = topic_registration_task + + self.phx_client.shutdown('test') + + topic_registration_task.cancel.assert_called() + + def test_any_event_handlers_registered_tasks_are_cancelled(self): + event_handler_1_task = Mock() + event_handler_2_task = Mock() + + self.phx_client._event_handler_config = { + 'event_1_name': EventHandlerConfig( + queue=Queue(), + default_handlers=[], + topic_handlers={}, + task=event_handler_1_task, + ), + 'event_2_name': EventHandlerConfig( + queue=Queue(), + default_handlers=[], + topic_handlers={}, + task=event_handler_2_task, + ), + } + + self.phx_client.shutdown('test') + + event_handler_1_task.cancel.assert_called() + event_handler_2_task.cancel.assert_called() + + def test_if_executor_pool_is_not_none_call_shutdown(self): + executor_pool = Mock() + + self.phx_client.shutdown('test', executor_pool=executor_pool) + + executor_pool.shutdown.assert_called_with(wait=True, cancel_futures=False) + + def test_if_executor_pool_is_not_none_call_shutdown_with_no_wait(self): + executor_pool = Mock() + + self.phx_client.shutdown('test', executor_pool=executor_pool, wait_for_completion=False) + + executor_pool.shutdown.assert_called_with(wait=False, cancel_futures=True) diff --git a/tests/test_client/test_start_processing.py b/tests/test_client/test_start_processing.py new file mode 100644 index 0000000000000000000000000000000000000000..dee2277a404fa8f69b06078363a987c6f592d3ad --- /dev/null +++ b/tests/test_client/test_start_processing.py @@ -0,0 +1,84 @@ +import signal +from unittest.mock import AsyncMock, Mock, patch + +import pytest + +from phx_events.client import PHXChannelsClient +from phx_events.phx_messages import Topic + + +pytestmark = pytest.mark.asyncio + + +class TestPHXChannelsClientStartProcessing: + def setup(self): + self.phx_client = PHXChannelsClient('ws://url/') + self.phx_client.register_topic_subscription(Topic('topic:subtopic')) + + async def test_does_nothing_if_no_topics_registered(self, caplog): + await PHXChannelsClient('ws://url/').start_processing() + + assert len(caplog.messages) == 1 + assert caplog.messages[0] == 'No subscribed topics nothing to do here - ending processing!' + + async def test_threadpool_executor_used_if_no_executor_pool_specified(self, mock_websocket_client): + with patch('phx_events.client.ThreadPoolExecutor') as mock_thread_pool: + await self.phx_client.start_processing() + + mock_thread_pool.assert_called() + + async def test_websocket_client_called_with_url(self, mock_websocket_client): + await self.phx_client.start_processing() + + mock_websocket_client.connect.assert_called_with(self.phx_client.channel_socket_url) + + async def test_signal_handlers_functions_created_and_registered_correctly( + self, + mock_executor_pool, + mock_executor_contextmanager, + mock_websocket_connection, + ): + mock_loop = Mock() + self.phx_client._loop = mock_loop + # Prevent any processing attempts + self.phx_client._subscribe_to_registered_topics = AsyncMock() + self.phx_client.process_websocket_messages = AsyncMock() + + partial_patch = patch('phx_events.client.partial') + shutdown_patch = patch.object(self.phx_client, 'shutdown') + + with shutdown_patch as mock_shutdown, partial_patch as mock_partial: + await self.phx_client.start_processing(executor_pool=mock_executor_pool) + + mock_partial.assert_any_call( + mock_shutdown, + websocket=mock_websocket_connection, + executor_pool=mock_executor_contextmanager, + wait_for_completion=False, + ) + mock_partial.assert_any_call(mock_partial.return_value, reason='SIGTERM') + mock_partial.assert_any_call(mock_partial.return_value, reason='Keyboard Interrupt') + mock_loop.add_signal_handler.assert_any_call(signal.SIGTERM, mock_partial.return_value) + mock_loop.add_signal_handler.assert_any_call(signal.SIGINT, mock_partial.return_value) + + async def test_subscribe_to_registered_topics_called_with_websocket(self, mock_websocket_connection): + # Prevent any processing attempts + self.phx_client.process_websocket_messages = AsyncMock() + + mock_subscribe_to_topics = AsyncMock() + self.phx_client._subscribe_to_registered_topics = mock_subscribe_to_topics + + await self.phx_client.start_processing() + + mock_subscribe_to_topics.assert_called_with(mock_websocket_connection) + + async def test_process_websocket_messages_called_with_websocket(self, mock_websocket_connection): + # Prevent any processing attempts + self.phx_client._subscribe_to_registered_topics = AsyncMock() + + mock_process_websocket_messages = AsyncMock() + self.phx_client.process_websocket_messages = mock_process_websocket_messages + + await self.phx_client.start_processing() + + mock_process_websocket_messages.assert_called_with(mock_websocket_connection) diff --git a/tests/test_client/test_subscribe_to_registered_topics.py b/tests/test_client/test_subscribe_to_registered_topics.py new file mode 100644 index 0000000000000000000000000000000000000000..d24fae40a50c18b8e5ef6a201b05c46b345fa2ef --- /dev/null +++ b/tests/test_client/test_subscribe_to_registered_topics.py @@ -0,0 +1,43 @@ +from unittest.mock import AsyncMock, patch + +import pytest + +from phx_events.client import PHXChannelsClient +from phx_events.phx_messages import PHXEvent, Topic +from phx_events.utils import make_message + + +pytestmark = pytest.mark.asyncio + + +class TestPHXChannelsClientSubscribeToRegisteredTopics: + def setup(self): + self.phx_client = PHXChannelsClient('ws://url/') + self.topic = Topic('topic:subtopic') + self.phx_client.register_topic_subscription(self.topic) + + async def test_process_topic_registration_responses_task_started(self, mock_websocket_connection): + mock_process_topic_responses = AsyncMock() + self.phx_client.process_topic_registration_responses = lambda: mock_process_topic_responses + + with patch.object(self.phx_client, '_loop') as mock_loop: + await self.phx_client._subscribe_to_registered_topics(mock_websocket_connection) + + mock_loop.create_task.assert_called_with(mock_process_topic_responses) + + async def test_all_topics_in_topic_registration_status_dict_have_messages_sent(self, mock_websocket_connection): + loop_patch = patch.object(self.phx_client, '_loop') + gather_patch = patch('phx_events.client.asyncio.gather', new_callable=AsyncMock) + partial_patch = patch('phx_events.client.partial') + + with loop_patch, partial_patch as mock_partial, gather_patch as mock_gather: + await self.phx_client._subscribe_to_registered_topics(mock_websocket_connection) + + expected_join_message = make_message(event=PHXEvent.join, topic=self.topic) + + # First partial application applying websocket to _send_message + mock_partial.assert_called_with(self.phx_client._send_message, mock_websocket_connection) + # Second partial application applying the messages to the first partial application + mock_partial.return_value.assert_called_with(expected_join_message) + # Gather is called on the results of the 2nd partial application + mock_gather.assert_called_with(mock_partial.return_value.return_value) diff --git a/tests/test_json_handler/__init__.py b/tests/test_json_handler/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/test_json_handler/test_decimal_serialiser.py b/tests/test_json_handler/test_decimal_serialiser.py new file mode 100644 index 0000000000000000000000000000000000000000..9e6ec1f1b65a1a4939c3c7bb95f81606fa3e84b0 --- /dev/null +++ b/tests/test_json_handler/test_decimal_serialiser.py @@ -0,0 +1,20 @@ +from hypothesis import given, strategies as st +import pytest + +from phx_events import json_handler + + +@given(st.text() | st.integers() | st.datetimes() | st.floats() | st.booleans()) +def test_raises_type_error_if_not_a_decimal(obj): + with pytest.raises(TypeError): + json_handler.decimal_serialiser(obj) + + +@given(st.decimals(allow_nan=False)) +def test_returns_serialised_decimals(decimal_obj): + serialised_decimal = json_handler.decimal_serialiser(decimal_obj) + + expected_serialisation = float(str(decimal_obj)) + + assert isinstance(serialised_decimal, float) + assert serialised_decimal == expected_serialisation diff --git a/tests/test_json_handler/test_deep_float_replace.py b/tests/test_json_handler/test_deep_float_replace.py new file mode 100644 index 0000000000000000000000000000000000000000..8dab4117fdcc95e2a8f755caaee7395d1191504e --- /dev/null +++ b/tests/test_json_handler/test_deep_float_replace.py @@ -0,0 +1,66 @@ +from decimal import Decimal + +from hypothesis import given, strategies as st + +from phx_events import json_handler + + +@given(st.floats(allow_nan=False)) +def test_returns_decimal_if_obj_is_float(float_obj): + decimal_replaced_float = json_handler.deep_float_replace(float_obj) + + assert isinstance(decimal_replaced_float, Decimal) + assert decimal_replaced_float == Decimal(str(float_obj)) + + +@given(st.integers() | st.decimals(allow_nan=False) | st.text() | st.datetimes()) +def test_returns_obj_if_not_float(obj): + assert json_handler.deep_float_replace(obj) == obj + + +@given(st.lists(st.floats(allow_nan=False))) +def test_converts_elements_of_a_list(float_list_obj): + decimal_replaced_list = json_handler.deep_float_replace(float_list_obj) + + expected_result = [Decimal(str(value)) for value in float_list_obj] + + assert all(isinstance(value, Decimal) for value in decimal_replaced_list) + assert decimal_replaced_list == expected_result + + +@given(st.dictionaries(st.text(), st.floats(allow_nan=False))) +def test_converts_elements_of_a_dict(float_dict_obj): + decimal_replaced_dict = json_handler.deep_float_replace(float_dict_obj) + + expected_result = {key: Decimal(str(value)) for key, value in float_dict_obj.items()} + + assert all(isinstance(value, Decimal) for value in decimal_replaced_dict.values()) + assert decimal_replaced_dict == expected_result + + +def test_converts_floats_in_complex_object(): + complex_object = [ + { + 'some_floats': [1.2, 1.3, 1.4, '1.5'], + 'all_floats': { + 'float_1': 1.0, + 'float_2': 2.0, + 'float_3-5': [3.0, 4.0, 5.0], + }, + }, + [1.555, 2.555, 3.555], + ] + + converted_complex_object = json_handler.deep_float_replace(complex_object) + + assert converted_complex_object == [ + { + 'some_floats': [Decimal('1.2'), Decimal('1.3'), Decimal('1.4'), '1.5'], + 'all_floats': { + 'float_1': Decimal('1.0'), + 'float_2': Decimal('2.0'), + 'float_3-5': [Decimal('3.0'), Decimal('4.0'), Decimal('5.0')], + }, + }, + [Decimal('1.555'), Decimal('2.555'), Decimal('3.555')], + ] diff --git a/tests/test_json_handler/test_dumps.py b/tests/test_json_handler/test_dumps.py new file mode 100644 index 0000000000000000000000000000000000000000..ee0bed1dd3a959577577302f870e722e4a1d7c8d --- /dev/null +++ b/tests/test_json_handler/test_dumps.py @@ -0,0 +1,26 @@ +from datetime import datetime +from decimal import Decimal + +from phx_events import json_handler + + +def test_dumps_returns_json_string_and_handles_decimals(): + test_datetime = datetime(2021, 8, 30, 15, 56, 39, 1254) + dump_dict = { + 'float': 1.5555, + 'decimals': [Decimal('1.3'), Decimal('2.6689')], + 'datetime': test_datetime, + 'deeper_dict': { + 'list': ['a', 'b', 'c', test_datetime], + 'text': 'Yes!', + }, + } + + dict_json = json_handler.dumps(dump_dict) + + assert dict_json == ( + '{"float":1.5555,' + '"decimals":[1.3,2.6689],' + '"datetime":"2021-08-30T15:56:39.001254",' + '"deeper_dict":{"list":["a","b","c","2021-08-30T15:56:39.001254"],"text":"Yes!"}}' + ).encode() diff --git a/tests/test_json_handler/test_loads.py b/tests/test_json_handler/test_loads.py new file mode 100644 index 0000000000000000000000000000000000000000..c750524362a4b627be188777134647d9aa20f0ac --- /dev/null +++ b/tests/test_json_handler/test_loads.py @@ -0,0 +1,52 @@ +from datetime import datetime +from decimal import Decimal + +from phx_events import json_handler + + +def test_loads_returns_dictionary_and_handles_decimals_when_floats_to_decimal_true(): + json_bytes = ( + '{"float":1.5555,' + '"decimals":[1.3,2.6689],' + '"datetime":"2021-08-30T15:56:39.001254",' + '"deeper_dict":{"list":["a","b","c","2021-08-30T15:56:39.001254"],"text":"Yes!"}}' + ).encode() + + expected_datetime = datetime(2021, 8, 30, 15, 56, 39, 1254) + expected_dict = { + 'float': Decimal('1.5555'), + 'decimals': [Decimal('1.3'), Decimal('2.6689')], + 'datetime': expected_datetime.isoformat(), + 'deeper_dict': { + 'list': ['a', 'b', 'c', expected_datetime.isoformat()], + 'text': 'Yes!', + }, + } + + json_dict = json_handler.loads(json_bytes) + + assert json_dict == expected_dict + + +def test_loads_returns_dictionary_and_leaves_floats_as_floats_when_floats_to_decimal_false(): + json_bytes = ( + '{"float":1.5555,' + '"decimals":[1.3,2.6689],' + '"datetime":"2021-08-30T15:56:39.001254",' + '"deeper_dict":{"list":["a","b","c","2021-08-30T15:56:39.001254"],"text":"Yes!"}}' + ).encode() + + expected_datetime = datetime(2021, 8, 30, 15, 56, 39, 1254) + expected_dict = { + 'float': 1.5555, + 'decimals': [1.3, 2.6689], + 'datetime': expected_datetime.isoformat(), + 'deeper_dict': { + 'list': ['a', 'b', 'c', expected_datetime.isoformat()], + 'text': 'Yes!', + }, + } + + json_dict = json_handler.loads(json_bytes, floats_to_decimal=False) + + assert json_dict == expected_dict diff --git a/tests/test_phx_messages/__init__.py b/tests/test_phx_messages/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/test_phx_messages/test_phx_event_message.py b/tests/test_phx_messages/test_phx_event_message.py new file mode 100644 index 0000000000000000000000000000000000000000..a171b784b016f393cc2f0a507d18ed57c6c78345 --- /dev/null +++ b/tests/test_phx_messages/test_phx_event_message.py @@ -0,0 +1,13 @@ +from phx_events.phx_messages import PHXEvent, PHXEventMessage, Topic + + +class TestSubtopic: + def test_returns_subtopic_if_it_exists(self): + phx_message = PHXEventMessage(topic=Topic('topic:subtopic:info'), ref='ref', event=PHXEvent.reply, payload={}) + + assert phx_message.subtopic == 'subtopic:info' + + def test_returns_none_if_it_does_not_exist(self): + phx_message = PHXEventMessage(topic=Topic('topic'), ref='ref', event=PHXEvent.reply, payload={}) + + assert phx_message.subtopic is None diff --git a/tests/test_phx_messages/test_phx_message.py b/tests/test_phx_messages/test_phx_message.py new file mode 100644 index 0000000000000000000000000000000000000000..6279093f998d0175b96430ddc69536004c38a6ef --- /dev/null +++ b/tests/test_phx_messages/test_phx_message.py @@ -0,0 +1,13 @@ +from phx_events.phx_messages import Event, PHXMessage, Topic + + +class TestSubtopic: + def test_returns_subtopic_if_it_exists(self): + phx_message = PHXMessage(topic=Topic('topic:subtopic:info'), ref='ref', event=Event('test_event'), payload={}) + + assert phx_message.subtopic == 'subtopic:info' + + def test_returns_none_if_it_does_not_exist(self): + phx_message = PHXMessage(topic=Topic('topic'), ref='ref', event=Event('test_event'), payload={}) + + assert phx_message.subtopic is None diff --git a/tests/test_utils.py b/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..21cffac0668f8b0bb1e869413473e916fe5b94a7 --- /dev/null +++ b/tests/test_utils.py @@ -0,0 +1,68 @@ +from freezegun import freeze_time +from hypothesis import given, strategies as st + +from phx_events import utils +from phx_events.phx_messages import Event, PHXEvent, PHXEventMessage, PHXMessage +from tests.strategy_utils import channel_event_strategy, event_strategy, phx_event_strategy, PHX_EVENTS + + +class TestParseEvent: + @given(st.sampled_from(PHX_EVENTS)) + def test_returns_event_enum_for_valid_phx_events(self, event_name): + parsed_event = utils.parse_event(Event(event_name)) + + assert isinstance(parsed_event, PHXEvent) + + @given(st.text().filter(lambda x: x not in PHX_EVENTS)) + def test_returns_string_for_anything_that_is_not_a_phx_event(self, random_event): + parsed_event = utils.parse_event(Event(random_event)) + + assert isinstance(parsed_event, str) + + +class TestMakeMessage: + @given(phx_event_strategy()) + def test_phx_event_message_returned_for_phx_event(self, phx_event_dict): + message = utils.make_message( + event=phx_event_dict['event'], + topic=phx_event_dict['topic'], + ref=phx_event_dict['ref'], + payload=phx_event_dict['payload'], + ) + + assert isinstance(message, PHXEventMessage) + assert message.event == PHXEvent(phx_event_dict['event']) + + @given(event_strategy()) + def test_phx_message_returned_for_other_events(self, event_dict): + message = utils.make_message( + event=event_dict['event'], + topic=event_dict['topic'], + ref=event_dict['ref'], + payload=event_dict['payload'], + ) + + assert isinstance(message, PHXMessage) + assert isinstance(message.event, str) + + @given(channel_event_strategy(payload=st.none())) + def test_none_payload_turned_into_empty_dict(self, event_dict): + message = utils.make_message( + event=event_dict['event'], + topic=event_dict['topic'], + ref=event_dict['ref'], + payload=event_dict['payload'], + ) + + assert message.payload == {} + + +class TestGenerateReference: + @given(st.text() | st.sampled_from(PHXEvent)) + def test_returns_correctly_for_event(self, event): + frozen_time = '2021-08-20T15:58:34' + + with freeze_time(frozen_time): + ref = utils.generate_reference(event) + + assert ref == f'20210820155834:{event!s}' diff --git a/tests/utils.py b/tests/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..dae1615c518050232cac60998fa6e0b565015368 --- /dev/null +++ b/tests/utils.py @@ -0,0 +1,8 @@ +from typing import TypeVar, AsyncIterator + +T = TypeVar('T') + + +async def async_iter(*items: T) -> AsyncIterator[T]: + for item in items: + yield item