-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathtest_component.py
More file actions
2319 lines (1970 loc) ยท 68.2 KB
/
test_component.py
File metadata and controls
2319 lines (1970 loc) ยท 68.2 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
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
from contextlib import nullcontext
from typing import Any, ClassVar
import pytest
import reflex as rx
from reflex.base import Base
from reflex.compiler.utils import compile_custom_component
from reflex.components.base.bare import Bare
from reflex.components.base.fragment import Fragment
from reflex.components.component import (
CUSTOM_COMPONENTS,
Component,
CustomComponent,
StatefulComponent,
custom_component,
)
from reflex.components.radix.themes.layout.box import Box
from reflex.constants import EventTriggers
from reflex.event import (
EventChain,
EventHandler,
JavascriptInputEvent,
input_event,
no_args_event_spec,
parse_args_spec,
passthrough_event_spec,
)
from reflex.state import BaseState
from reflex.style import Style
from reflex.utils import imports
from reflex.utils.exceptions import (
ChildrenTypeError,
EventFnArgMismatchError,
EventHandlerArgTypeMismatchError,
)
from reflex.utils.imports import ImportDict, ImportVar, ParsedImportDict, parse_imports
from reflex.vars import VarData
from reflex.vars.base import LiteralVar, Var
from reflex.vars.object import ObjectVar
@pytest.fixture
def test_state():
class TestState(BaseState):
num: int
def do_something(self):
pass
def do_something_arg(self, arg):
pass
def do_something_with_bool(self, arg: bool):
pass
def do_something_with_int(self, arg: int):
pass
def do_something_with_list_int(self, arg: list[int]):
pass
def do_something_with_list_str(self, arg: list[str]):
pass
def do_something_required_optional(
self, required_arg: int, optional_arg: int | None = None
):
pass
return TestState
@pytest.fixture
def component1() -> type[Component]:
"""A test component.
Returns:
A test component.
"""
class TestComponent1(Component):
# A test string prop.
text: Var[str]
# A test number prop.
number: Var[int]
# A test string/number prop.
text_or_number: Var[int | str]
def _get_imports(self) -> ParsedImportDict:
return {"react": [ImportVar(tag="Component")]}
def _get_custom_code(self) -> str:
return "console.log('component1')"
return TestComponent1
@pytest.fixture
def component2() -> type[Component]:
"""A test component.
Returns:
A test component.
"""
def on_prop_event_spec(e0: Any):
return [e0]
class TestComponent2(Component):
# A test list prop.
arr: Var[list[str]]
on_prop_event: EventHandler[on_prop_event_spec]
def get_event_triggers(self) -> dict[str, Any]:
"""Test controlled triggers.
Returns:
Test controlled triggers.
"""
return {
**super().get_event_triggers(),
"on_open": passthrough_event_spec(bool),
"on_close": passthrough_event_spec(bool),
"on_user_visited_count_changed": passthrough_event_spec(int),
"on_two_args": passthrough_event_spec(int, int),
"on_user_list_changed": passthrough_event_spec(list[str]),
}
def _get_imports(self) -> ParsedImportDict:
return {"react-redux": [ImportVar(tag="connect")]}
def _get_custom_code(self) -> str:
return "console.log('component2')"
return TestComponent2
@pytest.fixture
def component3() -> type[Component]:
"""A test component with hook defined.
Returns:
A test component.
"""
class TestComponent3(Component):
def _get_hooks(self) -> str:
return "const a = () => true"
return TestComponent3
@pytest.fixture
def component4() -> type[Component]:
"""A test component with hook defined.
Returns:
A test component.
"""
class TestComponent4(Component):
def _get_hooks(self) -> str:
return "const b = () => false"
return TestComponent4
@pytest.fixture
def component5() -> type[Component]:
"""A test component.
Returns:
A test component.
"""
class TestComponent5(Component):
tag = "RandomComponent"
_invalid_children: ClassVar[list[str]] = ["Text"]
_valid_children: ClassVar[list[str]] = ["Text"]
_valid_parents: ClassVar[list[str]] = ["Text"]
return TestComponent5
@pytest.fixture
def component6() -> type[Component]:
"""A test component.
Returns:
A test component.
"""
class TestComponent6(Component):
tag = "RandomComponent"
_invalid_children: ClassVar[list[str]] = ["Text"]
return TestComponent6
@pytest.fixture
def component7() -> type[Component]:
"""A test component.
Returns:
A test component.
"""
class TestComponent7(Component):
tag = "RandomComponent"
_valid_children: ClassVar[list[str]] = ["Text"]
return TestComponent7
@pytest.fixture
def on_click1() -> EventHandler:
"""A sample on click function.
Returns:
A sample on click function.
"""
def on_click1():
pass
return EventHandler(fn=on_click1)
@pytest.fixture
def on_click2() -> EventHandler:
"""A sample on click function.
Returns:
A sample on click function.
"""
def on_click2():
pass
return EventHandler(fn=on_click2)
@pytest.fixture
def my_component():
"""A test component function.
Returns:
A test component function.
"""
def my_component(prop1: Var[str], prop2: Var[int]):
return Box.create(prop1, prop2)
return my_component
def test_set_style_attrs(component1):
"""Test that style attributes are set in the dict.
Args:
component1: A test component.
"""
component = component1.create(color="white", text_align="center")
assert str(component.style["color"]) == '"white"'
assert str(component.style["textAlign"]) == '"center"'
def test_custom_attrs(component1):
"""Test that custom attributes are set in the dict.
Args:
component1: A test component.
"""
component = component1.create(custom_attrs={"attr1": "1", "attr2": "attr2"})
assert component.custom_attrs == {"attr1": "1", "attr2": "attr2"}
def test_create_component(component1):
"""Test that the component is created correctly.
Args:
component1: A test component.
"""
children = [component1.create() for _ in range(3)]
attrs = {"color": "white", "text_align": "center"}
c = component1.create(*children, **attrs)
assert isinstance(c, component1)
assert c.children == children
assert (
str(LiteralVar.create(c.style))
== '({ ["color"] : "white", ["textAlign"] : "center" })'
)
@pytest.mark.parametrize(
"prop_name,var,expected",
[
pytest.param(
"text",
LiteralVar.create("hello"),
None,
id="text",
),
pytest.param(
"text",
Var(_js_expr="hello", _var_type=str | None),
None,
id="text-optional",
),
pytest.param(
"text",
Var(_js_expr="hello", _var_type=str | None),
None,
id="text-union-str-none",
),
pytest.param(
"text",
Var(_js_expr="hello", _var_type=None | str),
None,
id="text-union-none-str",
),
pytest.param(
"text",
LiteralVar.create(1),
TypeError,
id="text-int",
),
pytest.param(
"number",
LiteralVar.create(1),
None,
id="number",
),
pytest.param(
"number",
Var(_js_expr="1", _var_type=int | None),
None,
id="number-optional",
),
pytest.param(
"number",
Var(_js_expr="1", _var_type=int | None),
None,
id="number-union-int-none",
),
pytest.param(
"number",
Var(_js_expr="1", _var_type=None | int),
None,
id="number-union-none-int",
),
pytest.param(
"number",
LiteralVar.create("1"),
TypeError,
id="number-str",
),
pytest.param(
"text_or_number",
LiteralVar.create("hello"),
None,
id="text_or_number-str",
),
pytest.param(
"text_or_number",
LiteralVar.create(1),
None,
id="text_or_number-int",
),
pytest.param(
"text_or_number",
Var(_js_expr="hello", _var_type=str | None),
None,
id="text_or_number-optional-str",
),
pytest.param(
"text_or_number",
Var(_js_expr="hello", _var_type=str | None),
None,
id="text_or_number-union-str-none",
),
pytest.param(
"text_or_number",
Var(_js_expr="hello", _var_type=None | str),
None,
id="text_or_number-union-none-str",
),
pytest.param(
"text_or_number",
Var(_js_expr="1", _var_type=int | None),
None,
id="text_or_number-optional-int",
),
pytest.param(
"text_or_number",
Var(_js_expr="1", _var_type=int | None),
None,
id="text_or_number-union-int-none",
),
pytest.param(
"text_or_number",
Var(_js_expr="1", _var_type=None | int),
None,
id="text_or_number-union-none-int",
),
pytest.param(
"text_or_number",
LiteralVar.create(1.0),
TypeError,
id="text_or_number-float",
),
pytest.param(
"text_or_number",
Var(_js_expr="hello", _var_type=str | int | None),
None,
id="text_or_number-optional-union-str-int",
),
],
)
def test_create_component_prop_validation(
component1: type[Component],
prop_name: str,
var: Var | str | int,
expected: type[Exception],
):
"""Test that component props are validated correctly.
Args:
component1: A test component.
prop_name: The name of the prop.
var: The value of the prop.
expected: The expected exception.
"""
ctx = pytest.raises(expected) if expected else nullcontext()
kwargs = {prop_name: var}
with ctx:
c = component1.create(**kwargs)
assert isinstance(c, component1)
assert c.children == []
assert c.style == {}
def test_add_style(component1, component2):
"""Test adding a style to a component.
Args:
component1: A test component.
component2: A test component.
"""
style = {
component1: Style({"color": "white"}),
component2: Style({"color": "black"}),
}
c1 = component1.create()._add_style_recursive(style)
c2 = component2.create()._add_style_recursive(style)
assert str(c1.style["color"]) == '"white"'
assert str(c2.style["color"]) == '"black"'
def test_add_style_create(component1, component2):
"""Test that adding style works with the create method.
Args:
component1: A test component.
component2: A test component.
"""
style = {
component1.create: Style({"color": "white"}),
component2.create: Style({"color": "black"}),
}
c1 = component1.create()._add_style_recursive(style)
c2 = component2.create()._add_style_recursive(style)
assert str(c1.style["color"]) == '"white"'
assert str(c2.style["color"]) == '"black"'
def test_get_imports(component1, component2):
"""Test getting the imports of a component.
Args:
component1: A test component.
component2: A test component.
"""
c1 = component1.create()
c2 = component2.create(c1)
assert c1._get_all_imports() == {"react": [ImportVar(tag="Component")]}
assert c2._get_all_imports() == {
"react-redux": [ImportVar(tag="connect")],
"react": [ImportVar(tag="Component")],
}
def test_get_custom_code(component1, component2):
"""Test getting the custom code of a component.
Args:
component1: A test component.
component2: A test component.
"""
# Check that the code gets compiled correctly.
c1 = component1.create()
c2 = component2.create()
assert c1._get_all_custom_code() == {"console.log('component1')"}
assert c2._get_all_custom_code() == {"console.log('component2')"}
# Check that nesting components compiles both codes.
c1 = component1.create(c2)
assert c1._get_all_custom_code() == {
"console.log('component1')",
"console.log('component2')",
}
# Check that code is not duplicated.
c1 = component1.create(c2, c2, c1, c1)
assert c1._get_all_custom_code() == {
"console.log('component1')",
"console.log('component2')",
}
def test_get_props(component1, component2):
"""Test that the props are set correctly.
Args:
component1: A test component.
component2: A test component.
"""
assert component1.get_props() == {"text", "number", "text_or_number"}
assert component2.get_props() == {"arr", "on_prop_event"}
@pytest.mark.parametrize(
"text,number",
[
("", 0),
("test", 1),
("hi", -13),
],
)
def test_valid_props(component1, text: str, number: int):
"""Test that we can construct a component with valid props.
Args:
component1: A test component.
text: A test string.
number: A test number.
"""
c = component1.create(text=text, number=number)
assert c.text._decode() == text
assert c.number._decode() == number
@pytest.mark.parametrize(
"text,number", [("", "bad_string"), (13, 1), ("test", [1, 2, 3])]
)
def test_invalid_prop_type(component1, text: str, number: int):
"""Test that an invalid prop type raises an error.
Args:
component1: A test component.
text: A test string.
number: A test number.
"""
# Check that
with pytest.raises(TypeError):
component1.create(text=text, number=number)
def test_var_props(component1, test_state):
"""Test that we can set a Var prop.
Args:
component1: A test component.
test_state: A test state.
"""
c1 = component1.create(text="hello", number=test_state.num)
assert c1.number.equals(test_state.num)
def test_get_event_triggers(component1, component2):
"""Test that we can get the triggers of a component.
Args:
component1: A test component.
component2: A test component.
"""
default_triggers = {
EventTriggers.ON_FOCUS,
EventTriggers.ON_BLUR,
EventTriggers.ON_CLICK,
EventTriggers.ON_CONTEXT_MENU,
EventTriggers.ON_DOUBLE_CLICK,
EventTriggers.ON_MOUSE_DOWN,
EventTriggers.ON_MOUSE_ENTER,
EventTriggers.ON_MOUSE_LEAVE,
EventTriggers.ON_MOUSE_MOVE,
EventTriggers.ON_MOUSE_OUT,
EventTriggers.ON_MOUSE_OVER,
EventTriggers.ON_MOUSE_UP,
EventTriggers.ON_SCROLL,
EventTriggers.ON_MOUNT,
EventTriggers.ON_UNMOUNT,
}
assert component1.create().get_event_triggers().keys() == default_triggers
assert (
component2.create().get_event_triggers().keys()
== {
"on_open",
"on_close",
"on_prop_event",
"on_user_visited_count_changed",
"on_two_args",
"on_user_list_changed",
}
| default_triggers
)
@pytest.fixture
def test_component() -> type[Component]:
"""A test component.
Returns:
A test component.
"""
class TestComponent(Component):
pass
return TestComponent
# Write a test case to check if the create method filters out None props
def test_create_filters_none_props(test_component):
child1 = test_component.create()
child2 = test_component.create()
props = {
"prop1": "value1",
"prop2": None,
"prop3": "value3",
"prop4": None,
"style": {"color": "white", "text-align": "center"}, # Adding a style prop
}
component = test_component.create(child1, child2, **props)
# Assert that None props are not present in the component's props
assert "prop2" not in component.get_props()
assert "prop4" not in component.get_props()
# Assert that the style prop is present in the component's props
assert str(component.style["color"]) == '"white"'
assert str(component.style["textAlign"]) == '"center"'
@pytest.mark.parametrize(
"children",
[
({"foo": "bar"},),
],
)
def test_component_create_unallowed_types(children, test_component):
with pytest.raises(ChildrenTypeError):
test_component.create(*children)
@pytest.mark.parametrize(
"element, expected",
[
(
(rx.text("first_text"),),
{
"name": "Fragment",
"props": [],
"contents": "",
"special_props": [],
"children": [
{
"name": "RadixThemesText",
"props": ['as={"p"}'],
"contents": "",
"special_props": [],
"children": [
{
"name": "",
"props": [],
"contents": '{"first_text"}',
"special_props": [],
"children": [],
"autofocus": False,
}
],
"autofocus": False,
}
],
"autofocus": False,
},
),
(
(rx.text("first_text"), rx.text("second_text")),
{
"autofocus": False,
"children": [
{
"autofocus": False,
"children": [
{
"autofocus": False,
"children": [],
"contents": '{"first_text"}',
"name": "",
"props": [],
"special_props": [],
}
],
"contents": "",
"name": "RadixThemesText",
"props": ['as={"p"}'],
"special_props": [],
},
{
"autofocus": False,
"children": [
{
"autofocus": False,
"children": [],
"contents": '{"second_text"}',
"name": "",
"props": [],
"special_props": [],
}
],
"contents": "",
"name": "RadixThemesText",
"props": ['as={"p"}'],
"special_props": [],
},
],
"contents": "",
"name": "Fragment",
"props": [],
"special_props": [],
},
),
(
(rx.text("first_text"), rx.box((rx.text("second_text"),))),
{
"autofocus": False,
"children": [
{
"autofocus": False,
"children": [
{
"autofocus": False,
"children": [],
"contents": '{"first_text"}',
"name": "",
"props": [],
"special_props": [],
}
],
"contents": "",
"name": "RadixThemesText",
"props": ['as={"p"}'],
"special_props": [],
},
{
"autofocus": False,
"children": [
{
"autofocus": False,
"children": [
{
"autofocus": False,
"children": [
{
"autofocus": False,
"children": [],
"contents": '{"second_text"}',
"name": "",
"props": [],
"special_props": [],
}
],
"contents": "",
"name": "RadixThemesText",
"props": ['as={"p"}'],
"special_props": [],
}
],
"contents": "",
"name": "Fragment",
"props": [],
"special_props": [],
}
],
"contents": "",
"name": "RadixThemesBox",
"props": [],
"special_props": [],
},
],
"contents": "",
"name": "Fragment",
"props": [],
"special_props": [],
},
),
],
)
def test_component_create_unpack_tuple_child(test_component, element, expected):
"""Test that component in tuples are unwrapped into an rx.Fragment.
Args:
test_component: Component fixture.
element: The children to pass to the component.
expected: The expected render dict.
"""
comp = test_component.create(element)
assert len(comp.children) == 1
fragment_wrapper = comp.children[0]
assert isinstance(fragment_wrapper, Fragment)
assert fragment_wrapper.render() == expected
class _Obj(Base):
custom: int = 0
class C1State(BaseState):
"""State for testing C1 component."""
def mock_handler(self, _e: JavascriptInputEvent, _bravo: dict, _charlie: _Obj):
"""Mock handler."""
pass
def test_component_event_trigger_arbitrary_args():
"""Test that we can define arbitrary types for the args of an event trigger."""
def on_foo_spec(
_e: ObjectVar[JavascriptInputEvent],
alpha: Var[str],
bravo: dict[str, Any],
charlie: ObjectVar[_Obj],
):
return [_e.target.value, bravo["nested"], charlie.custom.to(int) + 42]
class C1(Component):
library = "/local"
tag = "C1"
def get_event_triggers(self) -> dict[str, Any]:
return {
**super().get_event_triggers(),
"on_foo": on_foo_spec,
}
C1.create(on_foo=C1State.mock_handler)
def test_create_custom_component(my_component):
"""Test that we can create a custom component.
Args:
my_component: A test custom component.
"""
component = rx.memo(my_component)(prop1="test", prop2=1)
assert component.tag == "MyComponent"
assert component.get_props() == {"prop1", "prop2"}
assert component.tag in CUSTOM_COMPONENTS
def test_custom_component_hash(my_component):
"""Test that the hash of a custom component is correct.
Args:
my_component: A test custom component.
"""
component1 = rx.memo(my_component)(prop1="test", prop2=1)
component2 = rx.memo(my_component)(prop1="test", prop2=2)
assert {component1, component2} == {component1}
def test_custom_component_wrapper():
"""Test that the wrapper of a custom component is correct."""
@custom_component
def my_component(width: Var[int], color: Var[str]):
return rx.box(
width=width,
color=color,
)
from reflex.components.radix.themes.typography.text import Text
ccomponent = my_component(
rx.text("child"), width=LiteralVar.create(1), color=LiteralVar.create("red")
)
assert isinstance(ccomponent, CustomComponent)
assert len(ccomponent.children) == 1
assert isinstance(ccomponent.children[0], Text)
component = ccomponent.get_component(ccomponent)
assert isinstance(component, Box)
def test_invalid_event_handler_args(component2, test_state):
"""Test that an invalid event handler raises an error.
Args:
component2: A test component.
test_state: A test state.
"""
# EventHandler args must match
with pytest.raises(EventFnArgMismatchError):
component2.create(on_click=test_state.do_something_arg)
# EventHandler args must have at least as many default args as the spec.
with pytest.raises(EventFnArgMismatchError):
component2.create(on_click=test_state.do_something_required_optional)
# Multiple EventHandler args: all must match
with pytest.raises(EventFnArgMismatchError):
component2.create(
on_click=[test_state.do_something_arg, test_state.do_something]
)
# # Event Handler types must match
with pytest.raises(EventHandlerArgTypeMismatchError):
component2.create(
on_user_visited_count_changed=test_state.do_something_with_bool
)
with pytest.raises(EventHandlerArgTypeMismatchError):
component2.create(on_user_list_changed=test_state.do_something_with_int)
with pytest.raises(EventHandlerArgTypeMismatchError):
component2.create(on_user_list_changed=test_state.do_something_with_list_int)
component2.create(on_open=test_state.do_something_with_int)
component2.create(on_open=test_state.do_something_with_bool)
component2.create(on_user_visited_count_changed=test_state.do_something_with_int)
component2.create(on_user_list_changed=test_state.do_something_with_list_str)
# lambda cannot return weird values.
with pytest.raises(ValueError):
component2.create(on_click=lambda: 1)
with pytest.raises(ValueError):
component2.create(on_click=lambda: [1])
with pytest.raises(ValueError):
component2.create(
on_click=lambda: (test_state.do_something_arg(1), test_state.do_something)
)
# lambda signature must match event trigger.
with pytest.raises(EventFnArgMismatchError):
component2.create(on_click=lambda _: test_state.do_something_arg(1))
# lambda returning EventHandler must match spec
with pytest.raises(EventFnArgMismatchError):
component2.create(on_click=lambda: test_state.do_something_arg)
# Mixed EventSpec and EventHandler must match spec.
with pytest.raises(EventFnArgMismatchError):
component2.create(
on_click=lambda: [
test_state.do_something_arg(1),
test_state.do_something_arg,
]
)
def test_valid_event_handler_args(component2, test_state):
"""Test that an valid event handler args do not raise exception.
Args:
component2: A test component.
test_state: A test state.
"""
# Uncontrolled event handlers should not take args.
component2.create(on_click=test_state.do_something)
component2.create(on_click=test_state.do_something_arg(1))
# Does not raise because event handlers are allowed to have less args than the spec.
component2.create(on_open=test_state.do_something)
component2.create(on_prop_event=test_state.do_something)
# Does not raise because event handlers can have optional args.
component2.create(
on_user_visited_count_changed=test_state.do_something_required_optional
)