test_var.py 50 KB

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