1
0

test_var.py 52 KB

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