Hi everyone,
I am trying to implement tests for Dash callbacks. I am using flexible callback signature, so that I have grouped inputs to callback function. Something like code snippet below:
@callback(
Output("container", "children"),
inputs={
"all_inputs": {
"btn1": Input("btn-1", "n_clicks"),
"btn2": Input("btn-2", "n_clicks"),
"btn3": Input("btn-3", "n_clicks")
}
},
)
def display(all_inputs):
c = ctx.args_grouping.all_inputs
if c.btn1.triggered:
return f"Button 1 clicked {c.btn1.value} times"
elif c.btn2.triggered:
return f"Button 2 clicked {c.btn2.value} times"
elif c.btn3.triggered:
return f"Button 3 clicked {c.btn3.value} times"
I would tried to mock/patch callback context as in example on Plotly webpage, but it didnt work:
from contextvars import copy_context
from dash._callback_context import context_value
from dash._utils import AttributeDict
# Import the names of callback functions you want to test
from app import display, update
def test_update_callback():
output = update(1, 0)
assert output == 'button 1: 1 & button 2: 0'
def test_display_callback():
def run_callback():
context_value.set(AttributeDict(**{"triggered_inputs": [{"prop_id": "btn-1-ctx-example.n_clicks"}]}))
return display(1, 0, 0)
ctx = copy_context()
output = ctx.run(run_callback)
assert output == f'You last clicked button with ID btn-1-ctx-example'
I was getting error saying that “all_inputs are not list element…”.
Do you have experience with writing unittests for callbacks with flexible signatures?
Best,
Milan