def test_success_global_2(self): app = App(client=self.web_client, signing_secret=self.signing_secret,) app.global_shortcut("test-shortcut")(simple_listener) request = self.build_valid_request(global_shortcut_raw_body) response = app.dispatch(request) assert response.status == 200 assert self.mock_received_requests["/auth.test"] == 1 request = self.build_valid_request(message_shortcut_raw_body) response = app.dispatch(request) assert response.status == 404 assert self.mock_received_requests["/auth.test"] == 1
def test_oauth(self): app = App( client=self.web_client, signing_secret=self.signing_secret, oauth_settings=OAuthSettings( client_id="111.111", client_secret="xxx", scopes=["chat:write", "commands"], ), ) flask_app = Flask(__name__) @flask_app.route("/slack/install", methods=["GET"]) def endpoint(): return SlackRequestHandler(app).handle(request) with flask_app.test_client() as client: rv = client.get("/slack/install") assert rv.status_code == 200
def test_oauth(self): app = App( client=self.web_client, signing_secret=self.signing_secret, oauth_settings=OAuthSettings( client_id="111.111", client_secret="xxx", scopes=["chat:write", "commands"], ), ) event = { "body": "", "queryStringParameters": {}, "headers": {}, "requestContext": { "http": { "method": "GET" } }, "isBase64Encoded": False, } response = SlackRequestHandler(app).handle(event, self.context) assert response["statusCode"] == 200 assert response["headers"][ "content-type"] == "text/html; charset=utf-8" assert response.get("body") is not None event = { "body": "", "queryStringParameters": {}, "headers": {}, "requestContext": { "httpMethod": "GET" }, "isBase64Encoded": False, } response = SlackRequestHandler(app).handle(event, self.context) assert response["statusCode"] == 200 assert response["headers"][ "content-type"] == "text/html; charset=utf-8" assert "https://slack.com/oauth/v2/authorize?state=" in response.get( "body")
def test_failure(self): app = App( client=self.web_client, signing_secret=self.signing_secret, ) request = self.build_valid_request() response = app.dispatch(request) assert response.status == 404 assert self.mock_received_requests["/auth.test"] == 1 app.command("/another-one")(commander) response = app.dispatch(request) assert response.status == 404 assert self.mock_received_requests["/auth.test"] == 2
def test_cancellation_failure(self): app = App( client=self.web_client, signing_secret=self.signing_secret, ) request = self.build_valid_request(suggestion_raw_body) response = app.dispatch(request) assert response.status == 404 assert self.mock_received_requests["/auth.test"] == 1 app.dialog_cancellation("dialog-callback-iddddd")(handle_cancellation) response = app.dispatch(request) assert response.status == 404 assert self.mock_received_requests["/auth.test"] == 2
def test_failure_multi(self): app = App( client=self.web_client, signing_secret=self.signing_secret, ) request = self.build_valid_multi_request() response = app.dispatch(request) assert response.status == 404 assert self.mock_received_requests["/auth.test"] == 1 app.options("es_a")(show_options) response = app.dispatch(request) assert response.status == 404 assert self.mock_received_requests["/auth.test"] == 2
def test_cancellation_failure_without_type(self): app = App( client=self.web_client, signing_secret=self.signing_secret, ) request = self.build_valid_request(suggestion_raw_body) response = app.dispatch(request) assert response.status == 404 assert_auth_test_count(self, 1) app.action("dialog-callback-iddddd")(handle_cancellation) response = app.dispatch(request) assert response.status == 404 assert_auth_test_count(self, 1)
def test_failure(self): app = App( client=self.web_client, signing_secret=self.signing_secret, ) request = self.build_valid_request() response = app.dispatch(request) assert response.status == 404 assert self.mock_received_requests["/auth.test"] == 1 app.view("view-idddd")(simple_listener) response = app.dispatch(request) assert response.status == 404 assert self.mock_received_requests["/auth.test"] == 2
def test_failure(self): app = App( client=self.web_client, signing_secret=self.signing_secret, ) request = self.build_valid_request() response = app.dispatch(request) assert response.status == 404 assert_auth_test_count(self, 1) app.command("/another-one")(commander) response = app.dispatch(request) assert response.status == 404 assert_auth_test_count(self, 1)
def test_failure_2(self): app = App( client=self.web_client, signing_secret=self.signing_secret, ) request = self.build_valid_request() response = app.dispatch(request) assert response.status == 404 assert self.mock_received_requests["/auth.test"] == 1 app.attachment_action("unknown")(simple_listener) response = app.dispatch(request) assert response.status == 404 assert self.mock_received_requests["/auth.test"] == 1
def test_failure(self): app = App( client=self.web_client, signing_secret=self.signing_secret, ) request = self.build_valid_request(global_shortcut_raw_body) response = app.dispatch(request) assert response.status == 404 assert_auth_test_count(self, 1) app.shortcut("another-one")(simple_listener) response = app.dispatch(request) assert response.status == 404 assert_auth_test_count(self, 1)
def test_failure_multi(self): app = App( client=self.web_client, signing_secret=self.signing_secret, ) request = self.build_valid_multi_request() response = app.dispatch(request) assert response.status == 404 assert_auth_test_count(self, 1) app.options("es_a")(show_options) response = app.dispatch(request) assert response.status == 404 assert_auth_test_count(self, 1)
def test_failure(self): app = App( client=self.web_client, signing_secret=self.signing_secret, ) request = self.build_valid_request(global_shortcut_raw_body) response = app.dispatch(request) assert response.status == 404 assert self.mock_received_requests["/auth.test"] == 1 app.shortcut("another-one")(simple_listener) response = app.dispatch(request) assert response.status == 404 assert self.mock_received_requests["/auth.test"] == 1
def test_failure_2(self): app = App( client=self.web_client, signing_secret=self.signing_secret, ) request = self.build_valid_request() response = app.dispatch(request) assert response.status == 404 assert_auth_test_count(self, 1) app.block_action("aaa")(simple_listener) response = app.dispatch(request) assert response.status == 404 assert_auth_test_count(self, 1)
def test_custom(self): def error_handler(logger, payload, response): logger.info(payload) response.headers["x-test-result"] = ["1"] def failing_listener(): raise Exception("Something wrong!") app = App( client=self.web_client, signing_secret=self.signing_secret, ) app.error(error_handler) app.action("a")(failing_listener) request = self.build_valid_request() response = app.dispatch(request) assert response.status == 500 assert response.headers["x-test-result"] == ["1"]
def setup_server(cls): cls.old_os_env = remove_os_env_temporarily() setup_mock_web_api_server(cls) signing_secret = "secret" valid_token = "xoxb-valid" mock_api_server_base_url = "http://localhost:8888" web_client = WebClient( token=valid_token, base_url=mock_api_server_base_url, ) app = App( client=web_client, signing_secret=signing_secret, ) def event_handler(): pass def shortcut_handler(ack): ack() def command_handler(ack): ack() app.event("app_mention")(event_handler) app.shortcut("test-shortcut")(shortcut_handler) app.command("/hello-world")(command_handler) handler = SlackRequestHandler(app) class SlackApp(object): @cherrypy.expose @cherrypy.tools.slack_in() def events(self, **kwargs): return handler.handle() cherrypy.tree.mount(SlackApp(), "/slack")
def test_success_both_global_and_message(self): app = App( client=self.web_client, signing_secret=self.signing_secret, ) app.shortcut("test-shortcut")(simple_listener) request = self.build_valid_request(global_shortcut_raw_body) response = app.dispatch(request) assert response.status == 200 assert_auth_test_count(self, 1) request = self.build_valid_request(message_shortcut_raw_body) response = app.dispatch(request) assert response.status == 200 assert_auth_test_count(self, 1)
def test_suggestion_failure_2(self): app = App( client=self.web_client, signing_secret=self.signing_secret, ) request = self.build_valid_request(suggestion_raw_body) response = app.dispatch(request) assert response.status == 404 assert_auth_test_count(self, 1) app.options({ "type": "dialog_suggestion", "callback_id": "dialog-callback-iddddd" })(handle_suggestion) response = app.dispatch(request) assert response.status == 404 assert_auth_test_count(self, 1)
def test_submission_failure_2(self): app = App( client=self.web_client, signing_secret=self.signing_secret, ) request = self.build_valid_request(suggestion_raw_body) response = app.dispatch(request) assert response.status == 404 assert self.mock_received_requests["/auth.test"] == 1 app.action({ "type": "dialog_submission", "callback_id": "dialog-callback-iddddd" })(handle_submission) response = app.dispatch(request) assert response.status == 404 assert self.mock_received_requests["/auth.test"] == 2
def test_failure(self): app = App( client=self.web_client, signing_secret=self.signing_secret, ) request = self.build_valid_request() response = app.dispatch(request) assert response.status == 404 assert_auth_test_count(self, 1) app.view({ "type": "view_closed", "callback_id": "view-idddd" })(simple_listener) response = app.dispatch(request) assert response.status == 404 assert_auth_test_count(self, 1)
def test_failure(self): app = App( client=self.web_client, signing_secret=self.signing_secret, ) request = self.build_valid_request() response = app.dispatch(request) assert response.status == 404 assert self.mock_received_requests["/auth.test"] == 1 app.action({ "callback_id": "unknown", "type": "interactive_message", })(simple_listener) response = app.dispatch(request) assert response.status == 404 assert self.mock_received_requests["/auth.test"] == 2
def test_oauth(self): app = App( client=self.web_client, signing_secret=self.signing_secret, oauth_settings=OAuthSettings( client_id="111.111", client_secret="xxx", scopes=["chat:write", "commands"], ), ) api = FastAPI() app_handler = SlackRequestHandler(app) @api.get("/slack/install") async def endpoint(req: Request): return await app_handler.handle(req) client = TestClient(api) response = client.get("/slack/install", allow_redirects=False) assert response.status_code == 200 assert response.headers.get( "content-type") == "text/html; charset=utf-8" assert "https://slack.com/oauth/v2/authorize?state=" in response.text
def test_success_message(self): app = App( client=self.web_client, signing_secret=self.signing_secret, ) app.shortcut({"type": "message_action", "callback_id": "test-shortcut"})( simple_listener ) request = self.build_valid_request(message_shortcut_raw_body) response = app.dispatch(request) assert response.status == 200 assert_auth_test_count(self, 1) request = self.build_valid_request(global_shortcut_raw_body) response = app.dispatch(request) assert response.status == 404 assert_auth_test_count(self, 1)
import tornado from tornado.httpclient import HTTPRequest, HTTPResponse from tornado.testing import AsyncHTTPTestCase from tornado.web import Application from slack_bolt.adapter.tornado import SlackOAuthHandler from slack_bolt.app import App from slack_bolt.oauth.oauth_settings import OAuthSettings from tests.utils import remove_os_env_temporarily, restore_os_env signing_secret = "secret" app = App( signing_secret=signing_secret, oauth_settings=OAuthSettings( client_id="111.111", client_secret="xxx", scopes=["chat:write", "commands"], ), ) class TestTornado(AsyncHTTPTestCase): def get_app(self): return Application([("/slack/install", SlackOAuthHandler, dict(app=app))]) def setUp(self): AsyncHTTPTestCase.setUp(self) self.old_os_env = remove_os_env_temporarily() def tearDown(self):
def test_success_2(self): app = App( client=self.web_client, signing_secret=self.signing_secret, ) app.dialog_suggestion("dialog-callback-id")(handle_suggestion) app.dialog_submission("dialog-callback-id")(handle_submission) app.dialog_cancellation("dialog-callback-id")(handle_cancellation) request = self.build_valid_request(suggestion_raw_body) response = app.dispatch(request) assert response.status == 200 assert response.body != "" assert response.headers["content-type"][ 0] == "application/json;charset=utf-8" assert self.mock_received_requests["/auth.test"] == 1 request = self.build_valid_request(submission_raw_body) response = app.dispatch(request) assert response.status == 200 assert response.body == "" assert self.mock_received_requests["/auth.test"] == 2 request = self.build_valid_request(cancellation_raw_body) response = app.dispatch(request) assert response.status == 200 assert response.body == "" assert self.mock_received_requests["/auth.test"] == 3
import logging logging.basicConfig(level=logging.DEBUG) import os from slack_bolt.app import App from slack_bolt.context import BoltContext bot_token = os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN") app = App(signing_secret="will-be-removed-soon", token=bot_token) @app.event("app_mention") def mention(context: BoltContext): context.say(":wave: Hi there!") @app.event("message") def message(context: BoltContext, event: dict): context.client.reactions_add( channel=event["channel"], timestamp=event["ts"], name="eyes", ) @app.command("/hello-socket-mode") def hello_command(ack, body): user_id = body["user_id"] ack(f"Hi <@{user_id}>!")
class TestTornado(AsyncHTTPTestCase): signature_verifier = SignatureVerifier(signing_secret) def setUp(self): self.old_os_env = remove_os_env_temporarily() setup_mock_web_api_server(self) web_client = WebClient( token=valid_token, base_url=mock_api_server_base_url, ) self.app = App( client=web_client, signing_secret=signing_secret, ) self.app.event("app_mention")(event_handler) self.app.shortcut("test-shortcut")(shortcut_handler) self.app.command("/hello-world")(command_handler) AsyncHTTPTestCase.setUp(self) def tearDown(self): AsyncHTTPTestCase.tearDown(self) cleanup_mock_web_api_server(self) restore_os_env(self.old_os_env) def get_app(self): return Application([("/slack/events", SlackEventsHandler, dict(app=self.app))]) def generate_signature(self, body: str, timestamp: str): return self.signature_verifier.generate_signature( body=body, timestamp=timestamp, ) def build_headers(self, timestamp: str, body: str): content_type = ("application/json" if body.startswith("{") else "application/x-www-form-urlencoded") return { "content-type": content_type, "x-slack-signature": self.generate_signature(body, timestamp), "x-slack-request-timestamp": timestamp, } @gen_test async def test_events(self): input = { "token": "verification_token", "team_id": "T111", "enterprise_id": "E111", "api_app_id": "A111", "event": { "client_msg_id": "9cbd4c5b-7ddf-4ede-b479-ad21fca66d63", "type": "app_mention", "text": "<@W111> Hi there!", "user": "******", "ts": "1595926230.009600", "team": "T111", "channel": "C111", "event_ts": "1595926230.009600", }, "type": "event_callback", "event_id": "Ev111", "event_time": 1595926230, "authed_users": ["W111"], } timestamp, body = str(int(time())), json.dumps(input) request = HTTPRequest( url=self.get_url("/slack/events"), method="POST", body=body, headers=self.build_headers(timestamp, body), ) response: HTTPResponse = await self.http_client.fetch(request) assert response.code == 200 assert_auth_test_count(self, 1) @gen_test async def test_shortcuts(self): input = { "type": "shortcut", "token": "verification_token", "action_ts": "111.111", "team": { "id": "T111", "domain": "workspace-domain", "enterprise_id": "E111", "enterprise_name": "Org Name", }, "user": { "id": "W111", "username": "******", "team_id": "T111" }, "callback_id": "test-shortcut", "trigger_id": "111.111.xxxxxx", } timestamp, body = str(int( time())), f"payload={quote(json.dumps(input))}" request = HTTPRequest( url=self.get_url("/slack/events"), method="POST", body=body, headers=self.build_headers(timestamp, body), ) response: HTTPResponse = await self.http_client.fetch(request) assert response.code == 200 assert_auth_test_count(self, 1) @gen_test async def test_commands(self): input = ( "token=verification_token" "&team_id=T111" "&team_domain=test-domain" "&channel_id=C111" "&channel_name=random" "&user_id=W111" "&user_name=primary-owner" "&command=%2Fhello-world" "&text=Hi" "&enterprise_id=E111" "&enterprise_name=Org+Name" "&response_url=https%3A%2F%2Fhooks.slack.com%2Fcommands%2FT111%2F111%2Fxxxxx" "&trigger_id=111.111.xxx") timestamp, body = str(int(time())), input request = HTTPRequest( url=self.get_url("/slack/events"), method="POST", body=body, headers=self.build_headers(timestamp, body), ) response: HTTPResponse = await self.http_client.fetch(request) assert response.code == 200 assert_auth_test_count(self, 1)
# ------------------ import logging logging.basicConfig(level=logging.DEBUG) import os from slack_bolt.app import App from slack_bolt.context import BoltContext from slack_bolt.oauth.oauth_settings import OAuthSettings app = App( signing_secret=os.environ["SLACK_SIGNING_SECRET"], oauth_settings=OAuthSettings( client_id=os.environ["SLACK_CLIENT_ID"], client_secret=os.environ["SLACK_CLIENT_SECRET"], scopes=os.environ["SLACK_SCOPES"].split(","), ), ) @app.event("app_mention") def mention(context: BoltContext): context.say(":wave: Hi there!") @app.event("message") def message(context: BoltContext, event: dict): context.client.reactions_add( channel=event["channel"], timestamp=event["ts"],
import logging logging.basicConfig(level=logging.DEBUG) import os from slack_bolt.app import App from slack_bolt.oauth.oauth_settings import OAuthSettings from slack_bolt.adapter.socket_mode import SocketModeHandler app = App( signing_secret=os.environ["SLACK_SIGNING_SECRET"], oauth_settings=OAuthSettings( client_id=os.environ["SLACK_CLIENT_ID"], client_secret=os.environ["SLACK_CLIENT_SECRET"], scopes=os.environ["SLACK_SCOPES"].split(","), ), ) @app.command("/hello-socket-mode") def hello_command(ack, body): user_id = body["user_id"] ack(f"Hi <@{user_id}>!") @app.event("app_mention") def event_test(event, say): say(f"Hi there, <@{event['user']}>!") def ack_shortcut(ack):
def run_bolt_app(app: App, req: SocketModeRequest): # type: ignore bolt_req: BoltRequest = BoltRequest(mode="socket_mode", body=req.payload) bolt_resp: BoltResponse = app.dispatch(bolt_req) return bolt_resp