test_var.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849
  1. import json
  2. import math
  3. import sys
  4. import typing
  5. from typing import Dict, List, Optional, Set, Tuple, Union, cast
  6. import pytest
  7. from pandas import DataFrame
  8. import reflex as rx
  9. from reflex.base import Base
  10. from reflex.constants.base import REFLEX_VAR_CLOSING_TAG, REFLEX_VAR_OPENING_TAG
  11. from reflex.state import BaseState
  12. from reflex.utils.exceptions import PrimitiveUnserializableToJSON
  13. from reflex.utils.imports import ImportVar
  14. from reflex.vars import VarData
  15. from reflex.vars.base import (
  16. ComputedVar,
  17. LiteralVar,
  18. Var,
  19. computed_var,
  20. var_operation,
  21. var_operation_return,
  22. )
  23. from reflex.vars.function import ArgsFunctionOperation, FunctionStringVar
  24. from reflex.vars.number import LiteralBooleanVar, LiteralNumberVar, NumberVar
  25. from reflex.vars.object import LiteralObjectVar, ObjectVar
  26. from reflex.vars.sequence import (
  27. ArrayVar,
  28. ConcatVarOperation,
  29. LiteralArrayVar,
  30. LiteralStringVar,
  31. )
  32. test_vars = [
  33. Var(_js_expr="prop1", _var_type=int),
  34. Var(_js_expr="key", _var_type=str),
  35. Var(_js_expr="value", _var_type=str)._var_set_state("state"),
  36. Var(_js_expr="local", _var_type=str)._var_set_state("state"),
  37. Var(_js_expr="local2", _var_type=str),
  38. ]
  39. class ATestState(BaseState):
  40. """Test state."""
  41. value: str
  42. dict_val: Dict[str, List] = {}
  43. @pytest.fixture
  44. def TestObj():
  45. class TestObj(Base):
  46. foo: int
  47. bar: str
  48. return TestObj
  49. @pytest.fixture
  50. def ParentState(TestObj):
  51. class ParentState(BaseState):
  52. foo: int
  53. bar: int
  54. @computed_var
  55. def var_without_annotation(self):
  56. return TestObj
  57. return ParentState
  58. @pytest.fixture
  59. def ChildState(ParentState, TestObj):
  60. class ChildState(ParentState):
  61. @computed_var
  62. def var_without_annotation(self):
  63. """This shadows ParentState.var_without_annotation.
  64. Returns:
  65. TestObj: Test object.
  66. """
  67. return TestObj
  68. return ChildState
  69. @pytest.fixture
  70. def GrandChildState(ChildState, TestObj):
  71. class GrandChildState(ChildState):
  72. @computed_var
  73. def var_without_annotation(self):
  74. """This shadows ChildState.var_without_annotation.
  75. Returns:
  76. TestObj: Test object.
  77. """
  78. return TestObj
  79. return GrandChildState
  80. @pytest.fixture
  81. def StateWithAnyVar(TestObj):
  82. class StateWithAnyVar(BaseState):
  83. @computed_var
  84. def var_without_annotation(self) -> typing.Any:
  85. return TestObj
  86. return StateWithAnyVar
  87. @pytest.fixture
  88. def StateWithCorrectVarAnnotation():
  89. class StateWithCorrectVarAnnotation(BaseState):
  90. @computed_var
  91. def var_with_annotation(self) -> str:
  92. return "Correct annotation"
  93. return StateWithCorrectVarAnnotation
  94. @pytest.fixture
  95. def StateWithWrongVarAnnotation(TestObj):
  96. class StateWithWrongVarAnnotation(BaseState):
  97. @computed_var
  98. def var_with_annotation(self) -> str:
  99. return TestObj
  100. return StateWithWrongVarAnnotation
  101. @pytest.fixture
  102. def StateWithInitialComputedVar():
  103. class StateWithInitialComputedVar(BaseState):
  104. @computed_var(initial_value="Initial value")
  105. def var_with_initial_value(self) -> str:
  106. return "Runtime value"
  107. return StateWithInitialComputedVar
  108. @pytest.fixture
  109. def ChildWithInitialComputedVar(StateWithInitialComputedVar):
  110. class ChildWithInitialComputedVar(StateWithInitialComputedVar):
  111. @computed_var(initial_value="Initial value")
  112. def var_with_initial_value_child(self) -> str:
  113. return "Runtime value"
  114. return ChildWithInitialComputedVar
  115. @pytest.fixture
  116. def StateWithRuntimeOnlyVar():
  117. class StateWithRuntimeOnlyVar(BaseState):
  118. @computed_var(initial_value=None)
  119. def var_raises_at_runtime(self) -> str:
  120. raise ValueError("So nicht, mein Freund")
  121. return StateWithRuntimeOnlyVar
  122. @pytest.fixture
  123. def ChildWithRuntimeOnlyVar(StateWithRuntimeOnlyVar):
  124. class ChildWithRuntimeOnlyVar(StateWithRuntimeOnlyVar):
  125. @computed_var(initial_value="Initial value")
  126. def var_raises_at_runtime_child(self) -> str:
  127. raise ValueError("So nicht, mein Freund")
  128. return ChildWithRuntimeOnlyVar
  129. @pytest.mark.parametrize(
  130. "prop,expected",
  131. zip(
  132. test_vars,
  133. [
  134. "prop1",
  135. "key",
  136. "state.value",
  137. "state.local",
  138. "local2",
  139. ],
  140. ),
  141. )
  142. def test_full_name(prop, expected):
  143. """Test that the full name of a var is correct.
  144. Args:
  145. prop: The var to test.
  146. expected: The expected full name.
  147. """
  148. assert str(prop) == expected
  149. @pytest.mark.parametrize(
  150. "prop,expected",
  151. zip(
  152. test_vars,
  153. ["prop1", "key", "state.value", "state.local", "local2"],
  154. ),
  155. )
  156. def test_str(prop, expected):
  157. """Test that the string representation of a var is correct.
  158. Args:
  159. prop: The var to test.
  160. expected: The expected string representation.
  161. """
  162. assert str(prop) == expected
  163. @pytest.mark.parametrize(
  164. "prop,expected",
  165. [
  166. (Var(_js_expr="p", _var_type=int), 0),
  167. (Var(_js_expr="p", _var_type=float), 0.0),
  168. (Var(_js_expr="p", _var_type=str), ""),
  169. (Var(_js_expr="p", _var_type=bool), False),
  170. (Var(_js_expr="p", _var_type=list), []),
  171. (Var(_js_expr="p", _var_type=dict), {}),
  172. (Var(_js_expr="p", _var_type=tuple), ()),
  173. (Var(_js_expr="p", _var_type=set), set()),
  174. ],
  175. )
  176. def test_default_value(prop, expected):
  177. """Test that the default value of a var is correct.
  178. Args:
  179. prop: The var to test.
  180. expected: The expected default value.
  181. """
  182. assert prop.get_default_value() == expected
  183. @pytest.mark.parametrize(
  184. "prop,expected",
  185. zip(
  186. test_vars,
  187. [
  188. "set_prop1",
  189. "set_key",
  190. "state.set_value",
  191. "state.set_local",
  192. "set_local2",
  193. ],
  194. ),
  195. )
  196. def test_get_setter(prop, expected):
  197. """Test that the name of the setter function of a var is correct.
  198. Args:
  199. prop: The var to test.
  200. expected: The expected name of the setter function.
  201. """
  202. assert prop.get_setter_name() == expected
  203. @pytest.mark.parametrize(
  204. "value,expected",
  205. [
  206. (None, Var(_js_expr="null", _var_type=None)),
  207. (1, Var(_js_expr="1", _var_type=int)),
  208. ("key", Var(_js_expr='"key"', _var_type=str)),
  209. (3.14, Var(_js_expr="3.14", _var_type=float)),
  210. ([1, 2, 3], Var(_js_expr="[1, 2, 3]", _var_type=List[int])),
  211. (
  212. {"a": 1, "b": 2},
  213. Var(_js_expr='({ ["a"] : 1, ["b"] : 2 })', _var_type=Dict[str, int]),
  214. ),
  215. ],
  216. )
  217. def test_create(value, expected):
  218. """Test the var create function.
  219. Args:
  220. value: The value to create a var from.
  221. expected: The expected name of the setter function.
  222. """
  223. prop = LiteralVar.create(value)
  224. assert prop.equals(expected) # type: ignore
  225. def test_create_type_error():
  226. """Test the var create function when inputs type error."""
  227. class ErrorType:
  228. pass
  229. value = ErrorType()
  230. with pytest.raises(TypeError):
  231. LiteralVar.create(value)
  232. def v(value) -> Var:
  233. return LiteralVar.create(value)
  234. def test_basic_operations(TestObj):
  235. """Test the var operations.
  236. Args:
  237. TestObj: The test object.
  238. """
  239. assert str(v(1) == v(2)) == "(1 === 2)"
  240. assert str(v(1) != v(2)) == "(1 !== 2)"
  241. assert str(LiteralNumberVar.create(1) < 2) == "(1 < 2)"
  242. assert str(LiteralNumberVar.create(1) <= 2) == "(1 <= 2)"
  243. assert str(LiteralNumberVar.create(1) > 2) == "(1 > 2)"
  244. assert str(LiteralNumberVar.create(1) >= 2) == "(1 >= 2)"
  245. assert str(LiteralNumberVar.create(1) + 2) == "(1 + 2)"
  246. assert str(LiteralNumberVar.create(1) - 2) == "(1 - 2)"
  247. assert str(LiteralNumberVar.create(1) * 2) == "(1 * 2)"
  248. assert str(LiteralNumberVar.create(1) / 2) == "(1 / 2)"
  249. assert str(LiteralNumberVar.create(1) // 2) == "Math.floor(1 / 2)"
  250. assert str(LiteralNumberVar.create(1) % 2) == "(1 % 2)"
  251. assert str(LiteralNumberVar.create(1) ** 2) == "(1 ** 2)"
  252. assert str(LiteralNumberVar.create(1) & v(2)) == "(1 && 2)"
  253. assert str(LiteralNumberVar.create(1) | v(2)) == "(1 || 2)"
  254. assert str(LiteralArrayVar.create([1, 2, 3])[0]) == "[1, 2, 3].at(0)"
  255. assert (
  256. str(LiteralObjectVar.create({"a": 1, "b": 2})["a"])
  257. == '({ ["a"] : 1, ["b"] : 2 })["a"]'
  258. )
  259. assert str(v("foo") == v("bar")) == '("foo" === "bar")'
  260. assert str(Var(_js_expr="foo") == Var(_js_expr="bar")) == "(foo === bar)"
  261. assert (
  262. str(LiteralVar.create("foo") == LiteralVar.create("bar")) == '("foo" === "bar")'
  263. )
  264. print(Var(_js_expr="foo").to(ObjectVar, TestObj)._var_set_state("state"))
  265. assert (
  266. str(
  267. Var(_js_expr="foo").to(ObjectVar, TestObj)._var_set_state("state").bar
  268. == LiteralVar.create("bar")
  269. )
  270. == '(state.foo["bar"] === "bar")'
  271. )
  272. assert (
  273. str(Var(_js_expr="foo").to(ObjectVar, TestObj)._var_set_state("state").bar)
  274. == 'state.foo["bar"]'
  275. )
  276. assert str(abs(LiteralNumberVar.create(1))) == "Math.abs(1)"
  277. assert str(LiteralArrayVar.create([1, 2, 3]).length()) == "[1, 2, 3].length"
  278. assert (
  279. str(LiteralArrayVar.create([1, 2]) + LiteralArrayVar.create([3, 4]))
  280. == "[...[1, 2], ...[3, 4]]"
  281. )
  282. # Tests for reverse operation
  283. assert (
  284. str(LiteralArrayVar.create([1, 2, 3]).reverse())
  285. == "[1, 2, 3].slice().reverse()"
  286. )
  287. assert (
  288. str(LiteralArrayVar.create(["1", "2", "3"]).reverse())
  289. == '["1", "2", "3"].slice().reverse()'
  290. )
  291. assert (
  292. str(Var(_js_expr="foo")._var_set_state("state").to(list).reverse())
  293. == "state.foo.slice().reverse()"
  294. )
  295. assert str(Var(_js_expr="foo").to(list).reverse()) == "foo.slice().reverse()"
  296. assert str(Var(_js_expr="foo", _var_type=str).js_type()) == "(typeof(foo))"
  297. @pytest.mark.parametrize(
  298. "var, expected",
  299. [
  300. (v([1, 2, 3]), "[1, 2, 3]"),
  301. (v(set([1, 2, 3])), "[1, 2, 3]"),
  302. (v(["1", "2", "3"]), '["1", "2", "3"]'),
  303. (
  304. Var(_js_expr="foo")._var_set_state("state").to(list),
  305. "state.foo",
  306. ),
  307. (Var(_js_expr="foo").to(list), "foo"),
  308. (v((1, 2, 3)), "[1, 2, 3]"),
  309. (v(("1", "2", "3")), '["1", "2", "3"]'),
  310. (
  311. Var(_js_expr="foo")._var_set_state("state").to(tuple),
  312. "state.foo",
  313. ),
  314. (Var(_js_expr="foo").to(tuple), "foo"),
  315. ],
  316. )
  317. def test_list_tuple_contains(var, expected):
  318. assert str(var.contains(1)) == f"{expected}.includes(1)"
  319. assert str(var.contains("1")) == f'{expected}.includes("1")'
  320. assert str(var.contains(v(1))) == f"{expected}.includes(1)"
  321. assert str(var.contains(v("1"))) == f'{expected}.includes("1")'
  322. other_state_var = Var(_js_expr="other", _var_type=str)._var_set_state("state")
  323. other_var = Var(_js_expr="other", _var_type=str)
  324. assert str(var.contains(other_state_var)) == f"{expected}.includes(state.other)"
  325. assert str(var.contains(other_var)) == f"{expected}.includes(other)"
  326. class Foo(rx.Base):
  327. """Foo class."""
  328. bar: int
  329. baz: str
  330. class Bar(rx.Base):
  331. """Bar class."""
  332. bar: str
  333. baz: str
  334. foo: int
  335. @pytest.mark.parametrize(
  336. ("var", "var_type"),
  337. (
  338. [
  339. (Var(_js_expr="", _var_type=Foo | Bar).guess_type(), Foo | Bar),
  340. (Var(_js_expr="", _var_type=Foo | Bar).guess_type().bar, Union[int, str]),
  341. ]
  342. if sys.version_info >= (3, 10)
  343. else []
  344. )
  345. + [
  346. (Var(_js_expr="", _var_type=Union[Foo, Bar]).guess_type(), Union[Foo, Bar]),
  347. (Var(_js_expr="", _var_type=Union[Foo, Bar]).guess_type().baz, str),
  348. (
  349. Var(_js_expr="", _var_type=Union[Foo, Bar]).guess_type().foo,
  350. Union[int, None],
  351. ),
  352. ],
  353. )
  354. def test_var_types(var, var_type):
  355. assert var._var_type == var_type
  356. @pytest.mark.parametrize(
  357. "var, expected",
  358. [
  359. (v("123"), json.dumps("123")),
  360. (Var(_js_expr="foo")._var_set_state("state").to(str), "state.foo"),
  361. (Var(_js_expr="foo").to(str), "foo"),
  362. ],
  363. )
  364. def test_str_contains(var, expected):
  365. assert str(var.contains("1")) == f'{expected}.includes("1")'
  366. assert str(var.contains(v("1"))) == f'{expected}.includes("1")'
  367. other_state_var = Var(_js_expr="other")._var_set_state("state").to(str)
  368. other_var = Var(_js_expr="other").to(str)
  369. assert str(var.contains(other_state_var)) == f"{expected}.includes(state.other)"
  370. assert str(var.contains(other_var)) == f"{expected}.includes(other)"
  371. assert (
  372. str(var.contains("1", "hello"))
  373. == f'{expected}.some(obj => obj["hello"] === "1")'
  374. )
  375. @pytest.mark.parametrize(
  376. "var, expected",
  377. [
  378. (v({"a": 1, "b": 2}), '({ ["a"] : 1, ["b"] : 2 })'),
  379. (Var(_js_expr="foo")._var_set_state("state").to(dict), "state.foo"),
  380. (Var(_js_expr="foo").to(dict), "foo"),
  381. ],
  382. )
  383. def test_dict_contains(var, expected):
  384. assert str(var.contains(1)) == f"{expected}.hasOwnProperty(1)"
  385. assert str(var.contains("1")) == f'{expected}.hasOwnProperty("1")'
  386. assert str(var.contains(v(1))) == f"{expected}.hasOwnProperty(1)"
  387. assert str(var.contains(v("1"))) == f'{expected}.hasOwnProperty("1")'
  388. other_state_var = Var(_js_expr="other")._var_set_state("state").to(str)
  389. other_var = Var(_js_expr="other").to(str)
  390. assert (
  391. str(var.contains(other_state_var)) == f"{expected}.hasOwnProperty(state.other)"
  392. )
  393. assert str(var.contains(other_var)) == f"{expected}.hasOwnProperty(other)"
  394. @pytest.mark.parametrize(
  395. "var",
  396. [
  397. Var(_js_expr="list", _var_type=List[int]).guess_type(),
  398. Var(_js_expr="tuple", _var_type=Tuple[int, int]).guess_type(),
  399. Var(_js_expr="str", _var_type=str).guess_type(),
  400. ],
  401. )
  402. def test_var_indexing_lists(var):
  403. """Test that we can index into str, list or tuple vars.
  404. Args:
  405. var : The str, list or tuple base var.
  406. """
  407. # Test basic indexing.
  408. assert str(var[0]) == f"{var._js_expr}.at(0)"
  409. assert str(var[1]) == f"{var._js_expr}.at(1)"
  410. # Test negative indexing.
  411. assert str(var[-1]) == f"{var._js_expr}.at(-1)"
  412. @pytest.mark.parametrize(
  413. "var, type_",
  414. [
  415. (Var(_js_expr="list", _var_type=List[int]).guess_type(), [int, int]),
  416. (
  417. Var(_js_expr="tuple", _var_type=Tuple[int, str]).guess_type(),
  418. [int, str],
  419. ),
  420. ],
  421. )
  422. def test_var_indexing_types(var, type_):
  423. """Test that indexing returns valid types.
  424. Args:
  425. var : The list, typle base var.
  426. type_ : The type on indexed object.
  427. """
  428. assert var[0]._var_type == type_[0]
  429. assert var[1]._var_type == type_[1]
  430. def test_var_indexing_str():
  431. """Test that we can index into str vars."""
  432. str_var = Var(_js_expr="str").to(str)
  433. # Test that indexing gives a type of Var[str].
  434. assert isinstance(str_var[0], Var)
  435. assert str_var[0]._var_type is str
  436. # Test basic indexing.
  437. assert str(str_var[0]) == "str.at(0)"
  438. assert str(str_var[1]) == "str.at(1)"
  439. # Test negative indexing.
  440. assert str(str_var[-1]) == "str.at(-1)"
  441. @pytest.mark.parametrize(
  442. "var",
  443. [
  444. (Var(_js_expr="foo", _var_type=int).guess_type()),
  445. (Var(_js_expr="bar", _var_type=float).guess_type()),
  446. ],
  447. )
  448. def test_var_replace_with_invalid_kwargs(var):
  449. with pytest.raises(TypeError) as excinfo:
  450. var._replace(_this_should_fail=True)
  451. assert "unexpected keyword argument" in str(excinfo.value)
  452. def test_computed_var_replace_with_invalid_kwargs():
  453. @computed_var(initial_value=1)
  454. def test_var(state) -> int:
  455. return 1
  456. with pytest.raises(TypeError) as excinfo:
  457. test_var._replace(_random_kwarg=True)
  458. assert "Unexpected keyword argument" in str(excinfo.value)
  459. @pytest.mark.parametrize(
  460. "var, index",
  461. [
  462. (Var(_js_expr="lst", _var_type=List[int]).guess_type(), [1, 2]),
  463. (
  464. Var(_js_expr="lst", _var_type=List[int]).guess_type(),
  465. {"name": "dict"},
  466. ),
  467. (Var(_js_expr="lst", _var_type=List[int]).guess_type(), {"set"}),
  468. (
  469. Var(_js_expr="lst", _var_type=List[int]).guess_type(),
  470. (
  471. 1,
  472. 2,
  473. ),
  474. ),
  475. (Var(_js_expr="lst", _var_type=List[int]).guess_type(), 1.5),
  476. (Var(_js_expr="lst", _var_type=List[int]).guess_type(), "str"),
  477. (
  478. Var(_js_expr="lst", _var_type=List[int]).guess_type(),
  479. Var(_js_expr="string_var", _var_type=str).guess_type(),
  480. ),
  481. (
  482. Var(_js_expr="lst", _var_type=List[int]).guess_type(),
  483. Var(_js_expr="float_var", _var_type=float).guess_type(),
  484. ),
  485. (
  486. Var(_js_expr="lst", _var_type=List[int]).guess_type(),
  487. Var(_js_expr="list_var", _var_type=List[int]).guess_type(),
  488. ),
  489. (
  490. Var(_js_expr="lst", _var_type=List[int]).guess_type(),
  491. Var(_js_expr="set_var", _var_type=Set[str]).guess_type(),
  492. ),
  493. (
  494. Var(_js_expr="lst", _var_type=List[int]).guess_type(),
  495. Var(_js_expr="dict_var", _var_type=Dict[str, str]).guess_type(),
  496. ),
  497. (Var(_js_expr="str", _var_type=str).guess_type(), [1, 2]),
  498. (Var(_js_expr="lst", _var_type=str).guess_type(), {"name": "dict"}),
  499. (Var(_js_expr="lst", _var_type=str).guess_type(), {"set"}),
  500. (
  501. Var(_js_expr="lst", _var_type=str).guess_type(),
  502. Var(_js_expr="string_var", _var_type=str).guess_type(),
  503. ),
  504. (
  505. Var(_js_expr="lst", _var_type=str).guess_type(),
  506. Var(_js_expr="float_var", _var_type=float).guess_type(),
  507. ),
  508. (Var(_js_expr="str", _var_type=Tuple[str]).guess_type(), [1, 2]),
  509. (
  510. Var(_js_expr="lst", _var_type=Tuple[str]).guess_type(),
  511. {"name": "dict"},
  512. ),
  513. (Var(_js_expr="lst", _var_type=Tuple[str]).guess_type(), {"set"}),
  514. (
  515. Var(_js_expr="lst", _var_type=Tuple[str]).guess_type(),
  516. Var(_js_expr="string_var", _var_type=str).guess_type(),
  517. ),
  518. (
  519. Var(_js_expr="lst", _var_type=Tuple[str]).guess_type(),
  520. Var(_js_expr="float_var", _var_type=float).guess_type(),
  521. ),
  522. ],
  523. )
  524. def test_var_unsupported_indexing_lists(var, index):
  525. """Test unsupported indexing throws a type error.
  526. Args:
  527. var: The base var.
  528. index: The base var index.
  529. """
  530. with pytest.raises(TypeError):
  531. var[index]
  532. @pytest.mark.parametrize(
  533. "var",
  534. [
  535. Var(_js_expr="lst", _var_type=List[int]).guess_type(),
  536. Var(_js_expr="tuple", _var_type=Tuple[int, int]).guess_type(),
  537. ],
  538. )
  539. def test_var_list_slicing(var):
  540. """Test that we can slice into str, list or tuple vars.
  541. Args:
  542. var : The str, list or tuple base var.
  543. """
  544. assert str(var[:1]) == f"{var._js_expr}.slice(undefined, 1)"
  545. assert str(var[1:]) == f"{var._js_expr}.slice(1, undefined)"
  546. assert str(var[:]) == f"{var._js_expr}.slice(undefined, undefined)"
  547. def test_str_var_slicing():
  548. """Test that we can slice into str vars."""
  549. str_var = Var(_js_expr="str").to(str)
  550. # Test that slicing gives a type of Var[str].
  551. assert isinstance(str_var[:1], Var)
  552. assert str_var[:1]._var_type is str
  553. # Test basic slicing.
  554. assert str(str_var[:1]) == 'str.split("").slice(undefined, 1).join("")'
  555. assert str(str_var[1:]) == 'str.split("").slice(1, undefined).join("")'
  556. assert str(str_var[:]) == 'str.split("").slice(undefined, undefined).join("")'
  557. assert str(str_var[1:2]) == 'str.split("").slice(1, 2).join("")'
  558. # Test negative slicing.
  559. assert str(str_var[:-1]) == 'str.split("").slice(undefined, -1).join("")'
  560. assert str(str_var[-1:]) == 'str.split("").slice(-1, undefined).join("")'
  561. assert str(str_var[:-2]) == 'str.split("").slice(undefined, -2).join("")'
  562. assert str(str_var[-2:]) == 'str.split("").slice(-2, undefined).join("")'
  563. def test_dict_indexing():
  564. """Test that we can index into dict vars."""
  565. dct = Var(_js_expr="dct").to(ObjectVar, Dict[str, str])
  566. # Check correct indexing.
  567. assert str(dct["a"]) == 'dct["a"]'
  568. assert str(dct["asdf"]) == 'dct["asdf"]'
  569. @pytest.mark.parametrize(
  570. "var, index",
  571. [
  572. (
  573. Var(_js_expr="dict", _var_type=Dict[str, str]).guess_type(),
  574. [1, 2],
  575. ),
  576. (
  577. Var(_js_expr="dict", _var_type=Dict[str, str]).guess_type(),
  578. {"name": "dict"},
  579. ),
  580. (
  581. Var(_js_expr="dict", _var_type=Dict[str, str]).guess_type(),
  582. {"set"},
  583. ),
  584. (
  585. Var(_js_expr="dict", _var_type=Dict[str, str]).guess_type(),
  586. (
  587. 1,
  588. 2,
  589. ),
  590. ),
  591. (
  592. Var(_js_expr="lst", _var_type=Dict[str, str]).guess_type(),
  593. Var(_js_expr="list_var", _var_type=List[int]).guess_type(),
  594. ),
  595. (
  596. Var(_js_expr="lst", _var_type=Dict[str, str]).guess_type(),
  597. Var(_js_expr="set_var", _var_type=Set[str]).guess_type(),
  598. ),
  599. (
  600. Var(_js_expr="lst", _var_type=Dict[str, str]).guess_type(),
  601. Var(_js_expr="dict_var", _var_type=Dict[str, str]).guess_type(),
  602. ),
  603. (
  604. Var(_js_expr="df", _var_type=DataFrame).guess_type(),
  605. [1, 2],
  606. ),
  607. (
  608. Var(_js_expr="df", _var_type=DataFrame).guess_type(),
  609. {"name": "dict"},
  610. ),
  611. (
  612. Var(_js_expr="df", _var_type=DataFrame).guess_type(),
  613. {"set"},
  614. ),
  615. (
  616. Var(_js_expr="df", _var_type=DataFrame).guess_type(),
  617. (
  618. 1,
  619. 2,
  620. ),
  621. ),
  622. (
  623. Var(_js_expr="df", _var_type=DataFrame).guess_type(),
  624. Var(_js_expr="list_var", _var_type=List[int]).guess_type(),
  625. ),
  626. (
  627. Var(_js_expr="df", _var_type=DataFrame).guess_type(),
  628. Var(_js_expr="set_var", _var_type=Set[str]).guess_type(),
  629. ),
  630. (
  631. Var(_js_expr="df", _var_type=DataFrame).guess_type(),
  632. Var(_js_expr="dict_var", _var_type=Dict[str, str]).guess_type(),
  633. ),
  634. ],
  635. )
  636. def test_var_unsupported_indexing_dicts(var, index):
  637. """Test unsupported indexing throws a type error.
  638. Args:
  639. var: The base var.
  640. index: The base var index.
  641. """
  642. with pytest.raises(TypeError):
  643. var[index]
  644. @pytest.mark.parametrize(
  645. "fixture",
  646. [
  647. "ParentState",
  648. "StateWithAnyVar",
  649. ],
  650. )
  651. def test_computed_var_without_annotation_error(request, fixture):
  652. """Test that a type error is thrown when an attribute of a computed var is
  653. accessed without annotating the computed var.
  654. Args:
  655. request: Fixture Request.
  656. fixture: The state fixture.
  657. """
  658. with pytest.raises(TypeError) as err:
  659. state = request.getfixturevalue(fixture)
  660. state.var_without_annotation.foo
  661. full_name = state.var_without_annotation._var_full_name
  662. assert (
  663. err.value.args[0]
  664. == f"You must provide an annotation for the state var `{full_name}`. Annotation cannot be `typing.Any`"
  665. )
  666. @pytest.mark.parametrize(
  667. "fixture",
  668. [
  669. "ChildState",
  670. "GrandChildState",
  671. ],
  672. )
  673. def test_shadow_computed_var_error(request: pytest.FixtureRequest, fixture: str):
  674. """Test that a name error is thrown when an attribute of a computed var is
  675. shadowed by another attribute.
  676. Args:
  677. request: Fixture Request.
  678. fixture: The state fixture.
  679. """
  680. with pytest.raises(NameError):
  681. state = request.getfixturevalue(fixture)
  682. state.var_without_annotation.foo
  683. @pytest.mark.parametrize(
  684. "fixture",
  685. [
  686. "StateWithCorrectVarAnnotation",
  687. "StateWithWrongVarAnnotation",
  688. ],
  689. )
  690. def test_computed_var_with_annotation_error(request, fixture):
  691. """Test that an Attribute error is thrown when a non-existent attribute of an annotated computed var is
  692. accessed or when the wrong annotation is provided to a computed var.
  693. Args:
  694. request: Fixture Request.
  695. fixture: The state fixture.
  696. """
  697. with pytest.raises(AttributeError) as err:
  698. state = request.getfixturevalue(fixture)
  699. state.var_with_annotation.foo
  700. full_name = state.var_with_annotation._var_full_name
  701. assert (
  702. err.value.args[0]
  703. == f"The State var `{full_name}` has no attribute 'foo' or may have been annotated wrongly."
  704. )
  705. @pytest.mark.parametrize(
  706. "fixture,var_name,expected_initial,expected_runtime,raises_at_runtime",
  707. [
  708. (
  709. "StateWithInitialComputedVar",
  710. "var_with_initial_value",
  711. "Initial value",
  712. "Runtime value",
  713. False,
  714. ),
  715. (
  716. "ChildWithInitialComputedVar",
  717. "var_with_initial_value_child",
  718. "Initial value",
  719. "Runtime value",
  720. False,
  721. ),
  722. (
  723. "StateWithRuntimeOnlyVar",
  724. "var_raises_at_runtime",
  725. None,
  726. None,
  727. True,
  728. ),
  729. (
  730. "ChildWithRuntimeOnlyVar",
  731. "var_raises_at_runtime_child",
  732. "Initial value",
  733. None,
  734. True,
  735. ),
  736. ],
  737. )
  738. def test_state_with_initial_computed_var(
  739. request, fixture, var_name, expected_initial, expected_runtime, raises_at_runtime
  740. ):
  741. """Test that the initial and runtime values of a computed var are correct.
  742. Args:
  743. request: Fixture Request.
  744. fixture: The state fixture.
  745. var_name: The name of the computed var.
  746. expected_initial: The expected initial value of the computed var.
  747. expected_runtime: The expected runtime value of the computed var.
  748. raises_at_runtime: Whether the computed var is runtime only.
  749. """
  750. state = request.getfixturevalue(fixture)()
  751. state_name = state.get_full_name()
  752. initial_dict = state.dict(initial=True)[state_name]
  753. assert initial_dict[var_name] == expected_initial
  754. if raises_at_runtime:
  755. with pytest.raises(ValueError):
  756. state.dict()[state_name][var_name]
  757. else:
  758. runtime_dict = state.dict()[state_name]
  759. assert runtime_dict[var_name] == expected_runtime
  760. def test_literal_var():
  761. complicated_var = LiteralVar.create(
  762. [
  763. {"a": 1, "b": 2, "c": {"d": 3, "e": 4}},
  764. [1, 2, 3, 4],
  765. 9,
  766. "string",
  767. True,
  768. False,
  769. None,
  770. set([1, 2, 3]),
  771. ]
  772. )
  773. assert (
  774. str(complicated_var)
  775. == '[({ ["a"] : 1, ["b"] : 2, ["c"] : ({ ["d"] : 3, ["e"] : 4 }) }), [1, 2, 3, 4], 9, "string", true, false, null, [1, 2, 3]]'
  776. )
  777. def test_function_var():
  778. addition_func = FunctionStringVar.create("((a, b) => a + b)")
  779. assert str(addition_func.call(1, 2)) == "(((a, b) => a + b)(1, 2))"
  780. manual_addition_func = ArgsFunctionOperation.create(
  781. ("a", "b"),
  782. {
  783. "args": [Var(_js_expr="a"), Var(_js_expr="b")],
  784. "result": Var(_js_expr="a + b"),
  785. },
  786. )
  787. assert (
  788. str(manual_addition_func.call(1, 2))
  789. == '(((a, b) => (({ ["args"] : [a, b], ["result"] : a + b })))(1, 2))'
  790. )
  791. increment_func = addition_func(1)
  792. assert (
  793. str(increment_func.call(2))
  794. == "(((...args) => ((((a, b) => a + b)(1, ...args))))(2))"
  795. )
  796. create_hello_statement = ArgsFunctionOperation.create(
  797. ("name",), f"Hello, {Var(_js_expr='name')}!"
  798. )
  799. first_name = LiteralStringVar.create("Steven")
  800. last_name = LiteralStringVar.create("Universe")
  801. assert (
  802. str(create_hello_statement.call(f"{first_name} {last_name}"))
  803. == '(((name) => (("Hello, "+name+"!")))("Steven Universe"))'
  804. )
  805. def test_var_operation():
  806. @var_operation
  807. def add(a: Union[NumberVar, int], b: Union[NumberVar, int]):
  808. return var_operation_return(js_expression=f"({a} + {b})", var_type=int)
  809. assert str(add(1, 2)) == "(1 + 2)"
  810. assert str(add(a=4, b=-9)) == "(4 + -9)"
  811. five = LiteralNumberVar.create(5)
  812. seven = add(2, five)
  813. assert isinstance(seven, NumberVar)
  814. def test_string_operations():
  815. basic_string = LiteralStringVar.create("Hello, World!")
  816. assert str(basic_string.length()) == '"Hello, World!".split("").length'
  817. assert str(basic_string.lower()) == '"Hello, World!".toLowerCase()'
  818. assert str(basic_string.upper()) == '"Hello, World!".toUpperCase()'
  819. assert str(basic_string.strip()) == '"Hello, World!".trim()'
  820. assert str(basic_string.contains("World")) == '"Hello, World!".includes("World")'
  821. assert (
  822. str(basic_string.split(" ").join(",")) == '"Hello, World!".split(" ").join(",")'
  823. )
  824. def test_all_number_operations():
  825. starting_number = LiteralNumberVar.create(-5.4)
  826. complicated_number = (((-(starting_number + 1)) * 2 / 3) // 2 % 3) ** 2
  827. assert (
  828. str(complicated_number)
  829. == "((Math.floor(((-((-5.4 + 1)) * 2) / 3) / 2) % 3) ** 2)"
  830. )
  831. even_more_complicated_number = ~(
  832. abs(math.floor(complicated_number)) | 2 & 3 & round(complicated_number)
  833. )
  834. assert (
  835. str(even_more_complicated_number)
  836. == "!(((Math.abs(Math.floor(((Math.floor(((-((-5.4 + 1)) * 2) / 3) / 2) % 3) ** 2))) || (2 && Math.round(((Math.floor(((-((-5.4 + 1)) * 2) / 3) / 2) % 3) ** 2)))) !== 0))"
  837. )
  838. assert str(LiteralNumberVar.create(5) > False) == "(5 > 0)"
  839. assert str(LiteralBooleanVar.create(False) < 5) == "(Number(false) < 5)"
  840. assert (
  841. str(LiteralBooleanVar.create(False) < LiteralBooleanVar.create(True))
  842. == "(Number(false) < Number(true))"
  843. )
  844. @pytest.mark.parametrize(
  845. ("var", "expected"),
  846. [
  847. (Var.create(False), "false"),
  848. (Var.create(True), "true"),
  849. (Var.create("false"), 'isTrue("false")'),
  850. (Var.create([1, 2, 3]), "isTrue([1, 2, 3])"),
  851. (Var.create({"a": 1, "b": 2}), 'isTrue(({ ["a"] : 1, ["b"] : 2 }))'),
  852. (Var("mysterious_var"), "isTrue(mysterious_var)"),
  853. ],
  854. )
  855. def test_boolify_operations(var, expected):
  856. assert str(var.bool()) == expected
  857. def test_index_operation():
  858. array_var = LiteralArrayVar.create([1, 2, 3, 4, 5])
  859. assert str(array_var[0]) == "[1, 2, 3, 4, 5].at(0)"
  860. assert str(array_var[1:2]) == "[1, 2, 3, 4, 5].slice(1, 2)"
  861. assert (
  862. str(array_var[1:4:2])
  863. == "[1, 2, 3, 4, 5].slice(1, 4).filter((_, i) => i % 2 === 0)"
  864. )
  865. assert (
  866. str(array_var[::-1])
  867. == "[1, 2, 3, 4, 5].slice(0, [1, 2, 3, 4, 5].length).slice().reverse().slice(undefined, undefined).filter((_, i) => i % 1 === 0)"
  868. )
  869. assert str(array_var.reverse()) == "[1, 2, 3, 4, 5].slice().reverse()"
  870. assert str(array_var[0].to(NumberVar) + 9) == "([1, 2, 3, 4, 5].at(0) + 9)"
  871. @pytest.mark.parametrize(
  872. "var, expected_js",
  873. [
  874. (Var.create(float("inf")), "Infinity"),
  875. (Var.create(-float("inf")), "-Infinity"),
  876. (Var.create(float("nan")), "NaN"),
  877. ],
  878. )
  879. def test_inf_and_nan(var, expected_js):
  880. assert str(var) == expected_js
  881. assert isinstance(var, NumberVar)
  882. assert isinstance(var, LiteralVar)
  883. with pytest.raises(PrimitiveUnserializableToJSON):
  884. var.json()
  885. def test_array_operations():
  886. array_var = LiteralArrayVar.create([1, 2, 3, 4, 5])
  887. assert str(array_var.length()) == "[1, 2, 3, 4, 5].length"
  888. assert str(array_var.contains(3)) == "[1, 2, 3, 4, 5].includes(3)"
  889. assert str(array_var.reverse()) == "[1, 2, 3, 4, 5].slice().reverse()"
  890. assert (
  891. str(ArrayVar.range(10))
  892. == "Array.from({ length: (10 - 0) / 1 }, (_, i) => 0 + i * 1)"
  893. )
  894. assert (
  895. str(ArrayVar.range(1, 10))
  896. == "Array.from({ length: (10 - 1) / 1 }, (_, i) => 1 + i * 1)"
  897. )
  898. assert (
  899. str(ArrayVar.range(1, 10, 2))
  900. == "Array.from({ length: (10 - 1) / 2 }, (_, i) => 1 + i * 2)"
  901. )
  902. assert (
  903. str(ArrayVar.range(1, 10, -1))
  904. == "Array.from({ length: (10 - 1) / -1 }, (_, i) => 1 + i * -1)"
  905. )
  906. def test_object_operations():
  907. object_var = LiteralObjectVar.create({"a": 1, "b": 2, "c": 3})
  908. assert (
  909. str(object_var.keys()) == 'Object.keys(({ ["a"] : 1, ["b"] : 2, ["c"] : 3 }))'
  910. )
  911. assert (
  912. str(object_var.values())
  913. == 'Object.values(({ ["a"] : 1, ["b"] : 2, ["c"] : 3 }))'
  914. )
  915. assert (
  916. str(object_var.entries())
  917. == 'Object.entries(({ ["a"] : 1, ["b"] : 2, ["c"] : 3 }))'
  918. )
  919. assert str(object_var.a) == '({ ["a"] : 1, ["b"] : 2, ["c"] : 3 })["a"]'
  920. assert str(object_var["a"]) == '({ ["a"] : 1, ["b"] : 2, ["c"] : 3 })["a"]'
  921. assert (
  922. str(object_var.merge(LiteralObjectVar.create({"c": 4, "d": 5})))
  923. == '({...({ ["a"] : 1, ["b"] : 2, ["c"] : 3 }), ...({ ["c"] : 4, ["d"] : 5 })})'
  924. )
  925. def test_var_component():
  926. class ComponentVarState(rx.State):
  927. field_var: rx.Component = rx.text("I am a field var")
  928. @rx.var
  929. def computed_var(self) -> rx.Component:
  930. return rx.text("I am a computed var")
  931. def has_eval_react_component(var: Var):
  932. var_data = var._get_all_var_data()
  933. assert var_data is not None
  934. assert any(
  935. any(
  936. imported_object.name == "evalReactComponent"
  937. for imported_object in imported_objects
  938. )
  939. for _, imported_objects in var_data.imports
  940. )
  941. has_eval_react_component(ComponentVarState.field_var) # type: ignore
  942. has_eval_react_component(ComponentVarState.computed_var)
  943. def test_type_chains():
  944. object_var = LiteralObjectVar.create({"a": 1, "b": 2, "c": 3})
  945. assert (object_var._key_type(), object_var._value_type()) == (str, int)
  946. assert (object_var.keys()._var_type, object_var.values()._var_type) == (
  947. List[str],
  948. List[int],
  949. )
  950. assert (
  951. str(object_var.keys()[0].upper()) # type: ignore
  952. == 'Object.keys(({ ["a"] : 1, ["b"] : 2, ["c"] : 3 })).at(0).toUpperCase()'
  953. )
  954. assert (
  955. str(object_var.entries()[1][1] - 1) # type: ignore
  956. == '(Object.entries(({ ["a"] : 1, ["b"] : 2, ["c"] : 3 })).at(1).at(1) - 1)'
  957. )
  958. assert (
  959. str(object_var["c"] + object_var["b"]) # type: ignore
  960. == '(({ ["a"] : 1, ["b"] : 2, ["c"] : 3 })["c"] + ({ ["a"] : 1, ["b"] : 2, ["c"] : 3 })["b"])'
  961. )
  962. def test_nested_dict():
  963. arr = LiteralArrayVar.create([{"bar": ["foo", "bar"]}], List[Dict[str, List[str]]])
  964. assert (
  965. str(arr[0]["bar"][0]) == '[({ ["bar"] : ["foo", "bar"] })].at(0)["bar"].at(0)'
  966. )
  967. def nested_base():
  968. class Boo(Base):
  969. foo: str
  970. bar: int
  971. class Foo(Base):
  972. bar: Boo
  973. baz: int
  974. parent_obj = LiteralObjectVar.create(
  975. Foo(bar=Boo(foo="bar", bar=5), baz=5).dict(), Foo
  976. )
  977. assert (
  978. str(parent_obj.bar.foo)
  979. == '({ ["bar"] : ({ ["foo"] : "bar", ["bar"] : 5 }), ["baz"] : 5 })["bar"]["foo"]'
  980. )
  981. def test_retrival():
  982. var_without_data = Var(_js_expr="test")
  983. assert var_without_data is not None
  984. original_var_data = VarData(
  985. state="Test",
  986. imports={"react": [ImportVar(tag="useRef")]},
  987. hooks={"const state = useContext(StateContexts.state)": None},
  988. )
  989. var_with_data = var_without_data._replace(merge_var_data=original_var_data)
  990. f_string = f"foo{var_with_data}bar"
  991. assert REFLEX_VAR_OPENING_TAG in f_string
  992. assert REFLEX_VAR_CLOSING_TAG in f_string
  993. result_var_data = LiteralVar.create(f_string)._get_all_var_data()
  994. result_immutable_var_data = Var(_js_expr=f_string)._var_data
  995. assert result_var_data is not None and result_immutable_var_data is not None
  996. assert (
  997. result_var_data.state
  998. == result_immutable_var_data.state
  999. == original_var_data.state
  1000. )
  1001. assert (
  1002. result_var_data.imports
  1003. == result_immutable_var_data.imports
  1004. == original_var_data.imports
  1005. )
  1006. assert (
  1007. tuple(result_var_data.hooks)
  1008. == tuple(result_immutable_var_data.hooks)
  1009. == tuple(original_var_data.hooks)
  1010. )
  1011. def test_fstring_concat():
  1012. original_var_with_data = LiteralVar.create(
  1013. "imagination", _var_data=VarData(state="fear")
  1014. )
  1015. immutable_var_with_data = Var(
  1016. _js_expr="consequences",
  1017. _var_data=VarData(
  1018. imports={
  1019. "react": [ImportVar(tag="useRef")],
  1020. "utils": [ImportVar(tag="useEffect")],
  1021. }
  1022. ),
  1023. )
  1024. f_string = f"foo{original_var_with_data}bar{immutable_var_with_data}baz"
  1025. string_concat = LiteralStringVar.create(
  1026. f_string,
  1027. _var_data=VarData(
  1028. hooks={"const state = useContext(StateContexts.state)": None}
  1029. ),
  1030. )
  1031. assert str(string_concat) == '("fooimaginationbar"+consequences+"baz")'
  1032. assert isinstance(string_concat, ConcatVarOperation)
  1033. assert string_concat._get_all_var_data() == VarData(
  1034. state="fear",
  1035. imports={
  1036. "react": [ImportVar(tag="useRef")],
  1037. "utils": [ImportVar(tag="useEffect")],
  1038. },
  1039. hooks={"const state = useContext(StateContexts.state)": None},
  1040. )
  1041. var = Var(_js_expr="var", _var_type=str)
  1042. myvar = Var(_js_expr="myvar", _var_type=int)._var_set_state("state")
  1043. x = Var(_js_expr="x", _var_type=str)
  1044. @pytest.mark.parametrize(
  1045. "out, expected",
  1046. [
  1047. (f"{var}", f"<reflex.Var>{hash(var)}</reflex.Var>var"),
  1048. (
  1049. f"testing f-string with {myvar}",
  1050. f"testing f-string with <reflex.Var>{hash(myvar)}</reflex.Var>state.myvar",
  1051. ),
  1052. (
  1053. f"testing local f-string {x}",
  1054. f"testing local f-string <reflex.Var>{hash(x)}</reflex.Var>x",
  1055. ),
  1056. ],
  1057. )
  1058. def test_fstrings(out, expected):
  1059. assert out == expected
  1060. @pytest.mark.parametrize(
  1061. ("value", "expect_state"),
  1062. [
  1063. ([1], ""),
  1064. ({"a": 1}, ""),
  1065. ([LiteralVar.create(1)._var_set_state("foo")], "foo"),
  1066. ({"a": LiteralVar.create(1)._var_set_state("foo")}, "foo"),
  1067. ],
  1068. )
  1069. def test_extract_state_from_container(value, expect_state):
  1070. """Test that _var_state is extracted from containers containing BaseVar.
  1071. Args:
  1072. value: The value to create a var from.
  1073. expect_state: The expected state.
  1074. """
  1075. var_data = LiteralVar.create(value)._get_all_var_data()
  1076. var_state = var_data.state if var_data else ""
  1077. assert var_state == expect_state
  1078. @pytest.mark.parametrize(
  1079. "value",
  1080. [
  1081. "var",
  1082. "\nvar",
  1083. ],
  1084. )
  1085. def test_fstring_roundtrip(value):
  1086. """Test that f-string roundtrip carries state.
  1087. Args:
  1088. value: The value to create a Var from.
  1089. """
  1090. var = Var(_js_expr=value)._var_set_state("state")
  1091. rt_var = LiteralVar.create(f"{var}")
  1092. assert var._var_state == rt_var._var_state
  1093. assert str(rt_var) == str(var)
  1094. @pytest.mark.parametrize(
  1095. "var",
  1096. [
  1097. Var(_js_expr="var", _var_type=int).guess_type(),
  1098. Var(_js_expr="var", _var_type=float).guess_type(),
  1099. Var(_js_expr="var", _var_type=str).guess_type(),
  1100. Var(_js_expr="var", _var_type=bool).guess_type(),
  1101. Var(_js_expr="var", _var_type=dict).guess_type(),
  1102. Var(_js_expr="var", _var_type=None).guess_type(),
  1103. ],
  1104. )
  1105. def test_unsupported_types_for_reverse(var):
  1106. """Test that unsupported types for reverse throw a type error.
  1107. Args:
  1108. var: The base var.
  1109. """
  1110. with pytest.raises(TypeError) as err:
  1111. var.reverse()
  1112. assert err.value.args[0] == "Cannot reverse non-list var."
  1113. @pytest.mark.parametrize(
  1114. "var",
  1115. [
  1116. Var(_js_expr="var", _var_type=int).guess_type(),
  1117. Var(_js_expr="var", _var_type=float).guess_type(),
  1118. Var(_js_expr="var", _var_type=bool).guess_type(),
  1119. Var(_js_expr="var", _var_type=None).guess_type(),
  1120. ],
  1121. )
  1122. def test_unsupported_types_for_contains(var):
  1123. """Test that unsupported types for contains throw a type error.
  1124. Args:
  1125. var: The base var.
  1126. """
  1127. with pytest.raises(TypeError) as err:
  1128. assert var.contains(1)
  1129. assert (
  1130. err.value.args[0]
  1131. == f"Var of type {var._var_type} does not support contains check."
  1132. )
  1133. @pytest.mark.parametrize(
  1134. "other",
  1135. [
  1136. Var(_js_expr="other", _var_type=int).guess_type(),
  1137. Var(_js_expr="other", _var_type=float).guess_type(),
  1138. Var(_js_expr="other", _var_type=bool).guess_type(),
  1139. Var(_js_expr="other", _var_type=list).guess_type(),
  1140. Var(_js_expr="other", _var_type=dict).guess_type(),
  1141. Var(_js_expr="other", _var_type=tuple).guess_type(),
  1142. Var(_js_expr="other", _var_type=set).guess_type(),
  1143. ],
  1144. )
  1145. def test_unsupported_types_for_string_contains(other):
  1146. with pytest.raises(TypeError) as err:
  1147. assert Var(_js_expr="var").to(str).contains(other)
  1148. assert (
  1149. err.value.args[0]
  1150. == f"Unsupported Operand type(s) for contains: ToStringOperation, {type(other).__name__}"
  1151. )
  1152. def test_unsupported_default_contains():
  1153. with pytest.raises(TypeError) as err:
  1154. assert 1 in Var(_js_expr="var", _var_type=str).guess_type()
  1155. assert (
  1156. err.value.args[0]
  1157. == "'in' operator not supported for Var types, use Var.contains() instead."
  1158. )
  1159. @pytest.mark.parametrize(
  1160. "operand1_var,operand2_var,operators",
  1161. [
  1162. (
  1163. LiteralVar.create(10),
  1164. LiteralVar.create(5),
  1165. [
  1166. "+",
  1167. "-",
  1168. "/",
  1169. "//",
  1170. "*",
  1171. "%",
  1172. "**",
  1173. ">",
  1174. "<",
  1175. "<=",
  1176. ">=",
  1177. "|",
  1178. "&",
  1179. ],
  1180. ),
  1181. (
  1182. LiteralVar.create(10.5),
  1183. LiteralVar.create(5),
  1184. ["+", "-", "/", "//", "*", "%", "**", ">", "<", "<=", ">="],
  1185. ),
  1186. (
  1187. LiteralVar.create(5),
  1188. LiteralVar.create(True),
  1189. [
  1190. "+",
  1191. "-",
  1192. "/",
  1193. "//",
  1194. "*",
  1195. "%",
  1196. "**",
  1197. ">",
  1198. "<",
  1199. "<=",
  1200. ">=",
  1201. "|",
  1202. "&",
  1203. ],
  1204. ),
  1205. (
  1206. LiteralVar.create(10.5),
  1207. LiteralVar.create(5.5),
  1208. ["+", "-", "/", "//", "*", "%", "**", ">", "<", "<=", ">="],
  1209. ),
  1210. (
  1211. LiteralVar.create(10.5),
  1212. LiteralVar.create(True),
  1213. ["+", "-", "/", "//", "*", "%", "**", ">", "<", "<=", ">="],
  1214. ),
  1215. (LiteralVar.create("10"), LiteralVar.create("5"), ["+", ">", "<", "<=", ">="]),
  1216. (
  1217. LiteralVar.create([10, 20]),
  1218. LiteralVar.create([5, 6]),
  1219. ["+", ">", "<", "<=", ">="],
  1220. ),
  1221. (LiteralVar.create([10, 20]), LiteralVar.create(5), ["*"]),
  1222. (LiteralVar.create([10, 20]), LiteralVar.create(True), ["*"]),
  1223. (
  1224. LiteralVar.create(True),
  1225. LiteralVar.create(True),
  1226. [
  1227. "+",
  1228. "-",
  1229. "/",
  1230. "//",
  1231. "*",
  1232. "%",
  1233. "**",
  1234. ">",
  1235. "<",
  1236. "<=",
  1237. ">=",
  1238. "|",
  1239. "&",
  1240. ],
  1241. ),
  1242. ],
  1243. )
  1244. def test_valid_var_operations(operand1_var: Var, operand2_var, operators: List[str]):
  1245. """Test that operations do not raise a TypeError.
  1246. Args:
  1247. operand1_var: left operand.
  1248. operand2_var: right operand.
  1249. operators: list of supported operators.
  1250. """
  1251. for operator in operators:
  1252. print(
  1253. "testing",
  1254. operator,
  1255. "on",
  1256. operand1_var,
  1257. operand2_var,
  1258. " of types",
  1259. type(operand1_var),
  1260. type(operand2_var),
  1261. )
  1262. eval(f"operand1_var {operator} operand2_var")
  1263. eval(f"operand2_var {operator} operand1_var")
  1264. # operand1_var.operation(op=operator, other=operand2_var)
  1265. # operand1_var.operation(op=operator, other=operand2_var, flip=True)
  1266. @pytest.mark.parametrize(
  1267. "operand1_var,operand2_var,operators",
  1268. [
  1269. (
  1270. LiteralVar.create(10),
  1271. LiteralVar.create(5),
  1272. [
  1273. "^",
  1274. "<<",
  1275. ">>",
  1276. ],
  1277. ),
  1278. (
  1279. LiteralVar.create(10.5),
  1280. LiteralVar.create(5),
  1281. [
  1282. "^",
  1283. "<<",
  1284. ">>",
  1285. ],
  1286. ),
  1287. (
  1288. LiteralVar.create(10.5),
  1289. LiteralVar.create(True),
  1290. [
  1291. "^",
  1292. "<<",
  1293. ">>",
  1294. ],
  1295. ),
  1296. (
  1297. LiteralVar.create(10.5),
  1298. LiteralVar.create(5.5),
  1299. [
  1300. "^",
  1301. "<<",
  1302. ">>",
  1303. ],
  1304. ),
  1305. (
  1306. LiteralVar.create("10"),
  1307. LiteralVar.create("5"),
  1308. [
  1309. "-",
  1310. "/",
  1311. "//",
  1312. "*",
  1313. "%",
  1314. "**",
  1315. "^",
  1316. "<<",
  1317. ">>",
  1318. ],
  1319. ),
  1320. (
  1321. LiteralVar.create([10, 20]),
  1322. LiteralVar.create([5, 6]),
  1323. [
  1324. "-",
  1325. "/",
  1326. "//",
  1327. "*",
  1328. "%",
  1329. "**",
  1330. "^",
  1331. "<<",
  1332. ">>",
  1333. ],
  1334. ),
  1335. (
  1336. LiteralVar.create([10, 20]),
  1337. LiteralVar.create(5),
  1338. [
  1339. "+",
  1340. "-",
  1341. "/",
  1342. "//",
  1343. "%",
  1344. "**",
  1345. ">",
  1346. "<",
  1347. "<=",
  1348. ">=",
  1349. "^",
  1350. "<<",
  1351. ">>",
  1352. ],
  1353. ),
  1354. (
  1355. LiteralVar.create([10, 20]),
  1356. LiteralVar.create(True),
  1357. [
  1358. "+",
  1359. "-",
  1360. "/",
  1361. "//",
  1362. "%",
  1363. "**",
  1364. ">",
  1365. "<",
  1366. "<=",
  1367. ">=",
  1368. "^",
  1369. "<<",
  1370. ">>",
  1371. ],
  1372. ),
  1373. (
  1374. LiteralVar.create([10, 20]),
  1375. LiteralVar.create("5"),
  1376. [
  1377. "+",
  1378. "-",
  1379. "/",
  1380. "//",
  1381. "*",
  1382. "%",
  1383. "**",
  1384. ">",
  1385. "<",
  1386. "<=",
  1387. ">=",
  1388. "^",
  1389. "<<",
  1390. ">>",
  1391. ],
  1392. ),
  1393. (
  1394. LiteralVar.create([10, 20]),
  1395. LiteralVar.create({"key": "value"}),
  1396. [
  1397. "+",
  1398. "-",
  1399. "/",
  1400. "//",
  1401. "*",
  1402. "%",
  1403. "**",
  1404. ">",
  1405. "<",
  1406. "<=",
  1407. ">=",
  1408. "^",
  1409. "<<",
  1410. ">>",
  1411. ],
  1412. ),
  1413. (
  1414. LiteralVar.create([10, 20]),
  1415. LiteralVar.create(5.5),
  1416. [
  1417. "+",
  1418. "-",
  1419. "/",
  1420. "//",
  1421. "*",
  1422. "%",
  1423. "**",
  1424. ">",
  1425. "<",
  1426. "<=",
  1427. ">=",
  1428. "^",
  1429. "<<",
  1430. ">>",
  1431. ],
  1432. ),
  1433. (
  1434. LiteralVar.create({"key": "value"}),
  1435. LiteralVar.create({"another_key": "another_value"}),
  1436. [
  1437. "+",
  1438. "-",
  1439. "/",
  1440. "//",
  1441. "*",
  1442. "%",
  1443. "**",
  1444. ">",
  1445. "<",
  1446. "<=",
  1447. ">=",
  1448. "^",
  1449. "<<",
  1450. ">>",
  1451. ],
  1452. ),
  1453. (
  1454. LiteralVar.create({"key": "value"}),
  1455. LiteralVar.create(5),
  1456. [
  1457. "+",
  1458. "-",
  1459. "/",
  1460. "//",
  1461. "*",
  1462. "%",
  1463. "**",
  1464. ">",
  1465. "<",
  1466. "<=",
  1467. ">=",
  1468. "^",
  1469. "<<",
  1470. ">>",
  1471. ],
  1472. ),
  1473. (
  1474. LiteralVar.create({"key": "value"}),
  1475. LiteralVar.create(True),
  1476. [
  1477. "+",
  1478. "-",
  1479. "/",
  1480. "//",
  1481. "*",
  1482. "%",
  1483. "**",
  1484. ">",
  1485. "<",
  1486. "<=",
  1487. ">=",
  1488. "^",
  1489. "<<",
  1490. ">>",
  1491. ],
  1492. ),
  1493. (
  1494. LiteralVar.create({"key": "value"}),
  1495. LiteralVar.create(5.5),
  1496. [
  1497. "+",
  1498. "-",
  1499. "/",
  1500. "//",
  1501. "*",
  1502. "%",
  1503. "**",
  1504. ">",
  1505. "<",
  1506. "<=",
  1507. ">=",
  1508. "^",
  1509. "<<",
  1510. ">>",
  1511. ],
  1512. ),
  1513. (
  1514. LiteralVar.create({"key": "value"}),
  1515. LiteralVar.create("5"),
  1516. [
  1517. "+",
  1518. "-",
  1519. "/",
  1520. "//",
  1521. "*",
  1522. "%",
  1523. "**",
  1524. ">",
  1525. "<",
  1526. "<=",
  1527. ">=",
  1528. "^",
  1529. "<<",
  1530. ">>",
  1531. ],
  1532. ),
  1533. ],
  1534. )
  1535. def test_invalid_var_operations(operand1_var: Var, operand2_var, operators: List[str]):
  1536. for operator in operators:
  1537. print(f"testing {operator} on {str(operand1_var)} and {str(operand2_var)}")
  1538. with pytest.raises(TypeError):
  1539. print(eval(f"operand1_var {operator} operand2_var"))
  1540. # operand1_var.operation(op=operator, other=operand2_var)
  1541. with pytest.raises(TypeError):
  1542. print(eval(f"operand2_var {operator} operand1_var"))
  1543. # operand1_var.operation(op=operator, other=operand2_var, flip=True)
  1544. @pytest.mark.parametrize(
  1545. "var, expected",
  1546. [
  1547. (LiteralVar.create("string_value"), '"string_value"'),
  1548. (LiteralVar.create(1), "1"),
  1549. (LiteralVar.create([1, 2, 3]), "[1, 2, 3]"),
  1550. (LiteralVar.create({"foo": "bar"}), '({ ["foo"] : "bar" })'),
  1551. (
  1552. LiteralVar.create(ATestState.value),
  1553. f"{ATestState.get_full_name()}.value",
  1554. ),
  1555. (
  1556. LiteralVar.create(f"{ATestState.value} string"),
  1557. f'({ATestState.get_full_name()}.value+" string")',
  1558. ),
  1559. (
  1560. LiteralVar.create(ATestState.dict_val),
  1561. f"{ATestState.get_full_name()}.dict_val",
  1562. ),
  1563. ],
  1564. )
  1565. def test_var_name_unwrapped(var, expected):
  1566. assert str(var) == expected
  1567. def cv_fget(state: BaseState) -> int:
  1568. return 1
  1569. @pytest.mark.parametrize(
  1570. "deps,expected",
  1571. [
  1572. (["a"], {"a"}),
  1573. (["b"], {"b"}),
  1574. ([ComputedVar(fget=cv_fget)], {"cv_fget"}),
  1575. ],
  1576. )
  1577. def test_computed_var_deps(deps: List[Union[str, Var]], expected: Set[str]):
  1578. @computed_var(
  1579. deps=deps,
  1580. cache=True,
  1581. )
  1582. def test_var(state) -> int:
  1583. return 1
  1584. assert test_var._static_deps == expected
  1585. @pytest.mark.parametrize(
  1586. "deps",
  1587. [
  1588. [""],
  1589. [1],
  1590. ["", "abc"],
  1591. ],
  1592. )
  1593. def test_invalid_computed_var_deps(deps: List):
  1594. with pytest.raises(TypeError):
  1595. @computed_var(
  1596. deps=deps,
  1597. cache=True,
  1598. )
  1599. def test_var(state) -> int:
  1600. return 1
  1601. def test_to_string_operation():
  1602. class Email(str): ...
  1603. class TestState(BaseState):
  1604. optional_email: Optional[Email] = None
  1605. email: Email = Email("test@reflex.dev")
  1606. assert (
  1607. str(TestState.optional_email) == f"{TestState.get_full_name()}.optional_email"
  1608. )
  1609. my_state = TestState()
  1610. assert my_state.optional_email is None
  1611. assert my_state.email == "test@reflex.dev"
  1612. assert cast(Var, TestState.email)._var_type == Email
  1613. assert cast(Var, TestState.optional_email)._var_type == Optional[Email]
  1614. single_var = Var.create(Email())
  1615. assert single_var._var_type == Email