test_var.py 55 KB

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