Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 34 additions & 1 deletion tests/backend_tests/test_fastapi_before_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
and Quart."""
import pytest

from dash import Dash, Input, Output, _get_app, hooks, html
from dash import Dash, Input, Output, _get_app, callback, hooks, html

pytest.importorskip("fastapi")

Expand Down Expand Up @@ -187,3 +187,36 @@ def broken():
):
pass
assert "hook bug" in caplog.text


def test_fabr006_websocket_callback_before_any_http_request():
# dash.callback is only copied into callback_map by _setup_server, a
# before_request hook, so the handshake must run it too (gh-4082).
from starlette.testclient import TestClient

app = Dash(__name__, backend="fastapi")
app.layout = html.Div([html.Button(id="ws-btn"), html.Div(id="ws-out")])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this test ever regresses, _setup_server() never runs, so ws-out.children stays in _callback.GLOBAL_CALLBACK_MAP and gets pulled into whatever app the next test builds. Can you pop it in a finally (or a small fixture), like tests/unit/test_main_module_alias.py does, so one failure doesn't cascade?


@callback(Output("ws-out", "children"), Input("ws-btn", "n_clicks"), websocket=True)
def echo(n_clicks):
return f"ws {n_clicks}"

request = {
"type": "callback_request",
"requestId": "1",
"rendererId": "r",
"payload": {
"output": "ws-out.children",
"outputs": {"id": "ws-out", "property": "children"},
"inputs": [{"id": "ws-btn", "property": "n_clicks", "value": 1}],
"changedPropIds": ["ws-btn.n_clicks"],
},
}
with TestClient(app.server) as client:
with client.websocket_connect(
"/_dash-ws-callback", headers={"origin": "http://testserver"}
) as ws:
ws.send_json(request)
payload = ws.receive_json()["payload"]
assert payload["status"] == "ok"
assert payload["data"]["response"] == {"ws-out": {"children": "ws 1"}}