Testing a Slack Bolt App with pytest: What Worked, What Did Not
Three layers that tested a Bolt for Python app on 17 November 2026: pure functions, listeners called with fakes, and signed requests through app.dispatch against a local mock Web API, plus one live check. A subclassed WebClient and the default threading both made tests fail; here is why.
On this page
To test a Slack Bolt for Python app, split it into three layers: plain functions you test with no Slack at all, listener functions you call directly with MagicMock stand-ins for say and ack, and the whole app, where you sign a recorded payload, pass it to app.dispatch(), and point the app's WebClient at a local mock of the Slack Web API. Add one live test against a test workspace that runs only when credentials are set. We built this for a small app on 17 November 2026 with slack_bolt 1.30.0, slack_sdk 3.47.0 and pytest 9.2.0 on Python 3.13, and hit two traps on the way.
The app under test
import os
from slack_bolt import App
def deploy_reply(service: str) -> str:
service = service.strip() or "everything"
return "Deploying " + service + ". I will post here when it is live."
def handle_mention(event, say):
say(text="Deploys are green. Ask me with /sg1117 <service>.", thread_ts=event["ts"])
def handle_deploy(ack, command, client):
ack(deploy_reply(command["text"]))
client.chat_postMessage(channel=command["channel_id"], text=command["user_name"] + " started a deploy of " + command["text"])
def build_app(client=None, process_before_response=False) -> App:
app = App(
token=os.environ.get("SLACK_BOT_TOKEN"),
signing_secret=os.environ.get("SLACK_SIGNING_SECRET", "test-signing-secret"),
client=client,
token_verification_enabled=client is None,
process_before_response=process_before_response,
)
app.event("app_mention")(handle_mention)
app.command("/sg1117")(handle_deploy)
return app
Two choices make it testable. The handlers are named functions, so tests can import and call them. build_app() takes the client and process_before_response as arguments, so a test can swap both.
Fixtures from real payloads
We pointed the app's request URL at a tiny capture server, mentioned the bot and ran /sg1117 in a test workspace, and saved the two bodies Slack sent. Then we replaced the verification token, the response_url and the trigger_id with dummies. The scrubbed slash command:
{
"token": "test-verification-token",
"team_id": "T0B7JBCDKC1",
"team_domain": "slack-0yr1948",
"channel_id": "C0CJ58T774M",
"channel_name": "sg-1117-lab",
"user_id": "U0CDVBA6TMZ",
"user_name": "sgslacklab4739b4",
"command": "/sg1117",
"text": "api",
"api_app_id": "A0CK4UDJD6C",
"is_enterprise_install": "false",
"response_url": "https://hooks.slack.com/commands/T0B7JBCDKC1/0000/xxxx",
"trigger_id": "0000.1111.xxxx"
}
Real payloads catch field names you would get wrong by hand. The mention event, for example, nests the text under event.text and carries blocks with a rich_text element for the mention.
conftest.py: a mock Web API and signed headers
import hashlib
import hmac
import json
import pathlib
import threading
import time
import urllib.parse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
from slack_sdk import WebClient
FIXTURES = pathlib.Path(__file__).parent / "fixtures"
SECRET = "test-signing-secret"
class MockSlackAPI(BaseHTTPRequestHandler):
"""Answers every Web API method with ok and records the call."""
calls = []
def do_POST(self):
raw = self.rfile.read(int(self.headers.get("Content-Length", 0))).decode()
if self.headers.get("Content-Type", "").startswith("application/json"):
args = json.loads(raw or "{}")
else:
args = dict(urllib.parse.parse_qsl(raw))
method = self.path.strip("/")
if method != "auth.test":
MockSlackAPI.calls.append((method, args))
body = {"ok": True, "user_id": "U0BOT", "bot_id": "B0BOT", "team_id": "T0B7JBCDKC1", "ts": "1794879999.000100"}
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(body).encode())
def log_message(self, *args):
pass
@pytest.fixture(scope="session")
def mock_api():
server = ThreadingHTTPServer(("127.0.0.1", 0), MockSlackAPI)
threading.Thread(target=server.serve_forever, daemon=True).start()
yield "http://127.0.0.1:" + str(server.server_address[1]) + "/"
server.shutdown()
@pytest.fixture
def client(mock_api):
MockSlackAPI.calls.clear()
web = WebClient(token="xoxb-test", base_url=mock_api)
web.calls = MockSlackAPI.calls
return web
@pytest.fixture
def mention_event():
return json.loads((FIXTURES / "app_mention.json").read_text())
@pytest.fixture
def slash_command():
return json.loads((FIXTURES / "slash_command.json").read_text())
def signed_headers(body: str, secret: str = SECRET, ts: int | None = None) -> dict:
ts = str(ts or int(time.time()))
sig = "v0=" + hmac.new(secret.encode(), ("v0:" + ts + ":" + body).encode(), hashlib.sha256).hexdigest()
return {"x-slack-request-timestamp": [ts], "x-slack-signature": [sig]}
The tests
import json
import os
import time
import urllib.parse
from unittest.mock import MagicMock
import pytest
from slack_bolt.request import BoltRequest
from slack_sdk import WebClient
from app import build_app, deploy_reply, handle_deploy, handle_mention
from conftest import signed_headers
# 1. Pure logic: no Slack at all
def test_deploy_reply_names_the_service():
assert deploy_reply("api") == "Deploying api. I will post here when it is live."
assert deploy_reply(" ") == "Deploying everything. I will post here when it is live."
# 2. Listener functions called directly with fakes
def test_mention_answers_in_thread(mention_event):
say = MagicMock()
handle_mention(event=mention_event["event"], say=say)
say.assert_called_once()
assert say.call_args.kwargs["thread_ts"] == mention_event["event"]["ts"]
def test_deploy_acks_then_posts(slash_command, client):
ack = MagicMock()
handle_deploy(ack=ack, command=slash_command, client=client)
ack.assert_called_once_with("Deploying api. I will post here when it is live.")
assert client.calls[0][0] == "chat.postMessage"
# 3. The whole app: signed request in, Bolt routing, recorded API calls out
def test_signed_slash_command_through_bolt(slash_command, client):
app = build_app(client=client, process_before_response=True)
body = urllib.parse.urlencode(slash_command)
resp = app.dispatch(BoltRequest(body=body, headers=signed_headers(body)))
assert resp.status == 200
assert resp.body == "Deploying api. I will post here when it is live." # ack("...") answers text/plain
assert [c[0] for c in client.calls] == ["chat.postMessage"]
def test_signed_mention_through_bolt(mention_event, client):
app = build_app(client=client, process_before_response=True)
body = json.dumps(mention_event)
resp = app.dispatch(BoltRequest(body=body, headers=signed_headers(body)))
assert resp.status == 200
method, args = client.calls[0]
assert method == "chat.postMessage"
assert args["thread_ts"] == mention_event["event"]["ts"]
def test_bad_signature_is_rejected(slash_command, client):
app = build_app(client=client, process_before_response=True)
body = urllib.parse.urlencode(slash_command)
resp = app.dispatch(BoltRequest(body=body, headers=signed_headers(body, secret="wrong")))
assert resp.status == 401
assert client.calls == []
def test_old_timestamp_is_rejected(slash_command, client):
app = build_app(client=client, process_before_response=True)
body = urllib.parse.urlencode(slash_command)
resp = app.dispatch(BoltRequest(body=body, headers=signed_headers(body, ts=int(time.time()) - 600)))
assert resp.status == 401
# 4. One end-to-end check against a real workspace, skipped without credentials
@pytest.mark.skipif(not os.environ.get("SLACK_E2E_CHANNEL"), reason="no test workspace")
def test_bot_can_post_and_read_back():
web = WebClient(token=os.environ["SLACK_BOT_TOKEN"])
channel = os.environ["SLACK_E2E_CHANNEL"]
marker = "e2e-" + str(int(time.time()))
posted = web.chat_postMessage(channel=channel, text=marker)
try:
history = web.conversations_history(channel=channel, oldest=posted["ts"], inclusive=True, limit=1)
assert history["messages"][0]["text"] == marker
finally:
web.chat_delete(channel=channel, ts=posted["ts"])
The run with SLACK_BOT_TOKEN and SLACK_E2E_CHANNEL set:
test_app.py::test_deploy_reply_names_the_service PASSED [ 12%]
test_app.py::test_mention_answers_in_thread PASSED [ 25%]
test_app.py::test_deploy_acks_then_posts PASSED [ 37%]
test_app.py::test_signed_slash_command_through_bolt PASSED [ 50%]
test_app.py::test_signed_mention_through_bolt PASSED [ 62%]
test_app.py::test_bad_signature_is_rejected PASSED [ 75%]
test_app.py::test_old_timestamp_is_rejected PASSED [ 87%]
test_app.py::test_bot_can_post_and_read_back PASSED [100%]
============================== 8 passed in 0.70s ===============================
Without the variables the last test reports SKIPPED (no test workspace). With them it posts a marker message, reads it back with conversations.history, and deletes it in finally, so the test channel stays clean.
Never appear "away" on Slack again
Cloud-based. No downloads. Works 24/7 even when your laptop is off.
Trap 1: a subclassed WebClient is never used
Our first attempt subclassed WebClient and overrode api_call() to record calls, then passed it as client=. Calling listeners directly worked. Through app.dispatch() it did not:
ERROR slack_bolt.SingleTeamAuthorization:single_team_authorization.py:85 Failed to authorize with the given token (The request to the Slack API failed. (url: https://slack.com/api/auth.test)
The server responded with: {'ok': False, 'error': 'invalid_auth'})
FAILED test_fakeclient.py::test_subclassed_client_through_dispatch - AssertionError: assert [] == ['chat.postMessage']
Since version 1.15, Bolt builds a new WebClient for every request in App._init_context() (a comment there explains why), copying settings such as the base URL from your client. Your subclass and its override are dropped, and the real auth.test goes to slack.com with a fake token. The fix is the mock server in conftest.py: a plain WebClient(base_url=...) pointing at it, which the per-request copy keeps. The mock also answers auth.test with ok, which the app's authorization step calls before the first listener runs.
Trap 2: the listener has not run yet
With the default process_before_response=False, Bolt acknowledges the event first and runs the listener in a background thread. A test that dispatches and then checks the recorded calls races that thread:
> assert client.calls, "listener has not run yet"
E AssertionError: listener has not run yet
E assert []
FAILED test_race.py::test_mention_without_process_before_response - Assertion...
Building the app with process_before_response=True in tests runs the listener before dispatch() returns, and the same assertions pass every time. Keep the default in production for Socket Mode and long-running servers; set it to True on FaaS platforms such as AWS Lambda, where work after the response may be cut off.
What each layer catches
| Layer | Speed | Catches | Misses |
|---|---|---|---|
| Pure functions | Instant | Text, parsing, business rules | Everything Slack-shaped |
| Listeners with fakes | Instant | Wrong say/ack arguments, missing thread_ts | Routing, signatures, payload shape changes |
Signed dispatch with mock API | Under 0.1 s per test | Routing, signature and timestamp checks, real payload fields, which API methods run | Scopes, rate limits, how Slack renders the message |
| Live test workspace | About 1 s | Scopes, channel membership, real errors | Runs only where credentials exist |
The whole suite above took 0.70 to 0.76 s. For the request signing details see our signing secret test, and for what a failing listener shows users see Bolt error handling. If your app reads users or channels, a recorded users.list or conversations.list response makes a good second fixture for the mock server.
FAQ
Why does pytest warn that token will be unused?
With SLACK_BOT_TOKEN set, build_app() passes both a token and a client, and Bolt logged As you gave client as well, token will be unused. The test client's token wins, which is what you want in tests.
Can I test with Socket Mode? The listener and dispatch layers do not care how requests arrive. Only the live test needs a running app, and it can call the Web API directly as ours does.
Stop Jiggling Your Mouse.
Join hundreds of remote workers who never worry about their Slack status. Set it up once, stay green forever.
Related Articles
Slack Bolt Middleware: Global and Listener, Tested
Global middleware runs for every request and listener middleware for one listener. We ran both in Bolt for Python and Bolt for JavaScript on 20 November 2026 and logged what Slack did when next() was skipped: Python answered 404 and Slack sent the event again.
Slack Bolt with Express: ExpressReceiver and customRoutes, Tested
Two ways to serve your own HTTP routes next to a Bolt JS app: ExpressReceiver with receiver.router, or customRoutes on the built-in receiver. We ran both with Bolt 5.1.0 and Express 5.3.0 on 17 November 2026, plus the body-parser mistake that makes every slash command fail.
Slack Bolt Error Handling: What Users See for Each Failure, Tested
We made Bolt for Python listeners raise, skip ack() and miss an action, then recorded what Bolt logged, what the user saw in Slack and how @app.error changes it. One case is a race: ack() followed at once by an exception still shows the user a failure.