-
Notifications
You must be signed in to change notification settings - Fork 1
Replace private psycopg2/Bolt API usage with public interfaces for he… #83
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| """Slack Bolt HTTP server using public ``App.dispatch()`` only. | ||
|
|
||
| Mirrors slack-bolt's built-in development server without accessing private | ||
| ``_development_server`` internals. Requires slack-bolt >= 1.28.0 | ||
| (``App.dispatch``, ``BoltRequest``, ``BoltResponse``). | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| import logging | ||
| from collections.abc import Sequence | ||
| from http.server import BaseHTTPRequestHandler, HTTPServer | ||
| from typing import Any | ||
|
|
||
| from slack_bolt import App | ||
| from slack_bolt.request import BoltRequest | ||
| from slack_bolt.response import BoltResponse | ||
|
|
||
|
|
||
| def create_bolt_http_server( | ||
| app: App, | ||
| port: int, | ||
| path: str = "/slack/events", | ||
| bind_host: str = "0.0.0.0", | ||
| ) -> HTTPServer: | ||
| """Create an ``HTTPServer`` that dispatches Slack events via ``app.dispatch()``.""" | ||
| bolt_path = path | ||
| bolt_app = app | ||
|
|
||
| class _BoltHandler(BaseHTTPRequestHandler): | ||
| def log_message(self, format: str, *args: Any) -> None: | ||
| if bolt_app.logger.isEnabledFor(logging.DEBUG): | ||
| bolt_app.logger.debug("bolt: %s", format % args) | ||
|
|
||
| def do_POST(self) -> None: | ||
| request_path, _, query = self.path.partition("?") | ||
| if request_path != bolt_path: | ||
| self._send_response(404, headers={}) | ||
| return | ||
|
|
||
| len_header = self.headers.get("Content-Length") or 0 | ||
| request_body = self.rfile.read(int(len_header)).decode("utf-8") | ||
| bolt_req = BoltRequest( | ||
| body=request_body, | ||
| query=query, | ||
| headers=self.headers, | ||
| ) | ||
| bolt_resp = bolt_app.dispatch(bolt_req) | ||
| self._send_bolt_response(bolt_resp) | ||
|
|
||
| def do_GET(self) -> None: | ||
| self._send_response(404, headers={}) | ||
|
|
||
| def _send_bolt_response(self, bolt_resp: BoltResponse) -> None: | ||
| self._send_response( | ||
| status=bolt_resp.status, | ||
| headers=bolt_resp.headers, | ||
| body=bolt_resp.body, | ||
| ) | ||
|
|
||
| def _send_response( | ||
| self, | ||
| status: int, | ||
| headers: dict[str, Sequence[str]], | ||
| body: str | dict = "", | ||
| ) -> None: | ||
| self.send_response(status) | ||
| response_body = body if isinstance(body, str) else json.dumps(body) | ||
| body_bytes = response_body.encode("utf-8") | ||
| for key, values in headers.items(): | ||
| for value in values: | ||
| self.send_header(key, value) | ||
| self.send_header("Content-Length", str(len(body_bytes))) | ||
| self.end_headers() | ||
| self.wfile.write(body_bytes) | ||
|
|
||
| return HTTPServer((bind_host, port), _BoltHandler) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| """Tests for paperscout.bolt_server.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| import socket | ||
| import threading | ||
| import urllib.error | ||
| import urllib.request | ||
| from unittest.mock import MagicMock | ||
|
|
||
| import pytest | ||
| from slack_bolt.response import BoltResponse | ||
|
|
||
| from paperscout.bolt_server import create_bolt_http_server | ||
|
|
||
|
|
||
| def _find_free_port() -> int: | ||
| with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: | ||
| s.bind(("127.0.0.1", 0)) | ||
| return s.getsockname()[1] | ||
|
|
||
|
|
||
| @pytest.fixture() | ||
| def bolt_server_url(): | ||
| app = MagicMock() | ||
| app.logger.isEnabledFor.return_value = False | ||
| app.dispatch.return_value = BoltResponse( | ||
| status=200, | ||
| body="ok", | ||
| headers={"Content-Type": ["text/plain"]}, | ||
| ) | ||
| port = _find_free_port() | ||
| server = create_bolt_http_server(app, port, bind_host="127.0.0.1") | ||
| thread = threading.Thread( | ||
| target=server.serve_forever, | ||
| kwargs={"poll_interval": 0.05}, | ||
| daemon=True, | ||
| ) | ||
| thread.start() | ||
| yield f"http://127.0.0.1:{port}", app | ||
| server.shutdown() | ||
| server.server_close() | ||
| thread.join() | ||
| assert not thread.is_alive() | ||
|
|
||
|
|
||
| class TestBoltHttpServer: | ||
| def test_post_slack_events_dispatches_to_app(self, bolt_server_url): | ||
| base_url, app = bolt_server_url | ||
| req = urllib.request.Request( | ||
| f"{base_url}/slack/events", | ||
| data=b'{"type":"url_verification"}', | ||
| method="POST", | ||
| headers={"Content-Type": "application/json"}, | ||
| ) | ||
| resp = urllib.request.urlopen(req) | ||
| assert resp.status == 200 | ||
| assert resp.read() == b"ok" | ||
| app.dispatch.assert_called_once() | ||
| bolt_req = app.dispatch.call_args[0][0] | ||
| assert bolt_req.body == {"type": "url_verification"} | ||
|
|
||
| def test_wrong_path_returns_404(self, bolt_server_url): | ||
| base_url, app = bolt_server_url | ||
| req = urllib.request.Request( | ||
| f"{base_url}/wrong", | ||
| data=b"{}", | ||
| method="POST", | ||
| headers={"Content-Type": "application/json"}, | ||
| ) | ||
| with pytest.raises(urllib.error.HTTPError) as exc_info: | ||
| urllib.request.urlopen(req) | ||
| assert exc_info.value.code == 404 | ||
| app.dispatch.assert_not_called() | ||
|
|
||
| def test_get_returns_404(self, bolt_server_url): | ||
| base_url, app = bolt_server_url | ||
| with pytest.raises(urllib.error.HTTPError) as exc_info: | ||
| urllib.request.urlopen(f"{base_url}/slack/events") | ||
| assert exc_info.value.code == 404 | ||
| app.dispatch.assert_not_called() | ||
|
|
||
| def test_dispatch_json_body_response(self, bolt_server_url): | ||
| base_url, app = bolt_server_url | ||
| app.dispatch.return_value = BoltResponse( | ||
| status=200, | ||
| body={"challenge": "abc"}, | ||
| headers={}, | ||
| ) | ||
| req = urllib.request.Request( | ||
| f"{base_url}/slack/events", | ||
| data=b"{}", | ||
| method="POST", | ||
| ) | ||
| resp = urllib.request.urlopen(req) | ||
| assert json.loads(resp.read()) == {"challenge": "abc"} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.