|
| 1 | +import json |
| 2 | +from concurrent.futures import Executor, Future |
| 3 | +from typing import Any, Callable, Dict, List, Optional, Sequence |
| 4 | + |
| 5 | +from slack_bolt.app import App |
| 6 | +from slack_bolt.request import BoltRequest |
| 7 | +from slack_bolt.response import BoltResponse |
| 8 | + |
| 9 | +from . import payloads |
| 10 | +from .mock_slack_server import APICall, MockSlackServer |
| 11 | + |
| 12 | + |
| 13 | +class InlineExecutor(Executor): |
| 14 | + """An executor that runs each submitted function immediately in the calling thread.""" |
| 15 | + |
| 16 | + def submit(self, fn: Callable[..., Any], *args: Any, **kwargs: Any) -> Future: # type: ignore[override] |
| 17 | + future: Future = Future() |
| 18 | + try: |
| 19 | + future.set_result(fn(*args, **kwargs)) |
| 20 | + except BaseException as e: |
| 21 | + future.set_exception(e) |
| 22 | + return future |
| 23 | + |
| 24 | + |
| 25 | +class DispatchResult: |
| 26 | + """The outcome of dispatching one request to a Bolt app in a test.""" |
| 27 | + |
| 28 | + response: Optional[BoltResponse] |
| 29 | + """The HTTP response the app returned to Slack, or None if no listener acknowledged the request.""" |
| 30 | + api_calls: List[APICall] |
| 31 | + """The Web API calls the app made while handling this request.""" |
| 32 | + responds: List[Dict[str, Any]] |
| 33 | + """The messages the app posted to the request's `response_url` (e.g. with `respond()`).""" |
| 34 | + |
| 35 | + def __init__( |
| 36 | + self, |
| 37 | + *, |
| 38 | + response: Optional[BoltResponse], |
| 39 | + api_calls: List[APICall], |
| 40 | + responds: List[Dict[str, Any]], |
| 41 | + ): |
| 42 | + self.response = response |
| 43 | + self.api_calls = api_calls |
| 44 | + self.responds = responds |
| 45 | + |
| 46 | + @property |
| 47 | + def status(self) -> Optional[int]: |
| 48 | + """The HTTP status of the response, or None if no listener acknowledged the request.""" |
| 49 | + return self.response.status if self.response is not None else None |
| 50 | + |
| 51 | + @property |
| 52 | + def body(self) -> str: |
| 53 | + """The raw response body, e.g. the text passed to `ack()`.""" |
| 54 | + return self.response.body if self.response is not None else "" |
| 55 | + |
| 56 | + @property |
| 57 | + def json(self) -> Optional[Dict[str, Any]]: |
| 58 | + """The response body parsed as JSON, or None if it is empty or not JSON.""" |
| 59 | + try: |
| 60 | + parsed = json.loads(self.body) |
| 61 | + except ValueError: |
| 62 | + return None |
| 63 | + return parsed if isinstance(parsed, dict) else None |
| 64 | + |
| 65 | + def calls_to(self, method: str) -> List[APICall]: |
| 66 | + """The Web API calls made for the given method while handling this request.""" |
| 67 | + return [c for c in self.api_calls if c.method == method] |
| 68 | + |
| 69 | + def __repr__(self) -> str: |
| 70 | + return f"DispatchResult(status={self.status!r}, body={self.body!r}, api_calls={self.api_calls!r})" |
| 71 | + |
| 72 | + |
| 73 | +class _BaseTestClient: |
| 74 | + server: MockSlackServer |
| 75 | + signing_secret: str |
| 76 | + |
| 77 | + def _prepare(self, payload: Dict[str, Any], headers: Optional[Dict[str, str]]): |
| 78 | + body = payloads.to_http_body(payload) |
| 79 | + request_headers = payloads.signed_headers(body, self.signing_secret) |
| 80 | + request_headers.update(headers or {}) |
| 81 | + return body, request_headers |
| 82 | + |
| 83 | + def _with_response_url(self, kwargs: Dict[str, Any], key: str = "response_url") -> Dict[str, Any]: |
| 84 | + kwargs.setdefault(key, self.server.response_url()) |
| 85 | + return kwargs |
| 86 | + |
| 87 | + |
| 88 | +class BoltTestClient(_BaseTestClient): |
| 89 | + """Sends signed requests to a Bolt `App` in tests and reports what the app did. |
| 90 | +
|
| 91 | + server = MockSlackServer().start() |
| 92 | + app = App(client=server.web_client("xoxb-test"), signing_secret="secret") |
| 93 | +
|
| 94 | + @app.command("/hello") |
| 95 | + def hello(ack, respond): |
| 96 | + ack() |
| 97 | + respond("Hi!") |
| 98 | +
|
| 99 | + result = BoltTestClient(app, server).slash_command("/hello") |
| 100 | + assert result.status == 200 |
| 101 | + assert result.responds == [{"text": "Hi!"}] |
| 102 | +
|
| 103 | + Requests run through the app's full middleware chain, including request verification |
| 104 | + and authorization. The test client points the app's Web API client at `server`, and runs |
| 105 | + listeners and lazy listeners in the calling thread, so all of their side effects are done |
| 106 | + when a call returns, even when `process_before_response` is False. |
| 107 | + """ |
| 108 | + |
| 109 | + def __init__(self, app: App, server: MockSlackServer): |
| 110 | + self.app = app |
| 111 | + self.server = server |
| 112 | + self.signing_secret = app._signing_secret |
| 113 | + app.client.base_url = server.base_url |
| 114 | + executor = InlineExecutor() |
| 115 | + app.listener_runner.listener_executor = executor |
| 116 | + app.listener_runner.lazy_listener_runner.executor = executor # type: ignore[attr-defined] |
| 117 | + |
| 118 | + def dispatch(self, payload: Dict[str, Any], *, headers: Optional[Dict[str, str]] = None) -> DispatchResult: |
| 119 | + """Dispatches a payload (e.g. built with `slack_bolt.testing.payloads`) to the app.""" |
| 120 | + body, request_headers = self._prepare(payload, headers) |
| 121 | + calls_before = len(self.server.calls) |
| 122 | + responds_before = len(self.server.responds) |
| 123 | + response = self.app.dispatch(BoltRequest(body=body, headers=request_headers)) |
| 124 | + return DispatchResult( |
| 125 | + response=response, |
| 126 | + api_calls=self.server.calls[calls_before:], |
| 127 | + responds=self.server.responds[responds_before:], |
| 128 | + ) |
| 129 | + |
| 130 | + def event(self, event: Dict[str, Any], **kwargs: Any) -> DispatchResult: |
| 131 | + """Sends an Events API request with the given event, e.g. `{"type": "app_mention", ...}`.""" |
| 132 | + return self.dispatch(payloads.event(event, **kwargs)) |
| 133 | + |
| 134 | + def message(self, text: str, **kwargs: Any) -> DispatchResult: |
| 135 | + """Sends a `message` event.""" |
| 136 | + return self.dispatch(payloads.message(text, **kwargs)) |
| 137 | + |
| 138 | + def slash_command(self, command: str, text: str = "", **kwargs: Any) -> DispatchResult: |
| 139 | + """Sends a slash command. `respond()` calls are recorded in the result.""" |
| 140 | + return self.dispatch(payloads.slash_command(command, text, **self._with_response_url(kwargs))) |
| 141 | + |
| 142 | + def block_action(self, action_id: str, **kwargs: Any) -> DispatchResult: |
| 143 | + """Sends a `block_actions` request. `respond()` calls are recorded in the result.""" |
| 144 | + return self.dispatch(payloads.block_action(action_id, **self._with_response_url(kwargs))) |
| 145 | + |
| 146 | + def shortcut(self, callback_id: str, **kwargs: Any) -> DispatchResult: |
| 147 | + """Sends a global shortcut.""" |
| 148 | + return self.dispatch(payloads.shortcut(callback_id, **kwargs)) |
| 149 | + |
| 150 | + def message_shortcut(self, callback_id: str, **kwargs: Any) -> DispatchResult: |
| 151 | + """Sends a message shortcut. `respond()` calls are recorded in the result.""" |
| 152 | + return self.dispatch(payloads.message_shortcut(callback_id, **self._with_response_url(kwargs))) |
| 153 | + |
| 154 | + def view_submission( |
| 155 | + self, |
| 156 | + callback_id: str, |
| 157 | + values: Optional[Dict[str, Dict[str, Any]]] = None, |
| 158 | + **kwargs: Any, |
| 159 | + ) -> DispatchResult: |
| 160 | + """Sends a `view_submission` request for a modal.""" |
| 161 | + return self.dispatch(payloads.view_submission(callback_id, values, **kwargs)) |
| 162 | + |
| 163 | + |
| 164 | +__all__: Sequence[str] = ["BoltTestClient", "DispatchResult", "InlineExecutor"] |
0 commit comments