-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathtest_wildcards.py
More file actions
792 lines (662 loc) · 26.7 KB
/
test_wildcards.py
File metadata and controls
792 lines (662 loc) · 26.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
import pytest
import re
import threading
from selenium.webdriver.common.keys import Keys
import json
from multiprocessing import Lock
from dash.testing import wait
import dash
from dash import Dash, Input, Output, State, ALL, ALLSMALLER, MATCH, html, dcc, Patch
from tests.assets.todo_app import todo_app
from tests.assets.grouping_app import grouping_app
def stringify_id(id_):
if isinstance(id_, dict):
return json.dumps(id_, sort_keys=True, separators=(",", ":"))
return id_
def css_escape(s):
sel = re.sub("[\\{\\}\\\"\\'.:,]", lambda m: "\\" + m.group(0), s)
print(sel)
return sel
@pytest.mark.parametrize("content_callback", (False, True))
def test_cbwc001_todo_app(content_callback, dash_duo):
app = todo_app(content_callback)
dash_duo.start_server(app)
dash_duo.wait_for_text_to_equal("#totals", "0 of 0 items completed")
assert app.list_calls.value == 1
assert app.style_calls.value == 0
assert app.preceding_calls.value == 0
assert app.total_calls.value == 1
new_item = dash_duo.find_element("#new-item")
add_item = dash_duo.find_element("#add")
clear_done = dash_duo.find_element("#clear-done")
def assert_count(items):
assert len(dash_duo.find_elements("#list-container>div")) == items
def get_done_item(item):
selector = css_escape('#{"action":"done","item":%d} input' % item)
return dash_duo.find_element(selector)
def assert_item(item, text, done, prefix="", suffix=""):
dash_duo.wait_for_text_to_equal(css_escape('#{"item":%d}' % item), text)
expected_note = "" if done else (prefix + " preceding items are done" + suffix)
dash_duo.wait_for_text_to_equal(
css_escape('#{"item":%d,"preceding":true}' % item), expected_note
)
assert bool(get_done_item(item).get_attribute("checked")) == done
new_item.send_keys("apples")
add_item.click()
dash_duo.wait_for_text_to_equal("#totals", "0 of 1 items completed - 0%")
assert_count(1)
new_item.send_keys("bananas")
add_item.click()
dash_duo.wait_for_text_to_equal("#totals", "0 of 2 items completed - 0%")
assert_count(2)
new_item.send_keys("carrots")
add_item.click()
dash_duo.wait_for_text_to_equal("#totals", "0 of 3 items completed - 0%")
assert_count(3)
new_item.send_keys("dates")
add_item.click()
dash_duo.wait_for_text_to_equal("#totals", "0 of 4 items completed - 0%")
assert_count(4)
assert_item(0, "apples", False, "0 of 0", " DO THIS NEXT!")
assert_item(1, "bananas", False, "0 of 1")
assert_item(2, "carrots", False, "0 of 2")
assert_item(3, "dates", False, "0 of 3")
get_done_item(2).click()
dash_duo.wait_for_text_to_equal("#totals", "1 of 4 items completed - 25%")
assert_item(0, "apples", False, "0 of 0", " DO THIS NEXT!")
assert_item(1, "bananas", False, "0 of 1")
assert_item(2, "carrots", True)
assert_item(3, "dates", False, "1 of 3")
get_done_item(0).click()
dash_duo.wait_for_text_to_equal("#totals", "2 of 4 items completed - 50%")
assert_item(0, "apples", True)
assert_item(1, "bananas", False, "1 of 1", " DO THIS NEXT!")
assert_item(2, "carrots", True)
assert_item(3, "dates", False, "2 of 3")
clear_done.click()
dash_duo.wait_for_text_to_equal("#totals", "0 of 2 items completed - 0%")
assert_count(2)
assert_item(0, "bananas", False, "0 of 0", " DO THIS NEXT!")
assert_item(1, "dates", False, "0 of 1")
get_done_item(0).click()
dash_duo.wait_for_text_to_equal("#totals", "1 of 2 items completed - 50%")
assert_item(0, "bananas", True)
assert_item(1, "dates", False, "1 of 1", " DO THIS NEXT!")
get_done_item(1).click()
dash_duo.wait_for_text_to_equal("#totals", "2 of 2 items completed - 100%")
assert_item(0, "bananas", True)
assert_item(1, "dates", True)
clear_done.click()
# This was a tricky one - trigger based on deleted components
dash_duo.wait_for_text_to_equal("#totals", "0 of 0 items completed")
assert_count(0)
fibonacci_count = 0
fibonacci_sum_count = 0
def fibonacci_app(clientside):
global fibonacci_count
global fibonacci_sum_count
fibonacci_count = 0
fibonacci_sum_count = 0
# This app tests 2 things in particular:
# - clientside callbacks work the same as server-side
# - callbacks using ALLSMALLER as an input to MATCH of the exact same id/prop
app = Dash(__name__)
app.layout = html.Div(
[
dcc.Input(id="n", type="number", min=0, max=10, value=4),
html.Div(id="series"),
html.Div(id="sum"),
]
)
@app.callback(Output("series", "children"), Input("n", "value"))
def items(n):
return [html.Div(id={"i": i}) for i in range(n)]
if clientside:
app.clientside_callback(
"""
function(vals) {
var len = vals.length;
return len < 2 ? len : +(vals[len - 1] || 0) + +(vals[len - 2] || 0);
}
""",
Output({"i": MATCH}, "children"),
Input({"i": ALLSMALLER}, "children"),
)
app.clientside_callback(
"""
function(vals) {
var sum = vals.reduce(function(a, b) { return +a + +b; }, 0);
return vals.length + ' elements, sum: ' + sum;
}
""",
Output("sum", "children"),
Input({"i": ALL}, "children"),
)
else:
@app.callback(
Output({"i": MATCH}, "children"), Input({"i": ALLSMALLER}, "children")
)
def sequence(prev):
global fibonacci_count
fibonacci_count = fibonacci_count + 1
print(fibonacci_count)
if len(prev) < 2:
return len(prev)
return int(prev[-1] or 0) + int(prev[-2] or 0)
@app.callback(Output("sum", "children"), Input({"i": ALL}, "children"))
def show_sum(seq):
global fibonacci_sum_count
fibonacci_sum_count = fibonacci_sum_count + 1
print("fibonacci_sum_count: ", fibonacci_sum_count)
return "{} elements, sum: {}".format(
len(seq), sum(int(v or 0) for v in seq)
)
return app
@pytest.mark.parametrize("clientside", (False, True))
def test_cbwc002_fibonacci_app(clientside, dash_duo):
app = fibonacci_app(clientside)
dash_duo.start_server(app)
# app starts with 4 elements: 0, 1, 1, 2
dash_duo.wait_for_text_to_equal("#sum", "4 elements, sum: 4")
# add 5th item, "3"
dash_duo.find_element("#n").send_keys(Keys.UP)
dash_duo.wait_for_text_to_equal("#sum", "5 elements, sum: 7")
# add 6th item, "5"
dash_duo.find_element("#n").send_keys(Keys.UP)
dash_duo.wait_for_text_to_equal("#sum", "6 elements, sum: 12")
# add 7th item, "8"
dash_duo.find_element("#n").send_keys(Keys.UP)
dash_duo.wait_for_text_to_equal("#sum", "7 elements, sum: 20")
# back down all the way to no elements
dash_duo.find_element("#n").send_keys(Keys.DOWN)
dash_duo.wait_for_text_to_equal("#sum", "6 elements, sum: 12")
dash_duo.find_element("#n").send_keys(Keys.DOWN)
dash_duo.wait_for_text_to_equal("#sum", "5 elements, sum: 7")
dash_duo.find_element("#n").send_keys(Keys.DOWN)
dash_duo.wait_for_text_to_equal("#sum", "4 elements, sum: 4")
dash_duo.find_element("#n").send_keys(Keys.DOWN)
dash_duo.wait_for_text_to_equal("#sum", "3 elements, sum: 2")
dash_duo.find_element("#n").send_keys(Keys.DOWN)
dash_duo.wait_for_text_to_equal("#sum", "2 elements, sum: 1")
dash_duo.find_element("#n").send_keys(Keys.DOWN)
dash_duo.wait_for_text_to_equal("#sum", "1 elements, sum: 0")
dash_duo.find_element("#n").send_keys(Keys.DOWN)
dash_duo.wait_for_text_to_equal("#sum", "0 elements, sum: 0")
def test_cbwc003_same_keys(dash_duo):
app = Dash(__name__, suppress_callback_exceptions=True)
app.layout = html.Div(
[
html.Button("Add Filter", id="add-filter", n_clicks=0),
html.Div(id="container", children=[]),
]
)
@app.callback(
Output("container", "children"),
[Input("add-filter", "n_clicks")],
[State("container", "children")],
)
def display_dropdowns(n_clicks, children):
new_element = html.Div(
[
dcc.Dropdown(
id={"type": "dropdown", "index": n_clicks},
options=[
{"label": i, "value": i} for i in ["NYC", "MTL", "LA", "TOKYO"]
],
),
html.Div(id={"type": "output", "index": n_clicks}),
]
)
return children + [new_element]
@app.callback(
Output({"type": "output", "index": MATCH}, "children"),
[Input({"type": "dropdown", "index": MATCH}, "value")],
[State({"type": "dropdown", "index": MATCH}, "id")],
)
def display_output(value, id):
return html.Div("Dropdown {} = {}".format(id["index"], value))
dash_duo.start_server(app)
dash_duo.wait_for_text_to_equal("#add-filter", "Add Filter")
dash_duo.select_dcc_dropdown(
'#\\{\\"index\\"\\:0\\,\\"type\\"\\:\\"dropdown\\"\\}', "LA"
)
dash_duo.wait_for_text_to_equal(
'#\\{\\"index\\"\\:0\\,\\"type\\"\\:\\"output\\"\\}', "Dropdown 0 = LA"
)
dash_duo.find_element("#add-filter").click()
dash_duo.select_dcc_dropdown(
'#\\{\\"index\\"\\:1\\,\\"type\\"\\:\\"dropdown\\"\\}', "MTL"
)
dash_duo.wait_for_text_to_equal(
'#\\{\\"index\\"\\:1\\,\\"type\\"\\:\\"output\\"\\}', "Dropdown 1 = MTL"
)
dash_duo.wait_for_text_to_equal(
'#\\{\\"index\\"\\:0\\,\\"type\\"\\:\\"output\\"\\}', "Dropdown 0 = LA"
)
dash_duo.wait_for_no_elements(dash_duo.devtools_error_count_locator)
def test_cbwc004_layout_chunk_changed_props(dash_duo):
app = Dash(__name__)
app.layout = html.Div(
[
dcc.Input(id={"type": "input", "index": 1}, value="input-1"),
html.Div(id="container"),
html.Div(id="output-outer"),
html.Button("Show content", id="btn"),
]
)
@app.callback(Output("container", "children"), [Input("btn", "n_clicks")])
def display_output(n):
if n:
return html.Div(
[
dcc.Input(id={"type": "input", "index": 2}, value="input-2"),
html.Div(id="output-inner"),
]
)
else:
return "No content initially"
def trigger_info():
triggered = dash.callback_context.triggered
return "triggered is {} with prop_ids {}".format(
"Truthy" if triggered else "Falsy",
", ".join(t["prop_id"] for t in triggered),
)
@app.callback(
Output("output-inner", "children"),
[Input({"type": "input", "index": ALL}, "value")],
)
def update_dynamic_output_pattern(wc_inputs):
return trigger_info()
# When this is triggered because output-2 was rendered,
# nothing has changed
@app.callback(
Output("output-outer", "children"),
[Input({"type": "input", "index": ALL}, "value")],
)
def update_output_on_page_pattern(value):
return trigger_info()
# When this triggered on page load,
# nothing has changed
# When dcc.Input(id={'type': 'input', 'index': 2})
# is rendered (from display_output)
# then `{'type': 'input', 'index': 2}` has changed
dash_duo.start_server(app)
dash_duo.wait_for_text_to_equal("#container", "No content initially")
dash_duo.wait_for_text_to_equal(
"#output-outer", "triggered is Falsy with prop_ids ."
)
dash_duo.find_element("#btn").click()
dash_duo.wait_for_text_to_equal(
"#output-outer",
'triggered is Truthy with prop_ids {"index":2,"type":"input"}.value',
)
dash_duo.wait_for_text_to_equal(
"#output-inner", "triggered is Falsy with prop_ids ."
)
dash_duo.find_elements("input")[0].send_keys("X")
trigger_text = 'triggered is Truthy with prop_ids {"index":1,"type":"input"}.value'
dash_duo.wait_for_text_to_equal("#output-outer", trigger_text)
dash_duo.wait_for_text_to_equal("#output-inner", trigger_text)
def test_cbwc005_callbacks_count(dash_duo):
global fibonacci_count
global fibonacci_sum_count
app = fibonacci_app(False)
dash_duo.start_server(app)
wait.until(lambda: fibonacci_count == 4, 3) # initial
wait.until(lambda: fibonacci_sum_count == 2, 3) # initial + triggered
dash_duo.find_element("#n").send_keys(Keys.UP) # 5
wait.until(lambda: fibonacci_count == 9, 3)
wait.until(lambda: fibonacci_sum_count == 3, 3)
dash_duo.find_element("#n").send_keys(Keys.UP) # 6
wait.until(lambda: fibonacci_count == 15, 3)
wait.until(lambda: fibonacci_sum_count == 4, 3)
dash_duo.find_element("#n").send_keys(Keys.DOWN) # 5
wait.until(lambda: fibonacci_count == 20, 3)
wait.until(lambda: fibonacci_sum_count == 5, 3)
dash_duo.find_element("#n").send_keys(Keys.DOWN) # 4
wait.until(lambda: fibonacci_count == 24, 3)
wait.until(lambda: fibonacci_sum_count == 6, 3)
dash_duo.find_element("#n").send_keys(Keys.DOWN) # 3
wait.until(lambda: fibonacci_count == 27, 3)
wait.until(lambda: fibonacci_sum_count == 7, 3)
dash_duo.find_element("#n").send_keys(Keys.DOWN) # 2
wait.until(lambda: fibonacci_count == 29, 3)
wait.until(lambda: fibonacci_sum_count == 8, 3)
dash_duo.find_element("#n").send_keys(Keys.DOWN) # 1
wait.until(lambda: fibonacci_count == 30, 3)
wait.until(lambda: fibonacci_sum_count == 9, 3)
dash_duo.find_element("#n").send_keys(Keys.DOWN) # 0
wait.until(lambda: fibonacci_count == 30, 3)
wait.until(lambda: fibonacci_sum_count == 10, 3)
def test_cbwc006_grouping_callbacks(dash_duo):
app = grouping_app()
dash_duo.start_server(app)
dash_duo.wait_for_text_to_equal("#title", "Dash To-Do list")
new_item = dash_duo.find_element("#new-item")
add_item = dash_duo.find_element("#add")
def assert_count(items):
assert len(dash_duo.find_elements("#list-container>div")) == items
def assert_callback_context(items_text):
# Check args_grouping
args_grouping = dict(
items=dict(
all=[
{
"id": {"id": i},
"property": "children",
"value": text,
"str_id": stringify_id({"id": i}),
"triggered": False,
}
for i, text in enumerate(items_text[:-1])
],
new=dict(
id="new-item",
property="value",
value=items_text[-1],
str_id="new-item",
triggered=False,
),
),
triggers=[
{
"id": "add",
"property": "n_clicks",
"value": len(items_text),
"str_id": "add",
"triggered": True,
},
{
"id": "new-item",
"property": "n_submit",
"value": None,
"str_id": "new-item",
"triggered": False,
},
],
)
dash_duo.wait_for_text_to_equal("#cc-args-grouping", repr(args_grouping))
# Check outputs_grouping
outputs_grouping = dict(
list_container={"id": "list-container", "property": "children"},
new_item={"id": "new-item", "property": "value"},
totals={"id": "totals", "property": "children"},
cc_args_grouping={"id": "cc-args-grouping", "property": "children"},
cc_outputs_grouping={"id": "cc-outputs-grouping", "property": "children"},
)
dash_duo.wait_for_text_to_equal("#cc-outputs-grouping", repr(outputs_grouping))
new_item.send_keys("apples")
add_item.click()
dash_duo.wait_for_text_to_equal("#totals", "1 total item(s)")
assert_count(1)
assert_callback_context(["apples"])
new_item.send_keys("bananas")
add_item.click()
dash_duo.wait_for_text_to_equal("#totals", "2 total item(s)")
assert_count(2)
assert_callback_context(["apples", "bananas"])
new_item.send_keys("carrots")
add_item.click()
dash_duo.wait_for_text_to_equal("#totals", "3 total item(s)")
assert_count(3)
assert_callback_context(["apples", "bananas", "carrots"])
def test_cbwc007_pmc_update_subtree_ordering(dash_duo):
# Test for regression bug #2368, updated pmc subtree should keep order.
app = dash.Dash(__name__)
app.layout = html.Div(
[
html.Button("refresh options", id="refresh-options"),
html.Br(),
html.Div(
[
*[
dcc.Dropdown(
id={"type": "demo-options", "index": i},
placeholder=f"dropdown-{i}",
style={"width": "200px"},
)
for i in range(2)
],
dcc.Dropdown(
id={"type": "demo-options", "index": 2},
options=[f"option2-{i}" for i in range(3)],
placeholder="dropdown-2",
style={"width": "200px"},
),
],
id="dropdown-container",
),
html.Br(),
html.Pre(id="selected-values"),
],
style={"padding": "50px"},
)
@app.callback(
[
Output({"type": "demo-options", "index": 0}, "options"),
Output({"type": "demo-options", "index": 1}, "options"),
],
Input("refresh-options", "n_clicks"),
prevent_initial_call=True,
)
def refresh_options(_):
return [[f"option0-{i}" for i in range(3)], [f"option1-{i}" for i in range(3)]]
@app.callback(
Output("selected-values", "children"),
Input({"type": "demo-options", "index": ALL}, "value"),
)
def update_selected_values(values):
return str(values)
dash_duo.start_server(app)
dash_duo.select_dcc_dropdown(".dash-dropdown-wrapper:nth-child(3) button", index=2)
dash_duo.wait_for_text_to_equal("#selected-values", "[None, None, 'option2-2']")
dash_duo.wait_for_element("#refresh-options").click()
dash_duo.select_dcc_dropdown(".dash-dropdown-wrapper:nth-child(2) button", index=2)
dash_duo.wait_for_text_to_equal(
"#selected-values", "[None, 'option1-2', 'option2-2']"
)
dash_duo.select_dcc_dropdown(".dash-dropdown-wrapper:nth-child(1) button", index=2)
dash_duo.wait_for_text_to_equal(
"#selected-values", "['option0-2', 'option1-2', 'option2-2']"
)
def test_cbwc008_running_match(dash_duo):
lock = Lock()
app = dash.Dash()
app.layout = [
html.Div(
[
html.Button(
"Test1",
id={"component": "button", "index": "1"},
),
html.Button(
"Test2",
id={"component": "button", "index": "2"},
),
],
id="buttons",
),
html.Div(html.Div(id={"component": "output", "index": "1"}), id="output1"),
html.Div(html.Div(id={"component": "output", "index": "2"}), id="output2"),
]
@app.callback(
Output({"component": "output", "index": MATCH}, "children"),
Input({"component": "button", "index": MATCH}, "n_clicks"),
running=[
(
Output({"component": "button", "index": MATCH}, "children"),
"running",
"finished",
),
(Output({"component": "button", "index": ALL}, "disabled"), True, False),
],
prevent_initial_call=True,
)
def on_click(_) -> str:
with lock:
return "done"
dash_duo.start_server(app)
for i in range(1, 3):
with lock:
dash_duo.find_element(f"#buttons button:nth-child({i})").click()
dash_duo.wait_for_text_to_equal(
f"#buttons button:nth-child({i})", "running"
)
# verify all the buttons were disabled.
assert dash_duo.find_element("#buttons button:nth-child(1)").get_attribute(
"disabled"
)
assert dash_duo.find_element("#buttons button:nth-child(2)").get_attribute(
"disabled"
)
dash_duo.wait_for_text_to_equal(f"#output{i}", "done")
dash_duo.wait_for_text_to_equal(f"#buttons button:nth-child({i})", "finished")
assert not dash_duo.find_element("#buttons button:nth-child(1)").get_attribute(
"disabled"
)
assert not dash_duo.find_element("#buttons button:nth-child(2)").get_attribute(
"disabled"
)
def test_cbwc009_patch_no_spurious_match_callbacks(dash_duo):
"""Regression test for the oldPaths fix in getUnfilteredLayoutCallbacks.
When Patch() appends a new MATCH-pattern component, existing MATCH callbacks
must NOT re-fire for pre-existing components. Previously, crawlLayout would
visit all children in the layout chunk and mark every matching output as
initialCall=true, causing all existing callbacks to spuriously re-execute.
The fix passes oldPaths (the pre-update paths snapshot) into
getUnfilteredLayoutCallbacks and skips initialCall for any component whose
ID already exists in oldPaths.
"""
lock = threading.Lock()
fire_counts = {} # {index: count} how many times each MATCH callback fired
def make_item(index):
return html.Div(
[
dcc.Input(
id={"type": "item-input", "index": index},
value=index,
type="number",
className="item-input",
),
html.Div(
"init",
id={"type": "item-output", "index": index},
className="item-output",
),
]
)
app = Dash(__name__)
app.layout = html.Div(
[
html.Button("Add", id="add-btn", n_clicks=0),
html.Div([make_item(0), make_item(1)], id="container"),
]
)
@app.callback(
Output("container", "children"),
Input("add-btn", "n_clicks"),
prevent_initial_call=True,
)
def add_item(n):
p = Patch()
p.append(make_item(n + 1))
return p
@app.callback(
Output({"type": "item-output", "index": MATCH}, "children"),
Input({"type": "item-input", "index": MATCH}, "value"),
)
def on_value_change(value):
from dash import ctx
idx = ctx.outputs_grouping["id"]["index"]
with lock:
fire_counts[idx] = fire_counts.get(idx, 0) + 1
count = fire_counts[idx]
return f"fired-{idx}-#{count}"
dash_duo.start_server(app)
# Wait for the initial callbacks to fire for both pre-existing items.
wait.until(lambda: fire_counts.get(0, 0) >= 1, 5)
wait.until(lambda: fire_counts.get(1, 0) >= 1, 5)
counts_before = {0: fire_counts[0], 1: fire_counts[1]}
# Add a new item via Patch, this should fire only for index 2.
dash_duo.find_element("#add-btn").click()
wait.until(lambda: fire_counts.get(2, 0) >= 1, 5)
# Pre-existing callbacks must NOT have re-fired.
assert fire_counts[0] == counts_before[0], (
f"Item 0 callback fired spuriously after Patch: "
f"was {counts_before[0]}, now {fire_counts[0]}"
)
assert fire_counts[1] == counts_before[1], (
f"Item 1 callback fired spuriously after Patch: "
f"was {counts_before[1]}, now {fire_counts[1]}"
)
assert (
fire_counts[2] == 1
), f"New item 2 callback should have fired exactly once, fired {fire_counts[2]}"
def test_cbwc010_full_replace_fires_initial_callbacks(dash_duo):
"""Regression test ensuring full-replacement (non-Patch) outputs still fire
initial callbacks for all replaced components.
When a callback returns a full list (not a Patch), every component in the
new layout is a fresh instance. The isUnchangedOutputProp suppression must
NOT apply here: prePatchPaths is absent from the execution result, so
oldPaths/oldLayout are never passed, and all initial calls must fire.
"""
lock = threading.Lock()
fire_counts = {} # {index: count}
def make_item(index):
return html.Div(
[
dcc.Input(
id={"type": "fr-input", "index": index},
value=index,
type="number",
className="fr-input",
),
html.Div(
"init",
id={"type": "fr-output", "index": index},
className="fr-output",
),
]
)
app = Dash(__name__)
app.layout = html.Div(
[
html.Button("Replace", id="replace-btn", n_clicks=0),
html.Div([make_item(0), make_item(1)], id="fr-container"),
]
)
@app.callback(
Output("fr-container", "children"),
Input("replace-btn", "n_clicks"),
prevent_initial_call=True,
)
def replace_items(_):
# Full replacement — returns a plain list, not a Patch
return [make_item(10), make_item(11)]
@app.callback(
Output({"type": "fr-output", "index": MATCH}, "children"),
Input({"type": "fr-input", "index": MATCH}, "value"),
)
def on_value_change(value):
from dash import ctx
idx = ctx.outputs_grouping["id"]["index"]
with lock:
fire_counts[idx] = fire_counts.get(idx, 0) + 1
count = fire_counts[idx]
return f"fired-{idx}-#{count}"
dash_duo.start_server(app)
# Wait for the initial callbacks for items 0 and 1.
wait.until(lambda: fire_counts.get(0, 0) >= 1, 5)
wait.until(lambda: fire_counts.get(1, 0) >= 1, 5)
# Trigger a full replacement.
dash_duo.find_element("#replace-btn").click()
# After full replacement, items 10 and 11 are brand-new instances and
# MUST have their initial callbacks fire.
wait.until(lambda: fire_counts.get(10, 0) >= 1, 5)
wait.until(lambda: fire_counts.get(11, 0) >= 1, 5)
assert (
fire_counts[10] >= 1
), f"New item 10 callback should have fired after full replace, got {fire_counts.get(10, 0)}"
assert (
fire_counts[11] >= 1
), f"New item 11 callback should have fired after full replace, got {fire_counts.get(11, 0)}"