test_var.py 51 KB

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