|
| 1 | +import asyncio |
| 2 | + |
| 3 | +import pytest |
| 4 | +from slack_sdk.web.async_client import AsyncWebClient |
| 5 | + |
| 6 | +from slack_bolt.adapter.socket_mode.aiohttp import AsyncSocketModeHandler |
| 7 | +from slack_bolt.app.async_app import AsyncApp |
| 8 | +from tests.mock_web_api_server import ( |
| 9 | + setup_mock_web_api_server, |
| 10 | + cleanup_mock_web_api_server, |
| 11 | +) |
| 12 | +from tests.utils import remove_os_env_temporarily, restore_os_env |
| 13 | +from ...adapter_tests.socket_mode.mock_socket_mode_server import ( |
| 14 | + start_socket_mode_server, |
| 15 | + stop_socket_mode_server_async, |
| 16 | +) |
| 17 | + |
| 18 | + |
| 19 | +class TestSocketModeAiohttp: |
| 20 | + valid_token = "xoxb-valid" |
| 21 | + mock_api_server_base_url = "http://localhost:8888" |
| 22 | + web_client = AsyncWebClient( |
| 23 | + token=valid_token, |
| 24 | + base_url=mock_api_server_base_url, |
| 25 | + ) |
| 26 | + |
| 27 | + @pytest.fixture |
| 28 | + def event_loop(self): |
| 29 | + old_os_env = remove_os_env_temporarily() |
| 30 | + try: |
| 31 | + setup_mock_web_api_server(self) |
| 32 | + loop = asyncio.get_event_loop() |
| 33 | + yield loop |
| 34 | + loop.close() |
| 35 | + cleanup_mock_web_api_server(self) |
| 36 | + finally: |
| 37 | + restore_os_env(old_os_env) |
| 38 | + |
| 39 | + @pytest.mark.asyncio |
| 40 | + async def test_lazy_listeners(self): |
| 41 | + start_socket_mode_server(self, 3021) |
| 42 | + await asyncio.sleep(1) # wait for the server |
| 43 | + |
| 44 | + app = AsyncApp(client=self.web_client) |
| 45 | + |
| 46 | + result = {"lazy_called": False} |
| 47 | + |
| 48 | + @app.shortcut("do-something") |
| 49 | + async def shortcut_handler(ack): |
| 50 | + await ack() |
| 51 | + |
| 52 | + @app.event("message") |
| 53 | + async def handle_message_events(body, logger): |
| 54 | + logger.info(body) |
| 55 | + |
| 56 | + async def just_ack(ack): |
| 57 | + await ack() |
| 58 | + |
| 59 | + async def lazy_func(body): |
| 60 | + assert body.get("command") == "/hello-socket-mode" |
| 61 | + result["lazy_called"] = True |
| 62 | + |
| 63 | + app.command("/hello-socket-mode")(ack=just_ack, lazy=[lazy_func]) |
| 64 | + |
| 65 | + handler = AsyncSocketModeHandler( |
| 66 | + app_token="xapp-A111-222-xyz", |
| 67 | + app=app, |
| 68 | + ) |
| 69 | + try: |
| 70 | + handler.client.wss_uri = "ws://localhost:3021/link" |
| 71 | + |
| 72 | + await handler.connect_async() |
| 73 | + await asyncio.sleep(2) # wait for the message receiver |
| 74 | + await handler.client.send_message("foo") |
| 75 | + |
| 76 | + spent_time = 0 |
| 77 | + while spent_time < 5 and result["lazy_called"] is False: |
| 78 | + spent_time += 0.5 |
| 79 | + await asyncio.sleep(0.5) |
| 80 | + assert result["lazy_called"] is True |
| 81 | + |
| 82 | + finally: |
| 83 | + await handler.client.close() |
| 84 | + await stop_socket_mode_server_async(self) |
0 commit comments