|
| 1 | + |
| 2 | +from dash import ( |
| 3 | + Dash, |
| 4 | + Input, |
| 5 | + Output, |
| 6 | + html, |
| 7 | + ctx, |
| 8 | +) |
| 9 | +import requests |
| 10 | +import json |
| 11 | +from flask import jsonify |
| 12 | + |
| 13 | +test_string = ('{"step_0": "Data fetched - 1", "step_1": "Data fetched - 1", "step_2": "Data fetched - 1", ' |
| 14 | + '"step_3": "Data fetched - 1", "step_4": "Data fetched - 1"}') |
| 15 | + |
| 16 | +def test_apib001_api_callback(dash_duo): |
| 17 | + |
| 18 | + app = Dash(__name__) |
| 19 | + app.layout = html.Div([ |
| 20 | + html.Button("Slow Callback", id="slow-btn"), |
| 21 | + html.Div(id="slow-output"), |
| 22 | + ]) |
| 23 | + |
| 24 | + def get_data(n_clicks): |
| 25 | + # Simulate an async data fetch |
| 26 | + return f"Data fetched - {n_clicks}" |
| 27 | + |
| 28 | + @app.callback( |
| 29 | + Output("slow-output", "children"), |
| 30 | + Input("slow-btn", "n_clicks"), |
| 31 | + prevent_initial_call=True, |
| 32 | + api_endpoint='/api/slow_callback', # Example API path for the slow callback |
| 33 | + ) |
| 34 | + def slow_callback(n_clicks): |
| 35 | + data = {} |
| 36 | + for i in range(5): |
| 37 | + data[f'step_{i}'] = get_data(n_clicks) |
| 38 | + ret = f"{json.dumps(data)}" |
| 39 | + if ctx: |
| 40 | + return ret |
| 41 | + return jsonify(ret) |
| 42 | + |
| 43 | + app.setup_apis() |
| 44 | + |
| 45 | + dash_duo.start_server(app) |
| 46 | + |
| 47 | + dash_duo.wait_for_element("#slow-btn").click() |
| 48 | + dash_duo.wait_for_text_to_equal("#slow-output", test_string) |
| 49 | + r = requests.post(dash_duo.server_url +'/api/slow_callback', |
| 50 | + json={'n_clicks': 1}, |
| 51 | + headers={'Content-Type': 'application/json'}) |
| 52 | + assert r.status_code == 200 |
| 53 | + assert r.json() == test_string |
0 commit comments