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
45 changes: 44 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, _callback, _get_app, callback, hooks, html

pytest.importorskip("fastapi")

Expand Down Expand Up @@ -187,3 +187,46 @@ 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?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

The test now removes ws-out.children from GLOBAL_CALLBACK_MAP and GLOBAL_CALLBACK_LIST in a finally, like test_main_module_alias.py. With _setup_server patched to a no-op, only this test fails now, and a test that runs after it sees no leftover callback (0d0fc1d).


@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"],
},
}
try:
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"}}
finally:
# Without _setup_server, the callback stays in the global registry and
# would be added to the app of the next test.
_callback.GLOBAL_CALLBACK_MAP.pop("ws-out.children", None)
_callback.GLOBAL_CALLBACK_LIST[:] = [
spec
for spec in _callback.GLOBAL_CALLBACK_LIST
if spec["output"] != "ws-out.children"
]