-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathtest_memo.py
More file actions
1897 lines (1453 loc) ยท 66.9 KB
/
Copy pathtest_memo.py
File metadata and controls
1897 lines (1453 loc) ยท 66.9 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
"""Tests for rx.memo support."""
from __future__ import annotations
import inspect
from types import SimpleNamespace
from typing import Any, cast
from unittest.mock import patch
import pytest
from reflex_base.components.component import Component
from reflex_base.components.memo import (
_SPECS,
DEFAULT_MEMO_WRAPPER,
EMPTY_VAR_COMPONENT,
MEMOS,
MemoComponent,
MemoComponentDefinition,
MemoFunctionDefinition,
MemoParam,
MemoParamKind,
_analyze_params,
_LazyBody,
_MemoCallBinding,
_reregister_used_memo,
_strip_optional,
create_passthrough_component_memo,
materialize_registered_memo_bodies,
)
from reflex_base.event import EventChain, EventHandler, no_args_event_spec
from reflex_base.style import Style
from reflex_base.utils import console, memo_paths
from reflex_base.utils import format as format_utils
from reflex_base.utils.exceptions import ReflexError
from reflex_base.utils.imports import ImportVar
from reflex_base.vars import VarData
from reflex_base.vars.base import Var
from reflex_base.vars.function import FunctionStringVar, FunctionVar
import reflex as rx
from reflex.compiler import compiler
from reflex.compiler import utils as compiler_utils
@pytest.fixture(autouse=True)
def _restore_memo_registries(preserve_memo_registries):
"""Autouse wrapper around the shared preserve_memo_registries fixture."""
def test_var_returning_memo():
"""Var-returning memos should behave like imported function vars."""
@rx.memo
def format_price(amount: rx.Var[int], currency: rx.Var[str]) -> rx.Var[str]:
return currency.to(str) + ": $" + amount.to(str)
price = Var(_js_expr="price", _var_type=int)
currency = Var(_js_expr="currency", _var_type=str)
sym = memo_paths.mirrored_symbol("format_price", __name__)
assert (
str(format_price(amount=price, currency=currency))
== f"({sym}(price, currency))"
)
assert (
str(format_price.call(amount=price, currency=currency))
== f"({sym}(price, currency))"
)
assert isinstance(format_price._as_var(), FunctionVar)
definition = MEMOS["format_price", __name__]
assert isinstance(definition, MemoFunctionDefinition)
assert (
str(definition.function) == '((amount, currency) => ((currency+": $")+amount))'
)
with pytest.raises(TypeError, match="only accepts keyword props"):
format_price(price, currency)
def test_component_returning_memo_with_children_and_rest():
"""Component-returning memos should accept positional children and forwarded props."""
@rx.memo
def my_card(
children: rx.Var[rx.Component],
rest: rx.RestProp,
*,
title: rx.Var[str],
) -> rx.Component:
return rx.box(
rx.heading(title),
children,
rest,
)
component = my_card(
rx.text("child 1"),
rx.text("child 2"),
title="Hello",
foo="extra",
class_name="extra",
)
component_again = my_card(title="World")
sym = memo_paths.mirrored_symbol("MyCard", __name__)
assert isinstance(component, MemoComponent)
assert len(component.children) == 2
assert component.get_props() == ("title", "foo")
assert type(component) is type(component_again)
assert type(component).tag == sym
assert type(component).get_fields()["tag"].default == sym
rendered = component.render()
assert rendered["name"] == sym
assert 'title:"Hello"' in rendered["props"]
assert 'foo:"extra"' in rendered["props"]
assert 'className:"extra"' in rendered["props"]
definition = MEMOS["MyCard", __name__]
assert isinstance(definition, MemoComponentDefinition)
assert any(str(prop) == "rest" for prop in definition.component.special_props)
files, _ = compiler.compile_memo_components(tuple(MEMOS.values()))
code = "\n".join(c for _, c in files)
assert f"export const {sym} = memo(" in code
assert "({children, title:title" in code
assert "...rest" in code
assert "jsx(RadixThemesBox,{...rest}" in code
def test_component_returning_memo_accepts_component_var_result():
"""Component-returning memos should accept component-typed var results."""
@rx.memo
def conditional_slot(
show: rx.Var[bool],
first: rx.Var[rx.Component],
second: rx.Var[rx.Component],
) -> rx.Var[rx.Component]:
return rx.cond(show, first, second)
definition = MEMOS["ConditionalSlot", __name__]
assert isinstance(definition, MemoComponentDefinition)
assert definition.component.render() == {
"contents": "(showRxMemo ? firstRxMemo : secondRxMemo)"
}
sym = memo_paths.mirrored_symbol("ConditionalSlot", __name__)
files, _ = compiler.compile_memo_components(tuple(MEMOS.values()))
code = "\n".join(c for _, c in files)
assert f"export const {sym} = memo(" in code
assert "({show:showRxMemo" in code
assert "(showRxMemo ? firstRxMemo : secondRxMemo)" in code
def test_var_returning_memo_with_rest_props():
"""Var-returning memos should capture extra keyword args into RestProp."""
@rx.memo
def merge_styles(
base: rx.Var[dict[str, str]],
overrides: rx.RestProp,
) -> rx.Var[Any]:
return base.to(dict).merge(overrides)
base = Var(_js_expr="base", _var_type=dict[str, str])
merged = merge_styles(base=base, color="red", class_name="primary")
assert "merge_styles" in str(merged)
assert '["base"] : base' in str(merged)
assert '["color"] : "red"' in str(merged)
assert '["className"] : "primary"' in str(merged)
sym = memo_paths.mirrored_symbol("merge_styles", __name__)
files, _ = compiler.compile_memo_components(tuple(MEMOS.values()))
code = "\n".join(c for _, c in files)
assert (
f"export const {sym} = (({{base, ...overrides}}) => ({{...base, ...overrides}}));"
in code
)
with pytest.raises(TypeError, match="Do not pass `overrides=` directly"):
merge_styles(base=base, overrides={"color": "red"})
def test_component_returning_memo_with_only_rest():
"""Component-returning memos with only RestProp should emit valid JSX (#6443)."""
@rx.memo
def hover_trigger(rest: rx.RestProp) -> rx.Component:
return rx.text("hover me", rest)
files, _ = compiler.compile_memo_components(tuple(MEMOS.values()))
code = "\n".join(c for _, c in files)
assert "memo(({...rest})" in code
assert "({," not in code
def test_component_memo_rest_prop_merge_is_forwarded_as_rest_prop():
"""A merged ``RestProp`` stays a ``RestProp``.
Passing ``rest.merge({...})`` to another component must lift it onto that
component's ``special_props`` (a JSX spread), exactly like the bare ``rest``
โ not render it as a literal child.
"""
@rx.memo
def primary_button(rest: rx.RestProp, *, label: rx.Var[str]) -> rx.Component:
return rx.button(label, rest.merge({"className": "btn"}))
definition = MEMOS["PrimaryButton", __name__]
assert isinstance(definition, MemoComponentDefinition)
# The merged value is accepted as a RestProp: lifted onto special_props
# rather than wrapped as a child.
merged_specials = [
prop
for prop in definition.component.special_props
if isinstance(prop, rx.RestProp)
]
assert len(merged_specials) == 1
assert "...rest" in str(merged_specials[0])
files, _ = compiler.compile_memo_components(tuple(MEMOS.values()))
code = "\n".join(c for _, c in files)
# Spread into the button props, not emitted as a jsx child.
assert '{...({...rest, ...({ ["className"] : "btn" })})}' in code
def test_var_returning_memo_with_only_rest():
"""Var-returning memos with only RestProp should emit valid JS (#6443)."""
@rx.memo
def merge_only(overrides: rx.RestProp) -> rx.Var[Any]:
return overrides
files, _ = compiler.compile_memo_components(tuple(MEMOS.values()))
code = "\n".join(c for _, c in files)
assert "(({...overrides}) => overrides)" in code
assert "({," not in code
def test_var_returning_memo_with_children_and_rest():
"""Var-returning memos should accept positional children plus keyword props."""
@rx.memo
def label_slot(
children: rx.Var[rx.Component],
rest: rx.RestProp,
*,
label: rx.Var[str],
) -> rx.Var[str]:
return label
rendered = label_slot(
rx.text("child"),
label="Hello",
class_name="slot",
)
assert "label_slot" in str(rendered)
assert '["children"]' in str(rendered)
assert '["className"] : "slot"' in str(rendered)
sym = memo_paths.mirrored_symbol("label_slot", __name__)
files, _ = compiler.compile_memo_components(tuple(MEMOS.values()))
code = "\n".join(c for _, c in files)
assert f"export const {sym} = (({{children, label, ...rest}}) => label);" in code
def test_memo_munges_legacy_bare_type_param():
"""Legacy bare-type params should coerce to ``rx.Var[...]`` with a warning."""
with patch.object(console, "deprecate") as mock_deprecate:
@rx.memo
def bad_annotation(value: int) -> rx.Var[str]:
return rx.Var.create("x")
mock_deprecate.assert_called_once()
kwargs = mock_deprecate.call_args.kwargs
assert "bad_annotation" in kwargs["feature_name"]
assert "`value`" in kwargs["reason"]
definition = MEMOS["bad_annotation", __name__]
assert isinstance(definition, MemoFunctionDefinition)
(value_param,) = definition.params
assert value_param.kind is MemoParamKind.VALUE
# The bare ``int`` annotation is coerced into ``Var[int]``.
assert value_param.annotation == rx.Var[int]
def test_memo_munges_legacy_bare_type_params_for_component():
"""Component memos coerce legacy bare-type params and keep their defaults."""
with patch.object(console, "deprecate") as mock_deprecate:
@rx.memo
def legacy_card(title: str, count: int = 3) -> rx.Component:
return rx.box(rx.heading(title), rx.text(count))
mock_deprecate.assert_called_once()
reason = mock_deprecate.call_args.kwargs["reason"]
assert "`title`" in reason
assert "`count`" in reason
definition = MEMOS["LegacyCard", __name__]
assert isinstance(definition, MemoComponentDefinition)
assert {p.name: p.kind for p in definition.params} == {
"title": MemoParamKind.VALUE,
"count": MemoParamKind.VALUE,
}
count_param = next(p for p in definition.params if p.name == "count")
assert count_param.default == 3
# The munged props bind at instantiation; ``count`` falls back to its default.
component = legacy_card(title="Hi")
assert isinstance(component, MemoComponent)
def test_memo_does_not_warn_for_event_handler_param():
"""``rx.EventHandler`` params are recognized and must not be munged/warned."""
with patch.object(console, "deprecate") as mock_deprecate:
@rx.memo
def eh_only(event: rx.EventHandler) -> rx.Component:
return rx.button("click", on_click=event())
mock_deprecate.assert_not_called()
def test_memo_component_forwards_key_without_rest():
"""``key`` passes through a ``RestProp``-less memo and reaches the element.
``key`` is the one base ``Component`` prop that takes effect without an
``rx.RestProp``: React consumes it at the reconciliation layer, so the
legacy custom-component use case (notably setting ``key`` under
``rx.foreach``) keeps working. It is set as a real base field while a
deprecation warning points at ``rx.RestProp``. Props that only matter once
spread onto the rendered root (``id``, ``class_name``, ...) are *not*
forwardable here โ see ``test_memo_nonkey_base_props_require_rest_prop``.
"""
@rx.memo
def keyed_card(title: rx.Var[str]) -> rx.Component:
return rx.text(title)
with patch.object(console, "deprecate") as mock_deprecate:
component = keyed_card(title="hi", key="row-1")
mock_deprecate.assert_called_once()
feature_name = mock_deprecate.call_args.kwargs["feature_name"]
assert "keyed_card" in feature_name
assert "`key`" in feature_name
assert isinstance(component, MemoComponent)
# ``key`` lands as a real base field, not as a declared memo prop ...
assert component.key == "row-1"
assert component.get_props() == ("title",)
# ... and reaches the rendered element, where React reads it for list
# reconciliation.
assert 'key:"row-1"' in component.render()["props"]
def test_memo_component_key_deprecation_warns_once_across_instances():
"""Repeated ``key=`` instantiations warn once, without re-walking the stack.
Under ``rx.foreach`` a keyed memo is instantiated once per row. The warning
is deduped, but ``console.deprecate`` walks and path-resolves the call stack
*before* its dedupe check, so an ungated call site would pay that walk on
every row. The wrapper gates the call so only the first row reaches
``console.deprecate`` at all.
"""
@rx.memo
def row_card(title: rx.Var[str]) -> rx.Component:
return rx.text(title)
with patch.object(console, "deprecate") as mock_deprecate:
for i in range(5):
row_card(title="hi", key=f"row-{i}")
mock_deprecate.assert_called_once()
def test_memo_nonkey_base_props_require_rest_prop():
"""Non-``key`` base props raise without a ``RestProp`` rather than silently dropping.
Without a ``RestProp`` the compiled memo function destructures only its
declared params and emits no ``...rest`` spread, so ``id``/``class_name``/
``style``/``custom_attrs``/``ref`` set on the wrapper never reach the
rendered root โ they would be silently discarded. Reject them and point at
``rx.RestProp``, which genuinely forwards them (see
``test_memo_base_props_forward_to_root_via_rest_prop``).
"""
@rx.memo
def plain_card(title: rx.Var[str]) -> rx.Component:
return rx.text(title)
for prop, value in (
("id", "card-id"),
("class_name", "c"),
("style", {"color": "red"}),
("custom_attrs", {"data-x": "y"}),
("ref", "myref"),
):
with pytest.raises(TypeError, match=f"does not accept prop `{prop}`"):
plain_card(title="hi", **{prop: value})
def test_memo_nonkey_base_prop_dropped_from_render_without_rest():
"""Guard the *reason* non-``key`` base props are rejected: they don't render.
Bypass the call-site gate by setting ``class_name`` directly on a built memo
wrapper, then compile. The base prop shows up on the page-level element but
the memo's own function body neither destructures nor spreads it onto the
root โ proving a ``RestProp``-less memo cannot forward it, which is why the
call site rejects it.
"""
@rx.memo
def dropper(title: rx.Var[str]) -> rx.Component:
return rx.box(rx.text(title))
component = dropper(title="hi")
component.class_name = Var.create("leaks") # set past the call-site gate
files, _ = compiler.compile_memo_components(tuple(MEMOS.values()))
segments = memo_paths.module_to_mirrored_segments(__name__)
assert segments is not None
exp_path = compiler_utils.get_memo_module_path(segments)
code = next(c for path, c in files if path == exp_path)
# No rest capture, and the root Box gets an empty props object.
assert "...rest" not in code
assert "className" not in code
def test_memo_base_props_forward_to_root_via_rest_prop():
"""With an ``rx.RestProp``, base props reach the rendered root via JS ``...rest``.
This is the supported forwarding path the rejection message points users at.
"""
@rx.memo
def rest_card(rest: rx.RestProp, *, title: rx.Var[str]) -> rx.Component:
return rx.box(rx.text(title), rest)
component = rest_card(title="hi", class_name="c", id="card-id")
assert isinstance(component, MemoComponent)
files, _ = compiler.compile_memo_components(tuple(MEMOS.values()))
segments = memo_paths.module_to_mirrored_segments(__name__)
assert segments is not None
exp_path = compiler_utils.get_memo_module_path(segments)
code = next(c for path, c in files if path == exp_path)
# Undeclared props are captured in ``...rest`` and spread onto the root, so
# ``className``/``id`` actually reach the rendered element.
assert "...rest" in code
assert "{...rest}" in code
def test_memo_component_still_rejects_unknown_props_without_rest():
"""Props that are not base ``Component`` fields still raise without a ``RestProp``."""
@rx.memo
def plain_card(title: rx.Var[str]) -> rx.Component:
return rx.text(title)
with pytest.raises(TypeError, match="does not accept prop `bogus`"):
plain_card(title="hi", bogus="x")
def test_memo_component_rejects_unknown_even_alongside_base_props():
"""A genuinely-unknown prop raises even when a base prop is also present."""
@rx.memo
def mixed_card(title: rx.Var[str]) -> rx.Component:
return rx.text(title)
with pytest.raises(TypeError, match="does not accept prop `bogus`"):
mixed_card(title="hi", key="row-1", bogus="x")
def test_memo_component_rejects_structural_base_fields_without_rest():
"""Identity/internal base fields (``tag``, ``library``, ...) are not forwardable.
Overriding them would corrupt the memo's render, so they keep raising like
any other unknown prop rather than passing through.
"""
@rx.memo
def struct_card(title: rx.Var[str]) -> rx.Component:
return rx.text(title)
for prop in ("tag", "library", "event_triggers", "special_props"):
with pytest.raises(TypeError, match=f"does not accept prop `{prop}`"):
struct_card(title="hi", **{prop: "x"})
def test_analyze_params_strict_mode_rejects_bare_type():
"""Strict callers (``defaulted_params=None``) must still reject bare types."""
def bare(value: int) -> rx.Component:
return rx.text("x")
with pytest.raises(TypeError, match="must be annotated"):
_analyze_params(bare, for_component=True)
def test_is_memo_annotation_recognizes_supported_kinds():
"""``_is_memo_annotation`` gates which annotations are coerced to ``Var``."""
from reflex_base.components.memo import _is_memo_annotation
assert _is_memo_annotation(rx.Var[int]) is True
assert _is_memo_annotation(rx.RestProp) is True
assert _is_memo_annotation(rx.EventHandler) is True
assert (
_is_memo_annotation(rx.EventHandler[rx.event.passthrough_event_spec(str)])
is True
)
# Legacy bare types are not recognized -> they get munged + warned.
assert _is_memo_annotation(int) is False
assert _is_memo_annotation(str) is False
assert _is_memo_annotation(list[str]) is False
def test_memo_warns_on_missing_param_annotation():
"""Unannotated parameters should fall back to ``rx.Var[Any]`` with a warning."""
with patch.object(console, "deprecate") as mock_deprecate:
@rx.memo
def soft_missing(value) -> rx.Component:
return rx.text(value.to(str))
mock_deprecate.assert_called_once()
kwargs = mock_deprecate.call_args.kwargs
assert "soft_missing" in kwargs["feature_name"]
assert "`value`" in kwargs["reason"]
def test_memo_warns_on_missing_return_annotation():
"""A missing return annotation should default to ``rx.Component`` with a warning."""
with patch.object(console, "deprecate") as mock_deprecate:
@rx.memo
def soft_return():
return rx.box()
mock_deprecate.assert_called_once()
kwargs = mock_deprecate.call_args.kwargs
assert "soft_return" in kwargs["feature_name"]
assert "return annotation" in kwargs["reason"]
def test_memo_warning_suggests_component_return():
"""A missing return annotation warns with a constant `-> rx.Component` hint.
The suggestion no longer inspects the body's return value, so the warning
fires eagerly at decoration time even though the body itself runs lazily.
"""
evaluated = []
with patch.object(console, "deprecate") as mock_deprecate:
@rx.memo
def fragment_memo():
evaluated.append(1)
return rx.fragment(rx.text("x"))
mock_deprecate.assert_called_once()
reason = mock_deprecate.call_args.kwargs["reason"]
assert "-> rx.Component" in reason
# Emitting the warning did not require evaluating the body.
assert evaluated == []
def test_memo_component_body_not_evaluated_until_used():
"""A component memo's body must not run until the wrapper is instantiated."""
evaluated = []
@rx.memo
def lazy_box(value: rx.Var[str]) -> rx.Component:
evaluated.append(1)
return rx.box(value)
# Decoration registers the memo without running the body.
assert ("LazyBox", __name__) in MEMOS
assert evaluated == []
# First instantiation triggers a single evaluation...
component = lazy_box(value="hi")
assert isinstance(component, MemoComponent)
assert evaluated == [1]
# ...and subsequent uses reuse the cached body.
lazy_box(value="bye")
assert evaluated == [1]
def test_memo_function_body_not_evaluated_until_compiled():
"""A var memo's body must not run at decoration or when merely called."""
evaluated = []
@rx.memo
def lazy_join(value: rx.Var[str]) -> rx.Var[str]:
evaluated.append(1)
return value
assert ("lazy_join", __name__) in MEMOS
assert evaluated == []
# Calling a function memo references the imported var, not the body.
lazy_join(value=Var(_js_expr="x", _var_type=str))
assert evaluated == []
# The compiler (reading ``.function``) triggers a single evaluation.
definition = MEMOS["lazy_join", __name__]
assert isinstance(definition, MemoFunctionDefinition)
_ = definition.function
assert evaluated == [1]
_ = definition.function
assert evaluated == [1]
def test_lazy_body_placeholder_stands_in_for_reentrant_read():
"""A re-entrant read returns the placeholder, then caches the real body."""
cell: _LazyBody[str]
seen = []
def thunk() -> str:
seen.append(cell.get()) # re-enters while the thunk is running
return "real"
cell = _LazyBody(thunk, placeholder="placeholder")
assert cell.get() == "real"
assert seen == ["placeholder"]
# Cached afterwards; the thunk does not run again (``seen`` stays unchanged).
assert cell.get() == "real"
assert seen == ["placeholder"]
def test_lazy_body_reentrant_read_without_placeholder_raises():
"""A placeholder-less body that re-enters its own evaluation fails loudly."""
cell: _LazyBody[str]
def thunk() -> str:
return cell.get()
cell = _LazyBody(thunk)
with pytest.raises(RuntimeError, match="Re-entrant"):
cell.get()
@pytest.mark.parametrize(
("attr_name", "expected_type", "expected_render"),
[
("EMPTY_VAR_STR", str, '""'),
("EMPTY_VAR_INT", int, "0"),
("EMPTY_VAR_COMPONENT", Component, "(jsx(Fragment, ({})))"),
],
)
def test_empty_var_sentinels_are_public_typed_vars(
attr_name: str, expected_type: type, expected_render: str
):
"""`rx.EMPTY_VAR_*` defaults are public, correctly-typed empty Vars.
These back the documented `rx.Var[...]` memo prop defaults;
`EMPTY_VAR_COMPONENT` lives in `memo` (not `component`) to avoid a circular
import, but must still be reachable as `rx.EMPTY_VAR_COMPONENT`.
"""
sentinel = getattr(rx, attr_name)
assert isinstance(sentinel, Var)
assert sentinel._var_type is expected_type
assert str(sentinel) == expected_render
def test_empty_var_component_default_for_memo_children_slot():
"""`EMPTY_VAR_COMPONENT` works as the default for a memo `children` slot."""
@rx.memo
def slot(
children: rx.Var[rx.Component] = EMPTY_VAR_COMPONENT,
) -> rx.Component:
return rx.box(children)
# Omitting children falls back to the empty-component default.
assert isinstance(slot(), MemoComponent)
assert isinstance(slot(rx.text("hi")), MemoComponent)
def test_memo_warns_once_when_return_and_param_both_missing():
"""A function missing both should emit a single combined warning."""
with patch.object(console, "deprecate") as mock_deprecate:
@rx.memo
def soft_both(value):
return rx.text(value.to(str))
mock_deprecate.assert_called_once()
reason = mock_deprecate.call_args.kwargs["reason"]
assert "return annotation" in reason
assert "`value`" in reason
def test_memo_defaults_children_to_var_component():
"""An unannotated ``children`` parameter must default to ``Var[Component]``.
``Var[Any]`` would fail the children-name validation in ``_analyze_params``;
this guards the name-based special case.
"""
with patch.object(console, "deprecate") as mock_deprecate:
@rx.memo
def soft_children(children) -> rx.Component:
return rx.box(children)
mock_deprecate.assert_called_once()
definition = MEMOS["SoftChildren", __name__]
assert isinstance(definition, MemoComponentDefinition)
(children_param,) = definition.params
assert children_param.name == "children"
assert children_param.kind is MemoParamKind.CHILDREN
def test_memo_does_not_warn_when_fully_annotated():
"""Fully-annotated memos must not trigger the deprecation fallback."""
with patch.object(console, "deprecate") as mock_deprecate:
@rx.memo
def fully_typed(value: rx.Var[str]) -> rx.Component:
return rx.text(value)
mock_deprecate.assert_not_called()
def test_analyze_params_strict_mode_still_raises():
"""Internal callers (``defaulted_params=None``) must keep the strict contract."""
def missing_annotation(value) -> rx.Component:
return rx.text("x")
with pytest.raises(TypeError, match="Missing annotation"):
_analyze_params(missing_annotation, for_component=True)
def test_memo_rejects_invalid_children_annotation():
"""Component memos should validate the special children annotation."""
with pytest.raises(TypeError, match="children"):
@rx.memo
def bad_children(children: rx.Var[str]) -> rx.Component:
return rx.text(children)
def test_memo_rejects_multiple_rest_props():
"""Experimental memos should only allow a single RestProp."""
with pytest.raises(TypeError, match="only supports one"):
@rx.memo
def too_many_rest(
first: rx.RestProp,
second: rx.RestProp,
) -> rx.Var[Any]:
return first
def test_memo_rejects_component_and_function_name_collision():
"""Experimental memos should reject same exported name across kinds."""
@rx.memo
def foo_bar() -> rx.Component:
return rx.box()
assert ("FooBar", __name__) in MEMOS
with pytest.raises(ValueError, match=r"name collision.*FooBar"):
@rx.memo
def FooBar() -> rx.Var[str]:
return rx.Var.create("x")
def test_memo_rejects_component_export_name_collision():
"""Experimental memos should reject duplicate component export names."""
@rx.memo
def foo_bar() -> rx.Component:
return rx.box()
with pytest.raises(ValueError, match=r"name collision.*FooBar"):
@rx.memo
def foo__bar() -> rx.Component:
return rx.box()
def test_same_module_same_name_shadow_is_last_wins():
"""Two memos sharing a name in one module: the later definition wins.
This is plain Python shadowing โ a second ``def`` of the same name rebinds
the module global โ and the registry follows suit rather than erroring,
because a genuine shadow is indistinguishable from a hot-reload
re-registration (same type/python_name/module/qualname). The factory builds
two distinct function objects with identical identity metadata, exactly as
two module-level ``def shadow`` would.
"""
def _make_shadow(marker: str):
def shadow() -> rx.Component:
return rx.text(marker)
return shadow
rx.memo(_make_shadow("first-shadow-body"))
rx.memo(_make_shadow("second-shadow-body"))
shadow_keys = [k for k in MEMOS if isinstance(k, tuple) and k[0] == "Shadow"]
assert len(shadow_keys) == 1
definition = MEMOS["Shadow", __name__]
files, _ = compiler.compile_memo_components((definition,))
code = "\n".join(c for _, c in files)
assert "second-shadow-body" in code
assert "first-shadow-body" not in code
def test_memo_rejects_varargs():
"""Experimental memos should reject *args and **kwargs."""
with pytest.raises(TypeError, match=r"\*args"):
@rx.memo
def bad_args(*values: rx.Var[str]) -> rx.Var[str]:
return rx.Var.create("x")
with pytest.raises(TypeError, match=r"\*\*kwargs"):
@rx.memo
def bad_kwargs(**values: rx.Var[str]) -> rx.Var[str]:
return rx.Var.create("x")
def test_component_memo_rejects_invalid_positional_usage():
"""Component memos should only accept positional children."""
@rx.memo
def title_card(*, title: rx.Var[str]) -> rx.Component:
return rx.box(rx.heading(title))
with pytest.raises(TypeError, match="only accepts keyword props"):
title_card(rx.text("child"))
@rx.memo
def child_card(
children: rx.Var[rx.Component], *, title: rx.Var[str]
) -> rx.Component:
return rx.box(rx.heading(title), children)
with pytest.raises(TypeError, match="only accepts positional children"):
child_card("not a component", title="Hello")
def test_var_memo_rejects_invalid_positional_usage():
"""Var memos should also reserve positional arguments for children only."""
@rx.memo
def format_price(amount: rx.Var[int], currency: rx.Var[str]) -> rx.Var[str]:
return currency.to(str) + ": $" + amount.to(str)
price = Var(_js_expr="price", _var_type=int)
currency = Var(_js_expr="currency", _var_type=str)
with pytest.raises(TypeError, match="only accepts keyword props"):
format_price(price, currency)
@rx.memo
def child_label(
children: rx.Var[rx.Component], *, label: rx.Var[str]
) -> rx.Var[str]:
return label
with pytest.raises(TypeError, match="only accepts positional children"):
child_label("not a component", label="Hello")
def test_var_returning_memo_rejects_hooks():
"""Var-returning memos should reject hook-bearing expressions (lazily)."""
@rx.memo
def bad_hook(value: rx.Var[str]) -> rx.Var[str]:
return Var(
_js_expr="value",
_var_type=str,
_var_data=VarData(hooks={"const badHook = 1": None}),
)
# Decoration defers the body; reading ``.function`` surfaces the error.
definition = MEMOS["bad_hook", __name__]
assert isinstance(definition, MemoFunctionDefinition)
with pytest.raises(TypeError, match="cannot depend on hooks"):
_ = definition.function
def test_var_returning_memo_rejects_non_bundled_imports():
"""Var-returning memos should reject non-bundled imports (lazily)."""
@rx.memo
def bad_import(value: rx.Var[str]) -> rx.Var[str]:
return Var(
_js_expr="value",
_var_type=str,
_var_data=VarData(imports={"some-lib": [ImportVar(tag="x")]}),
)
# Decoration defers the body; reading ``.function`` surfaces the error.
definition = MEMOS["bad_import", __name__]
assert isinstance(definition, MemoFunctionDefinition)
with pytest.raises(TypeError, match="not bundled"):
_ = definition.function
def test_compile_memo_components_includes_functions_and_components():
"""The shared memo output should include both function and component memos."""
@rx.memo
def text_wrapper(title: rx.Var[str]) -> rx.Component:
return rx.text(title)
@rx.memo
def format_price(amount: rx.Var[int], currency: rx.Var[str]) -> rx.Var[str]:
return currency.to(str) + ": $" + amount.to(str)
@rx.memo
def my_card(children: rx.Var[rx.Component], *, title: rx.Var[str]) -> rx.Component:
return rx.box(rx.heading(title), children)
files, _ = compiler.compile_memo_components(tuple(MEMOS.values()))
code = "\n".join(c for _, c in files)
text_wrapper_sym = memo_paths.mirrored_symbol("TextWrapper", __name__)
format_price_sym = memo_paths.mirrored_symbol("format_price", __name__)
my_card_sym = memo_paths.mirrored_symbol("MyCard", __name__)
assert f"export const {text_wrapper_sym} = memo(" in code
assert f"export const {format_price_sym} =" in code
assert f"export const {my_card_sym} = memo(" in code
def test_compile_memo_components_groups_by_source_module():
"""Memos sharing a source module are concatenated into one mirrored file."""
@rx.memo
def grouped_first(title: rx.Var[str]) -> rx.Component:
return rx.text(title)
@rx.memo
def grouped_second(title: rx.Var[str]) -> rx.Component:
return rx.heading(title)
definition = MEMOS["GroupedFirst", __name__]
assert definition.source_module is not None
segments = memo_paths.module_to_mirrored_segments(definition.source_module)
assert segments is not None
files, _ = compiler.compile_memo_components(tuple(MEMOS.values()))
exp_path = compiler_utils.get_memo_module_path(segments)
grouped_files = [(path, code) for path, code in files if path == exp_path]
assert len(grouped_files) == 1
code = grouped_files[0][1]
first_sym = memo_paths.mirrored_symbol("GroupedFirst", __name__)
second_sym = memo_paths.mirrored_symbol("GroupedSecond", __name__)
assert f"export const {first_sym} = memo(" in code
assert f"export const {second_sym} = memo(" in code
# The merged module must carry imports its memos use, not just the
# framework-level ones added by the compiler.
assert "RadixThemesText" in code
assert "RadixThemesHeading" in code
def test_compile_memo_components_falls_back_when_no_source_module():
"""Memos with no source module emit to the legacy per-name path."""
legacy_definition = MemoComponentDefinition(
fn=lambda: None,
python_name="legacy_memo",
params=(),
export_name="LegacyMemo",
_component=_LazyBody.ready(rx.fragment()),
passthrough_hole_child=None,
)
files, _ = compiler.compile_memo_components((legacy_definition,))
exp_path = compiler._memo_component_file_path(
compiler_utils.get_memo_components_dir(), "LegacyMemo"
)
assert any(path == exp_path for path, _ in files)
def test_default_memo_wrapper_is_react_memo():
"""The default wrapper is React's ``memo``, carrying its own import."""
assert str(DEFAULT_MEMO_WRAPPER) == "memo"
var_data = DEFAULT_MEMO_WRAPPER._get_all_var_data()