File size: 75,248 Bytes
d086025 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 | 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
|