-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathtest_state.py
3645 lines (2908 loc) ยท 107 KB
/
test_state.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
from __future__ import annotations
import asyncio
import copy
import dataclasses
import datetime
import functools
import json
import os
import sys
import threading
from textwrap import dedent
from typing import (
Any,
AsyncGenerator,
Callable,
Dict,
List,
Optional,
Set,
Tuple,
Union,
)
from unittest.mock import AsyncMock, Mock
import pytest
import pytest_asyncio
from plotly.graph_objects import Figure
from pydantic import BaseModel as BaseModelV2
from pydantic.v1 import BaseModel as BaseModelV1
import reflex as rx
import reflex.config
from reflex import constants
from reflex.app import App
from reflex.base import Base
from reflex.components.sonner.toast import Toaster
from reflex.constants import CompileVars, RouteVar, SocketEvent
from reflex.event import Event, EventHandler
from reflex.state import (
BaseState,
ImmutableStateError,
LockExpiredError,
MutableProxy,
OnLoadInternalState,
RouterData,
State,
StateManager,
StateManagerDisk,
StateManagerMemory,
StateManagerRedis,
StateProxy,
StateUpdate,
_substate_key,
)
from reflex.testing import chdir
from reflex.utils import format, prerequisites, types
from reflex.utils.exceptions import (
ReflexRuntimeError,
SetUndefinedStateVarError,
StateSerializationError,
)
from reflex.utils.format import json_dumps
from reflex.vars.base import Var, computed_var
from tests.units.states.mutation import MutableSQLAModel, MutableTestState
from .states import GenState
CI = bool(os.environ.get("CI", False))
LOCK_EXPIRATION = 2000 if CI else 300
LOCK_EXPIRE_SLEEP = 2.5 if CI else 0.4
formatted_router = {
"session": {"client_token": "", "client_ip": "", "session_id": ""},
"headers": {
"host": "",
"origin": "",
"upgrade": "",
"connection": "",
"cookie": "",
"pragma": "",
"cache_control": "",
"user_agent": "",
"sec_websocket_version": "",
"sec_websocket_key": "",
"sec_websocket_extensions": "",
"accept_encoding": "",
"accept_language": "",
},
"page": {
"host": "",
"path": "",
"raw_path": "",
"full_path": "",
"full_raw_path": "",
"params": {},
},
}
class Object(Base):
"""A test object fixture."""
prop1: int = 42
prop2: str = "hello"
class TestState(BaseState):
"""A test state."""
# Set this class as not test one
__test__ = False
num1: int
num2: float = 3.14
key: str
map_key: str = "a"
array: List[float] = [1, 2, 3.14]
mapping: Dict[str, List[int]] = {"a": [1, 2, 3], "b": [4, 5, 6]}
obj: Object = Object()
complex: Dict[int, Object] = {1: Object(), 2: Object()}
fig: Figure = Figure()
dt: datetime.datetime = datetime.datetime.fromisoformat("1989-11-09T18:53:00+01:00")
_backend: int = 0
asynctest: int = 0
@computed_var
def sum(self) -> float:
"""Dynamically sum the numbers.
Returns:
The sum of the numbers.
"""
return self.num1 + self.num2
@computed_var
def upper(self) -> str:
"""Uppercase the key.
Returns:
The uppercased key.
"""
return self.key.upper()
def do_something(self):
"""Do something."""
pass
async def set_asynctest(self, value: int):
"""Set the asynctest value. Intentionally overwrite the default setter with an async one.
Args:
value: The new value.
"""
self.asynctest = value
class ChildState(TestState):
"""A child state fixture."""
value: str
count: int = 23
def change_both(self, value: str, count: int):
"""Change both the value and count.
Args:
value: The new value.
count: The new count.
"""
self.value = value.upper()
self.count = count * 2
class ChildState2(TestState):
"""A child state fixture."""
value: str
class ChildState3(TestState):
"""A child state fixture."""
value: str
class GrandchildState(ChildState):
"""A grandchild state fixture."""
value2: str
def do_nothing(self):
"""Do something."""
pass
class GrandchildState2(ChildState2):
"""A grandchild state fixture."""
@rx.var(cache=True)
def cached(self) -> str:
"""A cached var.
Returns:
The value.
"""
return self.value
class GrandchildState3(ChildState3):
"""A great grandchild state fixture."""
@rx.var
def computed(self) -> str:
"""A computed var.
Returns:
The value.
"""
return self.value
class DateTimeState(BaseState):
"""A State with some datetime fields."""
d: datetime.date = datetime.date.fromisoformat("1989-11-09")
dt: datetime.datetime = datetime.datetime.fromisoformat("1989-11-09T18:53:00+01:00")
t: datetime.time = datetime.time.fromisoformat("18:53:00+01:00")
td: datetime.timedelta = datetime.timedelta(days=11, minutes=11)
@pytest.fixture
def test_state() -> TestState:
"""A state.
Returns:
A test state.
"""
return TestState() # type: ignore
@pytest.fixture
def child_state(test_state) -> ChildState:
"""A child state.
Args:
test_state: A test state.
Returns:
A test child state.
"""
child_state = test_state.get_substate([ChildState.get_name()])
assert child_state is not None
return child_state
@pytest.fixture
def child_state2(test_state) -> ChildState2:
"""A second child state.
Args:
test_state: A test state.
Returns:
A second test child state.
"""
child_state2 = test_state.get_substate([ChildState2.get_name()])
assert child_state2 is not None
return child_state2
@pytest.fixture
def grandchild_state(child_state) -> GrandchildState:
"""A state.
Args:
child_state: A child state.
Returns:
A test state.
"""
grandchild_state = child_state.get_substate([GrandchildState.get_name()])
assert grandchild_state is not None
return grandchild_state
def test_base_class_vars(test_state):
"""Test that the class vars are set correctly.
Args:
test_state: A state.
"""
fields = test_state.get_fields()
cls = type(test_state)
for field in fields:
if field in test_state.get_skip_vars():
continue
prop = getattr(cls, field)
assert isinstance(prop, Var)
assert prop._js_expr.split(".")[-1] == field
assert cls.num1._var_type is int
assert cls.num2._var_type is float
assert cls.key._var_type is str
def test_computed_class_var(test_state):
"""Test that the class computed vars are set correctly.
Args:
test_state: A state.
"""
cls = type(test_state)
vars = [(prop._js_expr, prop._var_type) for prop in cls.computed_vars.values()]
assert ("sum", float) in vars
assert ("upper", str) in vars
def test_class_vars(test_state):
"""Test that the class vars are set correctly.
Args:
test_state: A state.
"""
cls = type(test_state)
assert cls.vars.keys() == {
"router",
"num1",
"num2",
"key",
"map_key",
"array",
"mapping",
"obj",
"complex",
"sum",
"upper",
"fig",
"dt",
"asynctest",
}
def test_event_handlers(test_state):
"""Test that event handler is set correctly.
Args:
test_state: A state.
"""
expected_keys = (
"do_something",
"set_array",
"set_complex",
"set_fig",
"set_key",
"set_mapping",
"set_num1",
"set_num2",
"set_obj",
)
cls = type(test_state)
assert all(key in cls.event_handlers for key in expected_keys)
def test_default_value(test_state):
"""Test that the default value of a var is correct.
Args:
test_state: A state.
"""
assert test_state.num1 == 0
assert test_state.num2 == 3.14
assert test_state.key == ""
assert test_state.sum == 3.14
assert test_state.upper == ""
def test_computed_vars(test_state):
"""Test that the computed var is computed correctly.
Args:
test_state: A state.
"""
test_state.num1 = 1
test_state.num2 = 4
assert test_state.sum == 5
test_state.key = "hello world"
assert test_state.upper == "HELLO WORLD"
def test_dict(test_state: TestState):
"""Test that the dict representation of a state is correct.
Args:
test_state: A state.
"""
substates = {
test_state.get_full_name(),
ChildState.get_full_name(),
GrandchildState.get_full_name(),
ChildState2.get_full_name(),
GrandchildState2.get_full_name(),
ChildState3.get_full_name(),
GrandchildState3.get_full_name(),
}
test_state_dict = test_state.dict()
assert set(test_state_dict) == substates
assert set(test_state_dict[test_state.get_name()]) == set(test_state.vars)
assert set(test_state.dict(include_computed=False)[test_state.get_name()]) == set(
test_state.base_vars
)
def test_default_setters(test_state):
"""Test that we can set default values.
Args:
test_state: A state.
"""
for prop_name in test_state.base_vars:
# Each base var should have a default setter.
assert hasattr(test_state, f"set_{prop_name}")
def test_class_indexing_with_vars():
"""Test that we can index into a state var with another var."""
prop = TestState.array[TestState.num1]
assert str(prop) == f"{TestState.get_name()}.array.at({TestState.get_name()}.num1)"
prop = TestState.mapping["a"][TestState.num1]
assert (
str(prop)
== f'{TestState.get_name()}.mapping["a"].at({TestState.get_name()}.num1)'
)
prop = TestState.mapping[TestState.map_key]
assert (
str(prop) == f"{TestState.get_name()}.mapping[{TestState.get_name()}.map_key]"
)
def test_class_attributes():
"""Test that we can get class attributes."""
prop = TestState.obj.prop1
assert str(prop) == f'{TestState.get_name()}.obj["prop1"]'
prop = TestState.complex[1].prop1
assert str(prop) == f'{TestState.get_name()}.complex[1]["prop1"]'
def test_get_parent_state():
"""Test getting the parent state."""
assert TestState.get_parent_state() is None
assert ChildState.get_parent_state() == TestState
assert ChildState2.get_parent_state() == TestState
assert GrandchildState.get_parent_state() == ChildState
def test_get_substates():
"""Test getting the substates."""
assert TestState.get_substates() == {ChildState, ChildState2, ChildState3}
assert ChildState.get_substates() == {GrandchildState}
assert ChildState2.get_substates() == {GrandchildState2}
assert GrandchildState.get_substates() == set()
assert GrandchildState2.get_substates() == set()
def test_get_name():
"""Test getting the name of a state."""
assert TestState.get_name() == "tests___units___test_state____test_state"
assert ChildState.get_name() == "tests___units___test_state____child_state"
assert ChildState2.get_name() == "tests___units___test_state____child_state2"
assert (
GrandchildState.get_name() == "tests___units___test_state____grandchild_state"
)
def test_get_full_name():
"""Test getting the full name."""
assert TestState.get_full_name() == "tests___units___test_state____test_state"
assert (
ChildState.get_full_name()
== "tests___units___test_state____test_state.tests___units___test_state____child_state"
)
assert (
ChildState2.get_full_name()
== "tests___units___test_state____test_state.tests___units___test_state____child_state2"
)
assert (
GrandchildState.get_full_name()
== "tests___units___test_state____test_state.tests___units___test_state____child_state.tests___units___test_state____grandchild_state"
)
def test_get_class_substate():
"""Test getting the substate of a class."""
assert TestState.get_class_substate((ChildState.get_name(),)) == ChildState
assert TestState.get_class_substate((ChildState2.get_name(),)) == ChildState2
assert (
ChildState.get_class_substate((GrandchildState.get_name(),)) == GrandchildState
)
assert (
TestState.get_class_substate(
(ChildState.get_name(), GrandchildState.get_name())
)
== GrandchildState
)
with pytest.raises(ValueError):
TestState.get_class_substate(("invalid_child",))
with pytest.raises(ValueError):
TestState.get_class_substate(
(
ChildState.get_name(),
"invalid_child",
)
)
def test_get_class_var():
"""Test getting the var of a class."""
assert TestState.get_class_var(("num1",)).equals(TestState.num1)
assert TestState.get_class_var(("num2",)).equals(TestState.num2)
assert ChildState.get_class_var(("value",)).equals(ChildState.value)
assert GrandchildState.get_class_var(("value2",)).equals(GrandchildState.value2)
assert TestState.get_class_var((ChildState.get_name(), "value")).equals(
ChildState.value
)
assert TestState.get_class_var(
(ChildState.get_name(), GrandchildState.get_name(), "value2")
).equals(
GrandchildState.value2,
)
assert ChildState.get_class_var((GrandchildState.get_name(), "value2")).equals(
GrandchildState.value2,
)
with pytest.raises(ValueError):
TestState.get_class_var(("invalid_var",))
with pytest.raises(ValueError):
TestState.get_class_var(
(
ChildState.get_name(),
"invalid_var",
)
)
def test_set_class_var():
"""Test setting the var of a class."""
with pytest.raises(AttributeError):
TestState.num3 # type: ignore
TestState._set_var(Var(_js_expr="num3", _var_type=int)._var_set_state(TestState))
var = TestState.num3 # type: ignore
assert var._js_expr == TestState.get_full_name() + ".num3"
assert var._var_type is int
assert var._var_state == TestState.get_full_name()
def test_set_parent_and_substates(test_state, child_state, grandchild_state):
"""Test setting the parent and substates.
Args:
test_state: A state.
child_state: A child state.
grandchild_state: A grandchild state.
"""
assert len(test_state.substates) == 3
assert set(test_state.substates) == {
ChildState.get_name(),
ChildState2.get_name(),
ChildState3.get_name(),
}
assert child_state.parent_state == test_state
assert len(child_state.substates) == 1
assert set(child_state.substates) == {GrandchildState.get_name()}
assert grandchild_state.parent_state == child_state
assert len(grandchild_state.substates) == 0
def test_get_child_attribute(test_state, child_state, child_state2, grandchild_state):
"""Test getting the attribute of a state.
Args:
test_state: A state.
child_state: A child state.
child_state2: A child state.
grandchild_state: A grandchild state.
"""
assert test_state.num1 == 0
assert child_state.value == ""
assert child_state2.value == ""
assert child_state.count == 23
assert grandchild_state.value2 == ""
with pytest.raises(AttributeError):
test_state.invalid
with pytest.raises(AttributeError):
test_state.child_state.invalid
with pytest.raises(AttributeError):
test_state.child_state.grandchild_state.invalid
def test_set_child_attribute(test_state, child_state, grandchild_state):
"""Test setting the attribute of a state.
Args:
test_state: A state.
child_state: A child state.
grandchild_state: A grandchild state.
"""
test_state.num1 = 10
assert test_state.num1 == 10
assert child_state.num1 == 10
assert grandchild_state.num1 == 10
grandchild_state.num1 = 5
assert test_state.num1 == 5
assert child_state.num1 == 5
assert grandchild_state.num1 == 5
child_state.value = "test"
assert child_state.value == "test"
assert grandchild_state.value == "test"
grandchild_state.value = "test2"
assert child_state.value == "test2"
assert grandchild_state.value == "test2"
grandchild_state.value2 = "test3"
assert grandchild_state.value2 == "test3"
def test_get_substate(test_state, child_state, child_state2, grandchild_state):
"""Test getting the substate of a state.
Args:
test_state: A state.
child_state: A child state.
child_state2: A child state.
grandchild_state: A grandchild state.
"""
assert test_state.get_substate((ChildState.get_name(),)) == child_state
assert test_state.get_substate((ChildState2.get_name(),)) == child_state2
assert (
test_state.get_substate((ChildState.get_name(), GrandchildState.get_name()))
== grandchild_state
)
assert child_state.get_substate((GrandchildState.get_name(),)) == grandchild_state
with pytest.raises(ValueError):
test_state.get_substate(("invalid",))
with pytest.raises(ValueError):
test_state.get_substate((ChildState.get_name(), "invalid"))
with pytest.raises(ValueError):
test_state.get_substate(
(ChildState.get_name(), GrandchildState.get_name(), "invalid")
)
def test_set_dirty_var(test_state):
"""Test changing state vars marks the value as dirty.
Args:
test_state: A state.
"""
# Initially there should be no dirty vars.
assert test_state.dirty_vars == set()
# Setting a var should mark it as dirty.
test_state.num1 = 1
assert test_state.dirty_vars == {"num1", "sum"}
# Setting another var should mark it as dirty.
test_state.num2 = 2
assert test_state.dirty_vars == {"num1", "num2", "sum"}
# Cleaning the state should remove all dirty vars.
test_state._clean()
assert test_state.dirty_vars == set()
def test_set_dirty_substate(
test_state: TestState,
child_state: ChildState,
child_state2: ChildState2,
grandchild_state: GrandchildState,
):
"""Test changing substate vars marks the value as dirty.
Args:
test_state: A state.
child_state: A child state.
child_state2: A child state.
grandchild_state: A grandchild state.
"""
# Initially there should be no dirty vars.
assert test_state.dirty_vars == set()
assert child_state.dirty_vars == set()
assert child_state2.dirty_vars == set()
assert grandchild_state.dirty_vars == set()
# Setting a var should mark it as dirty.
child_state.value = "test"
assert child_state.dirty_vars == {"value"}
assert test_state.dirty_substates == {ChildState.get_name()}
assert child_state.dirty_substates == set()
# Cleaning the parent state should remove the dirty substate.
test_state._clean()
assert test_state.dirty_substates == set()
assert child_state.dirty_vars == set()
# Setting a var on the grandchild should bubble up.
grandchild_state.value2 = "test2"
assert child_state.dirty_substates == {GrandchildState.get_name()}
assert test_state.dirty_substates == {ChildState.get_name()}
# Cleaning the middle state should keep the parent state dirty.
child_state._clean()
assert test_state.dirty_substates == {ChildState.get_name()}
assert child_state.dirty_substates == set()
assert grandchild_state.dirty_vars == set()
def test_reset(test_state, child_state):
"""Test resetting the state.
Args:
test_state: A state.
child_state: A child state.
"""
# Set some values.
test_state.num1 = 1
test_state.num2 = 2
test_state._backend = 3
child_state.value = "test"
# Reset the state.
test_state.reset()
# The values should be reset.
assert test_state.num1 == 0
assert test_state.num2 == 3.14
assert test_state._backend == 0
assert child_state.value == ""
expected_dirty_vars = {
"num1",
"num2",
"obj",
"upper",
"complex",
"fig",
"key",
"sum",
"array",
"map_key",
"mapping",
"dt",
"_backend",
"asynctest",
}
# The dirty vars should be reset.
assert test_state.dirty_vars == expected_dirty_vars
assert child_state.dirty_vars == {"count", "value"}
# The dirty substates should be reset.
assert test_state.dirty_substates == {
ChildState.get_name(),
ChildState2.get_name(),
ChildState3.get_name(),
}
@pytest.mark.asyncio
async def test_process_event_simple(test_state):
"""Test processing an event.
Args:
test_state: A state.
"""
assert test_state.num1 == 0
event = Event(token="t", name="set_num1", payload={"value": 69})
update = await test_state._process(event).__anext__()
# The event should update the value.
assert test_state.num1 == 69
# The delta should contain the changes, including computed vars.
# assert update.delta == {"test_state": {"num1": 69, "sum": 72.14}}
assert update.delta == {
TestState.get_full_name(): {"num1": 69, "sum": 72.14, "upper": ""},
GrandchildState3.get_full_name(): {"computed": ""},
}
assert update.events == []
@pytest.mark.asyncio
async def test_process_event_substate(test_state, child_state, grandchild_state):
"""Test processing an event on a substate.
Args:
test_state: A state.
child_state: A child state.
grandchild_state: A grandchild state.
"""
# Events should bubble down to the substate.
assert child_state.value == ""
assert child_state.count == 23
event = Event(
token="t",
name=f"{ChildState.get_name()}.change_both",
payload={"value": "hi", "count": 12},
)
update = await test_state._process(event).__anext__()
assert child_state.value == "HI"
assert child_state.count == 24
assert update.delta == {
TestState.get_full_name(): {"sum": 3.14, "upper": ""},
ChildState.get_full_name(): {"value": "HI", "count": 24},
GrandchildState3.get_full_name(): {"computed": ""},
}
test_state._clean()
# Test with the granchild state.
assert grandchild_state.value2 == ""
event = Event(
token="t",
name=f"{GrandchildState.get_full_name()}.set_value2",
payload={"value": "new"},
)
update = await test_state._process(event).__anext__()
assert grandchild_state.value2 == "new"
assert update.delta == {
TestState.get_full_name(): {"sum": 3.14, "upper": ""},
GrandchildState.get_full_name(): {"value2": "new"},
GrandchildState3.get_full_name(): {"computed": ""},
}
@pytest.mark.asyncio
async def test_process_event_generator():
"""Test event handlers that generate multiple updates."""
gen_state = GenState() # type: ignore
event = Event(
token="t",
name="go",
payload={"c": 5},
)
gen = gen_state._process(event)
count = 0
async for update in gen:
count += 1
if count == 6:
assert update.delta == {}
assert update.final
else:
assert gen_state.value == count
assert update.delta == {
GenState.get_full_name(): {"value": count},
}
assert not update.final
assert count == 6
def test_get_client_token(test_state, router_data):
"""Test that the token obtained from the router_data is correct.
Args:
test_state: The test state.
router_data: The router data fixture.
"""
test_state.router = RouterData(router_data)
assert (
test_state.router.session.client_token == "b181904c-3953-4a79-dc18-ae9518c22f05"
)
def test_get_sid(test_state, router_data):
"""Test getting session id.
Args:
test_state: A state.
router_data: The router data fixture.
"""
test_state.router = RouterData(router_data)
assert test_state.router.session.session_id == "9fpxSzPb9aFMb4wFAAAH"
def test_get_headers(test_state, router_data, router_data_headers):
"""Test getting client headers.
Args:
test_state: A state.
router_data: The router data fixture.
router_data_headers: The expected headers.
"""
print(router_data_headers)
test_state.router = RouterData(router_data)
print(test_state.router.headers)
assert dataclasses.asdict(test_state.router.headers) == {
format.to_snake_case(k): v for k, v in router_data_headers.items()
}
def test_get_client_ip(test_state, router_data):
"""Test getting client IP.
Args:
test_state: A state.
router_data: The router data fixture.
"""
test_state.router = RouterData(router_data)
assert test_state.router.session.client_ip == "127.0.0.1"
def test_get_current_page(test_state):
assert test_state.router.page.path == ""
route = "mypage/subpage"
test_state.router = RouterData({RouteVar.PATH: route})
assert test_state.router.page.path == route
def test_get_query_params(test_state):
assert test_state.router.page.params == {}
params = {"p1": "a", "p2": "b"}
test_state.router = RouterData({RouteVar.QUERY: params})
assert dict(test_state.router.page.params) == params
def test_add_var():
class DynamicState(BaseState):
pass
ds1 = DynamicState()
assert "dynamic_int" not in ds1.__dict__
assert not hasattr(ds1, "dynamic_int")
ds1.add_var("dynamic_int", int, 42)
# Existing instances get the BaseVar
assert ds1.dynamic_int.equals(DynamicState.dynamic_int) # type: ignore
# New instances get an actual value with the default
assert DynamicState().dynamic_int == 42
ds1.add_var("dynamic_list", List[int], [5, 10])
assert ds1.dynamic_list.equals(DynamicState.dynamic_list) # type: ignore
ds2 = DynamicState()
assert ds2.dynamic_list == [5, 10]
ds2.dynamic_list.append(15)
assert ds2.dynamic_list == [5, 10, 15]
assert DynamicState().dynamic_list == [5, 10]
ds1.add_var("dynamic_dict", Dict[str, int], {"k1": 5, "k2": 10})
assert ds1.dynamic_dict.equals(DynamicState.dynamic_dict) # type: ignore
assert ds2.dynamic_dict.equals(DynamicState.dynamic_dict) # type: ignore
assert DynamicState().dynamic_dict == {"k1": 5, "k2": 10}
assert DynamicState().dynamic_dict == {"k1": 5, "k2": 10}
def test_add_var_default_handlers(test_state):
test_state.add_var("rand_int", int, 10)
assert "set_rand_int" in test_state.event_handlers
assert isinstance(test_state.event_handlers["set_rand_int"], EventHandler)
class InterdependentState(BaseState):
"""A state with 3 vars and 3 computed vars.
x: a variable that no computed var depends on
v1: a varable that one computed var directly depeneds on
_v2: a backend variable that one computed var directly depends on
v1x2: a computed var that depends on v1
v2x2: a computed var that depends on backend var _v2
v1x2x2: a computed var that depends on computed var v1x2
"""
x: int = 0
v1: int = 0
_v2: int = 1
@rx.var(cache=True)
def v1x2(self) -> int:
"""Depends on var v1.
Returns:
Var v1 multiplied by 2
"""
return self.v1 * 2
@rx.var(cache=True)
def v2x2(self) -> int:
"""Depends on backend var _v2.