test_var.py 49 KB

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