-
Notifications
You must be signed in to change notification settings - Fork 18
/
core_test.py
3210 lines (2562 loc) · 91.4 KB
/
core_test.py
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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import gc
import sys
import time
import traceback
import unittest.mock
import weakref
from concurrent.futures import ThreadPoolExecutor
from typing import Callable, Generic, List, Optional, Tuple, TypeVar, cast
import ipyvuetify
import ipywidgets
import ipywidgets as widgets
import numpy as np
import pandas as pd
import pytest
import traitlets
from IPython.display import display
import reacton as react
import reacton.core
from reacton.core import component, use_effect
from . import bqplot # noqa: F401
from . import logging # noqa: F401
from . import core
from . import ipyvuetify as v
from . import ipywidgets as w
from .core import _get_widgets_dict, ipywidget_version_major
from .patch_display import patch as patch_display
patch_display()
T = TypeVar("T")
def first(container: List[T]) -> T:
return container[0]
def clear():
_get_widgets_dict().clear()
def count():
return len(_get_widgets_dict())
class ContextManager:
def __init__(self, el) -> None:
self.el = el
def __enter__(self):
pass
def __exit__(self, *args):
def effect():
def cleanup():
pass
return cleanup
reacton.use_effect(effect, [])
def set_text(text: str):
pass
reacton.core._component_context_manager_classes.append(ContextManager)
# components used for testing
@component
def MyComponent():
return w.Button()
@react.component
def ButtonComponentFunction(**kwargs):
return w.Button(**kwargs)
@react.component
def ButtonNumber(value):
# to test state reuse
value, set_value = react.use_state(value)
return w.Button(description=str(value))
@react.component
def ButtonNumber2(value):
# to test state reuse
value, set_value = react.use_state(value)
return w.Button(description=str(value))
@react.component
def ContainerFunction(children=[]):
return w.HBox(children=children)
@pytest.fixture(autouse=True)
def cleanup_guard():
before = set(_get_widgets_dict())
yield
after = set(_get_widgets_dict())
leftover = after - before
if leftover:
leftover_widgets = [_get_widgets_dict()[k] for k in leftover]
assert not leftover_widgets
assert reacton.core.Element._callback_wrappers == {}
@pytest.fixture(params=["ButtonComponentWidget", "ButtonComponentFunction"])
def ButtonComponent(request):
return dict(ButtonComponentWidget=w.Button, ButtonComponentFunction=ButtonComponentFunction)[request.param]
@pytest.fixture(params=["ContainerWidget", "ContainerFunction"])
def Container(request):
return dict(ContainerWidget=w.HBox, ContainerFunction=ContainerFunction)[request.param]
Container1 = Container
Container2 = Container
def test_internals():
@react.component
def Child():
return w.VBox()
@react.component
def App():
return Child().key("child") # type: ignore
app = App()
# root_context:
# element: App
# children:
# - '/':
widget, rc = react.render_fixed(app, handle_error=False)
assert rc.context_root.root_element == app
assert rc.context_root.root_element_next is None
assert list(rc.context_root.children_next) == []
assert list(rc.context_root.children) == ["/"]
app_context = rc.context_root.children["/"]
assert list(app_context.children_next) == []
assert list(app_context.children) == ["child"]
assert app_context.invoke_element is app
rc.close()
# assert app_context.children["child"].invoke_element is app_context.elements["child"]
# assert list(rc.context_root.children["/"].children["child"].invoke_element) == ["child"]
def test_create_element():
clear()
button: react.core.Element[widgets.Button] = react.core.Element[widgets.Button](MyComponent)
assert count() == 0
hbox, rc = react.render(button, handle_error=False)
assert len(hbox.children) == 1
assert isinstance(hbox.children[0], widgets.Button)
assert count() == 2 + 3 # button + button layout + button style
rc.close()
def test_no_on_value_on_write():
on_value = unittest.mock.Mock()
def set_value(x: int):
pass
@react.component
def Test():
nonlocal set_value
value, set_value = react.use_state(0) # type: ignore
return w.IntSlider(value=value, on_value=on_value)
box, rc = react.render(Test(), handle_error=False)
assert len(rc.find(widgets.IntSlider)) == 1
set_value(1)
on_value.assert_not_called()
rc.close()
def test_render_element_twice(ButtonComponent, Container):
el = ButtonComponent(description="Hi")
@react.component
def Test(el):
return Container(children=[el, el])
box, rc = react.render(Test(el), handle_error=False)
assert len(rc.find(widgets.Button)) == 2
rc.force_update()
assert len(rc.find(widgets.Button)) == 2
rc.force_update()
assert len(rc.find(widgets.Button)) == 2
rc.close()
def test_remove_element_twice(ButtonComponent, Container):
el1 = ButtonComponent(description="Hi1")
el2 = w.FloatLogSlider(description="Hi2")
def set_first(x: bool):
pass
@react.component
def Test(el1, el2):
nonlocal set_first
first, set_first = react.use_state(True) # type: ignore
if first:
el = el1
else:
el = el2
# return Container(children=[Container(children=[el])], Container(children=[el]))
with Container(children=[el]) as main:
with Container(children=[el]):
pass
with Container(children=[el]):
pass
return main
box, rc = react.render(Test(el1, el2), handle_error=False)
assert len(rc.find(widgets.Button)) == 3
rc.force_update()
assert len(rc.find(widgets.Button)) == 3
rc.force_update()
assert len(rc.find(widgets.Button)) == 3
assert rc.find(widgets.Button)[0].widget.description == "Hi1"
set_first(False)
assert len(rc.find(widgets.FloatLogSlider)) == 3
assert rc.find(widgets.FloatLogSlider)[0].widget.description == "Hi2"
rc.force_update()
rc.close()
def test_remove_element_repeated(ButtonComponent, Container):
def set_other_case(x: bool):
pass
@react.component
def Test():
nonlocal set_other_case
el = ButtonComponent(description="Hi")
other_case, set_other_case = react.use_state(True) # type: ignore
with Container(children=[el]) as main:
with Container(children=[el]):
pass
if other_case:
# this will trigger the removal of el twice
w.Label(value="bump up the children")
with Container(children=[el]):
pass
with Container(children=[el]):
pass
return main
box, rc = react.render(Test(), handle_error=False)
assert len(rc.find(widgets.Button)) == 4
buttons = rc.find(widgets.Button).widgets
assert [b is not buttons[0] for b in buttons]
rc.force_update()
buttons = rc.find(widgets.Button).widgets
assert [b is not buttons[0] for b in buttons]
assert len(rc.find(widgets.Button)) == 4
buttons = rc.find(widgets.Button).widgets
assert [b is not buttons[0] for b in buttons]
rc.force_update()
buttons = rc.find(widgets.Button).widgets
assert [b is not buttons[0] for b in buttons]
assert len(rc.find(widgets.Button)) == 4
assert rc.find(widgets.Button)[0].widget.description == "Hi"
set_other_case(False)
rc.force_update()
rc.close()
def test_replace_parent(ButtonComponent):
def set_other_case(x: bool):
pass
@react.component
def Test():
nonlocal set_other_case
other_case, set_other_case = react.use_state(True) # type: ignore
el = ButtonComponent(description="Hi")
if other_case:
Container = w.VBox
else:
Container = w.HBox
# the root stays the same to have the keys the same
with w.VBox() as main:
# but the intermediate parent changes
with Container(children=[el]):
pass
return main
box, rc = react.render(Test(), handle_error=False)
assert len(rc.find(widgets.Button)) == 1
rc.force_update()
set_other_case(False)
rc.force_update()
rc.close()
@pytest.mark.parametrize("shared", [False, True])
def test_render_count_element(Container, ButtonComponent, shared):
button = ButtonComponent()
@react.component
def DoNothing(children=[]):
return ButtonComponent(description="ignore the arguments")
@react.component
def Test():
nonlocal button
button = ButtonComponent(description="Button")
if shared:
button = button.shared()
with Container() as main:
w.HBox(children=[button])
w.VBox(children=[button])
Container(children=[button])
DoNothing(children=[button])
return main
box, rc = react.render(Test(), handle_error=False)
assert button._render_count == (1 if shared else 3)
rc.close()
def test_monkey_patch():
button = widgets.Button.element(description="Hi")
hbox, rc = react.render(button)
assert len(hbox.children) == 1
assert isinstance(hbox.children[0], widgets.Button)
assert hbox.children[0].description == "Hi"
rc.close()
def test_component_function():
clear()
assert count() == 0
@react.component
def button_or_label(make_button):
if make_button:
return w.Button(description="Button")
else:
return w.Label(description="Label")
hbox, rc = react.render(button_or_label(make_button=False))
assert count() == 2 + 3 # label + label layout + label style
assert len(hbox.children) == 1
assert isinstance(hbox.children[0], widgets.Label)
assert hbox.children[0].description == "Label"
rc.close()
assert count() == 0
hbox, rc = react.render(button_or_label(make_button=True), hbox, "children")
assert len(hbox.children) == 1
assert isinstance(hbox.children[0], widgets.Button)
assert hbox.children[0].description == "Button"
assert count() == 3 # button + label
rc.close()
def test_render_replace():
hbox, rc = react.render(w.Button())
rc.render(w.VBox(), rc.container)
rc.close()
def test_render_conditional_child():
set_value = lambda x: None # noqa
@react.component
def Child():
nonlocal set_value
value, set_value = react.use_state(0)
if value == 0:
return w.Button(description="Button in child")
else:
return w.Label(description="Label in child")
@react.component
def Test():
return Child()
hbox, rc = react.render(Test(), handle_error=False)
assert rc._find(widgets.Button).widget.description == "Button in child"
set_value(1)
assert rc._find(widgets.Label).widget.description == "Label in child"
set_value(0)
assert rc._find(widgets.Button).widget.description == "Button in child"
rc.close()
def test_render_conditional_replace_component_with_element():
set_value = lambda x: None # noqa
def Container():
button = w.Button(description="Button in container")
return w.VBox(children=[button])
@react.component
def Test():
nonlocal set_value
value, set_value = react.use_state(0)
if value == 1:
return Container()
else:
return w.Button(description="Button in root")
hbox, rc = react.render(Test(), handle_error=False)
rc.find(widgets.Button).widget.description == "Button in root"
set_value(1)
rc.find(widgets.Button).widget.description == "Button in container"
set_value(0)
rc.find(widgets.Button).widget.description == "Button in root"
rc.close()
def test_render_many_flip_flop_component():
set_action = None
effect_mock = unittest.mock.Mock()
cleanup = unittest.mock.Mock()
@react.component
def Component(description):
description, set_description = react.use_state(description)
def effect():
effect_mock()
return cleanup
# also test use effect to be sure!
react.use_effect(effect)
return w.Button(description=description)
@react.component
def Test():
nonlocal set_action
action, set_action = react.use_state(0)
if action == 0:
return w.Text(value="initial")
elif action == 1:
set_action(2)
# render component
return Component("first")
elif action == 2:
# render float slider next
set_action(3)
return w.FloatSlider()
elif action == 3:
# set_action(4)
# and return to the component again
return Component("second")
else:
return w.FloatLogSlider()
box, rc = react.render(Test())
assert isinstance(box.children[0], widgets.Text)
assert set_action is not None
set_action(1)
assert isinstance(box.children[0], widgets.Button)
assert box.children[0].description == "second"
assert react.core.local.last_rc() is not None
react.core.local.last_rc().close()
def test_state_simple():
clear()
@react.component
def slider_text():
value, set_value = react.use_state(0.0)
description, set_description = react.use_state("Not changed")
def on_value(value: float):
set_description(f"Value = {value}")
set_value(value)
return w.FloatSlider(value=value, on_value=on_value, description=description)
hbox, rc = react.render(slider_text())
assert count() == 2 + 3
assert len(hbox.children) == 1
slider = hbox.children[0]
assert isinstance(slider, widgets.FloatSlider)
assert slider.description == "Not changed"
assert slider.value == 0
slider.value = 1
# we should update, not replace
assert slider is hbox.children[0]
assert slider.description == "Value = 1.0"
assert count() == 2 + 3
rc.close()
def test_restore_default():
@react.component
def Slider(value):
return w.IntSlider(value=value, description=f"Value {value}")
slider, rc = react.render_fixed(Slider(2))
assert slider.description == "Value 2"
assert slider.value == 2
rc.render(Slider(0))
assert slider.description == "Value 0"
assert slider.value == 0
rc.render(Slider(2))
assert slider.description == "Value 2"
assert slider.value == 2
rc.close()
# now start with the default
slider, rc = react.render_fixed(Slider(0))
assert slider.description == "Value 0"
assert slider.value == 0
rc.render(Slider(2))
assert slider.description == "Value 2"
assert slider.value == 2
rc.render(Slider(0))
assert slider.description == "Value 0"
assert slider.value == 0
rc.close()
def test_state_complicated():
@react.component
def slider_text():
value, set_value = react.use_state(0.0)
description, set_description = react.use_state("Initial value")
set_description(f"Value = {value}")
def on_value(value: float):
set_value(value)
set_description(f"Value = {value}")
return w.FloatSlider(value=value, on_value=on_value, description=description)
slider, rc = react.render_fixed(slider_text())
assert slider.description == "Value = 0.0"
assert slider.value == 0
slider.value = 1
assert slider.description == "Value = 1.0"
rc.close()
def test_state_outside():
clear()
checkbox = widgets.Checkbox(value=False, description="Show button?")
assert count() == 3
@react.component
def button_or_label(checkbox):
show_button = react.use_state_widget(checkbox, "value")
if show_button:
return w.Button(description="Button")
else:
return w.Label(description="Label")
el = button_or_label(checkbox=checkbox)
hbox, rc = react.render(el)
assert count() == 3 + 2 + 3 # checkbox, box, label
assert len(hbox.children) == 1
assert isinstance(hbox.children[0], widgets.Label)
assert hbox.children[0].description == "Label"
before = dict(_get_widgets_dict())
checkbox.value = True
after = dict(_get_widgets_dict())
diff = set(after) - set(before)
extra = list(diff)
assert count() == 3 + 2 + 3 # similar
assert len(extra) == 3
assert len(hbox.children) == 1
assert isinstance(hbox.children[0], widgets.Button)
assert hbox.children[0].description == "Button"
before = dict(_get_widgets_dict())
checkbox.value = False
after = dict(_get_widgets_dict())
diff = set(after) - set(before)
extra = list(diff)
assert len(extra) == 3
assert count() == 3 + 2 + 3
assert len(hbox.children) == 1
assert isinstance(hbox.children[0], widgets.Label)
assert hbox.children[0].description == "Label"
rc.close()
checkbox.layout.close()
checkbox.style.close()
checkbox.close()
def test_children_collect():
class SomeContainer(widgets.Widget):
v_slots = traitlets.Any(widgets.Widget)
@react.component
def Test():
with w.HBox() as main:
button = w.Button(description="Button")
SomeContainer.element(v_slots=[{"name": "extension", "children": button}])
return main
vbox, rc = react.render(Test(), handle_error=False)
# should only have SomeContainer as child
assert len(rc.find(widgets.HBox).widget.children) == 1
rc.close()
def test_children():
clear()
# hbox = widgets.HBox()
# slider = widgets.IntSlider(value=2, description="How many buttons?")
@react.component
def buttons():
buttons, set_buttons = react.use_state(2)
with w.HBox() as main:
_ = w.IntSlider(value=buttons, on_value=set_buttons, description="How many buttons?")
_ = [w.Button(description=f"Button {i}") for i in range(buttons)]
return main
hbox, rc = react.render_fixed(buttons())
slider = hbox.children[0]
# hbox + slider: 2 + 3
assert count() == 2 + 3 + 2 * 3 # added 2 buttons
assert len(hbox.children) == 1 + 2
assert isinstance(hbox.children[1], widgets.Button)
assert isinstance(hbox.children[2], widgets.Button)
assert hbox.children[1] != hbox.children[2]
assert hbox.children[1].description == "Button 0"
assert hbox.children[2].description == "Button 1"
slider.value = 3
assert len(hbox.children) == 1 + 3
assert count() == 2 + 3 + 2 * 3 + 3 # added 1 button
assert isinstance(hbox.children[1], widgets.Button)
assert isinstance(hbox.children[2], widgets.Button)
assert isinstance(hbox.children[3], widgets.Button)
assert hbox.children[1] != hbox.children[2]
assert hbox.children[1] != hbox.children[3]
assert hbox.children[2] != hbox.children[3]
assert hbox.children[1].description == "Button 0"
assert hbox.children[2].description == "Button 1"
assert hbox.children[3].description == "Button 2"
slider.value = 2
assert count() == 2 + 3 + 2 * 3 # nothing added, just 1 unused
# TODO: what do we do with pool?
# assert len(rc.pool) == 1 # which is added to the pool
assert len(hbox.children) == 1 + 2
assert isinstance(hbox.children[1], widgets.Button)
assert isinstance(hbox.children[2], widgets.Button)
rc.close()
def test_display():
@react.component
def Button(value):
return w.Button(description=f"Value {value}")
react.display(Button(2))
assert react.core.local.last_rc() is not None
vbox: widgets.VBox = react.core.local.last_rc().container
assert vbox._view_count == 0
vbox._view_count = 1 # act as if it is displayed
vbox._view_count = 0 # and removed again
# so we don't have to do this manually:
# react.core.local.last_rc().close()
def test_box():
hbox = widgets.HBox()
slider = widgets.IntSlider(value=2, description="How many buttons?")
assert count() == 2 + 3
@react.component
def buttons(slider):
buttons = react.use_state_widget(slider, "value")
return w.VBox(children=[w.Button(description=f"Button {i}") for i in range(buttons)])
el = buttons(slider)
hbox, rc = react.render(el, hbox, "children")
assert count() == 2 + 3 + 2 + 2 * 3 # add vbox and 2 buttons
assert len(hbox.children[0].children) == 2
assert isinstance(hbox.children[0].children[0], widgets.Button)
assert isinstance(hbox.children[0].children[1], widgets.Button)
slider.value = 3
rc.force_update()
assert count() == 2 + 3 + 2 + 2 * 3 + 3 # add 1 button
assert len(hbox.children[0].children) == 3
assert isinstance(hbox.children[0].children[0], widgets.Button)
assert isinstance(hbox.children[0].children[1], widgets.Button)
assert isinstance(hbox.children[0].children[2], widgets.Button)
slider.value = 2
rc.force_update()
assert count() == 2 + 3 + 2 + 2 * 3 # should clean up
assert len(hbox.children[0].children) == 2
assert isinstance(hbox.children[0].children[0], widgets.Button)
assert isinstance(hbox.children[0].children[1], widgets.Button)
rc.close()
slider.style.close()
slider.layout.close()
slider.close()
def test_shared_instance_via_widget_element(ButtonComponent, Container):
checkbox = widgets.Checkbox(value=True, description="Share button")
@react.component
def Buttons(checkbox):
share = react.use_state_widget(checkbox, "value", "share")
if share:
button_shared = ButtonComponent(description="Button shared", tooltip="shared").shared()
return Container(children=[button_shared, button_shared])
else:
return Container(children=[ButtonComponent(description=f"Button {i}") for i in range(2)])
hbox, rc = react.render(Buttons(checkbox), handle_error=False)
vbox = hbox.children[0]
assert vbox.children[0] is vbox.children[1]
assert vbox.children[0].description == "Button shared"
assert vbox.children[0].tooltip == "shared"
checkbox.value = False
rc.force_update()
assert vbox.children[0] is not vbox.children[1]
assert vbox.children[0].description == "Button 0"
assert vbox.children[1].description == "Button 1"
if ipywidget_version_major >= 8:
assert vbox.children[0].tooltip is None
assert vbox.children[1].tooltip is None
else:
assert vbox.children[0].tooltip == ""
assert vbox.children[1].tooltip == ""
rc.close()
checkbox.style.close()
checkbox.layout.close()
checkbox.close()
@pytest.mark.parametrize("shared", [False, True])
def test_shared_instance_via_component(ButtonComponent, shared, Container):
@react.component
def Child(button):
return button
@react.component
def Buttons():
button = ButtonComponent(description="Button shared")
if shared:
button = button.shared()
return Container(children=[Child(button), Child(button)])
vbox, rc = react.render_fixed(Buttons())
assert vbox.children[0].description == "Button shared"
assert vbox.children[1].description == "Button shared"
if shared:
assert vbox.children[0] is vbox.children[1]
else:
assert vbox.children[0] is not vbox.children[1]
rc.close()
def test_bqplot():
clear()
exponent = widgets.FloatSlider(min=0.1, max=2, value=1.0, description="Exponent")
assert count() == 3
@react.component
def Plot(exponent, x, y):
exponent_value = react.use_state_widget(exponent, "value")
x = x**exponent_value
x_scale = bqplot.LinearScale(allow_padding=False).shared()
y_scale = bqplot.LinearScale(allow_padding=False).shared()
lines = bqplot.Lines(x=x, y=y, scales={"x": x_scale, "y": y_scale}, stroke_width=3, colors=["red"], display_legend=True, labels=["Line chart"])
x_axis = bqplot.Axis(scale=x_scale)
y_axis = bqplot.Axis(scale=y_scale)
axes = [x_axis, y_axis]
return bqplot.Figure(axes=axes, marks=[lines], scale_x=x_scale, scale_y=y_scale)
x = np.arange(4)
y = x**exponent.value
hbox, rc = react.render(Plot(exponent, x, y))
widgets_initial = count()
figure = hbox.children[0]
import bqplot as bq # type: ignore
assert isinstance(figure.axes[0], bq.Axis)
assert figure.marks[0].x.tolist() == x.tolist()
assert figure.axes[0] is not figure.axes[1]
assert figure.axes[0].scale is not figure.axes[1].scale
assert figure.axes[0].scale is figure.marks[0].scales["x"]
before = dict(_get_widgets_dict())
exponent.value = 2
after = dict(_get_widgets_dict())
diff = set(after) - set(before)
extra = list(diff)
assert extra == []
before = dict(_get_widgets_dict())
assert count() == widgets_initial # nothing should be recreated
# figure = box.children[0]
assert figure.marks[0].x.tolist() == (x**2).tolist()
exponent.style.close()
exponent.layout.close()
exponent.close()
rc.close()
def test_use_effect():
@react.component
def Button2():
clicks, set_clicks = react.use_state(0)
def add_event_handler():
button: widgets.Button = react.core.get_widget(button_el)
def handler(change):
set_clicks(clicks + 1)
button.on_click(handler)
return lambda: button.on_click(handler, remove=True)
react.use_effect(add_event_handler)
button_el = w.Button(description=f"Clicked {clicks} times")
return button_el
hbox, rc = react.render(Button2(), handle_error=False)
assert count() == 2 + 3 # label + button
button = hbox.children[0]
assert button.description == "Clicked 0 times"
button.click()
assert len(button._click_handlers.callbacks) == 1
assert button.description == "Clicked 1 times"
rc.close()
def test_use_effect_no_deps():
calls = 0
cleanups = 0
@react.component
def TestNoDeps(a, b, not_used=0):
def test_effect():
def cleanup():
nonlocal cleanups
cleanups += 1
nonlocal calls
calls += 1
return cleanup
react.use_effect(test_effect)
return w.Button()
hbox, rc = react.render(TestNoDeps(a=1, b=1))
assert calls == 1
assert cleanups == 0
rc.render(TestNoDeps(a=1, b=1, not_used=2), hbox)
assert calls == 2
assert cleanups == 1
rc.close()
def test_use_effect_once():
calls = 0
cleanups = 0
counters_seen = []
@react.component
def TestNoDeps(a, b):
counter, set_counter = react.use_state(0)
def test_effect():
def cleanup():
nonlocal cleanups
cleanups += 1
nonlocal calls
calls += 1
# we should only be executed after the last render
# when counter is 1
counters_seen.append(counter)
return cleanup
# this forces a rerender, but the use_effect should
# still be called just once
if counter == 0:
set_counter(1)
react.use_effect(test_effect, [])
return w.Button()
hbox, rc = react.render(TestNoDeps(a=1, b=1))
assert calls == 1
assert cleanups == 0
assert counters_seen == [1]
rc.render(TestNoDeps(a=1, b=1), hbox)
assert calls == 1
assert cleanups == 0
rc.close()
def test_use_effect_deps():
calls = 0
cleanups = 0
@react.component
def TestNoDeps(a, b):
def test_effect():
def cleanup():
nonlocal cleanups
cleanups += 1
nonlocal calls
calls += 1
return cleanup
react.use_effect(test_effect, [a, b])
return w.Button()
hbox, rc = react.render(TestNoDeps(a=1, b=1))
assert calls == 1
assert cleanups == 0
rc.render(TestNoDeps(a=1, b=1), hbox)
assert calls == 1
assert cleanups == 0
rc.render(TestNoDeps(a=1, b=2), hbox)
assert calls == 2
assert cleanups == 1
rc.close()
@react.component
def ButtonClicks(**kwargs):
clicks, set_clicks = react.use_state(0)
return w.Button(description=f"Clicked {clicks} times", on_click=lambda: set_clicks(clicks + 1), **kwargs)
def test_use_button():
hbox, rc = react.render(ButtonClicks())
assert count() == 2 + 3 # label + button
button = hbox.children[0]
assert button.description == "Clicked 0 times"
button.click()
assert len(button._click_handlers.callbacks) == 1
assert button.description == "Clicked 1 times"
rc.close()
def test_key_widget():
set_reverse = None
@react.component
def Buttons():
nonlocal set_reverse
reverse, set_reverse = react.use_state(False)
with w.VBox() as main:
if reverse:
widgets.IntSlider.element(value=4).key("slider")
widgets.Button.element(description="Hi").key("btn")
else:
widgets.Button.element(description="Hi").key("btn")
widgets.IntSlider.element(value=4).key("slider")
return main