test_var.py 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390
  1. import json
  2. import typing
  3. from typing import Dict, List, Set, Tuple
  4. import pytest
  5. from pandas import DataFrame
  6. from reflex.base import Base
  7. from reflex.state import BaseState
  8. from reflex.vars import (
  9. BaseVar,
  10. Var,
  11. computed_var,
  12. )
  13. test_vars = [
  14. BaseVar(_var_name="prop1", _var_type=int),
  15. BaseVar(_var_name="key", _var_type=str),
  16. BaseVar(_var_name="value", _var_type=str)._var_set_state("state"),
  17. BaseVar(_var_name="local", _var_type=str, _var_is_local=True)._var_set_state(
  18. "state"
  19. ),
  20. BaseVar(_var_name="local2", _var_type=str, _var_is_local=True),
  21. ]
  22. class ATestState(BaseState):
  23. """Test state."""
  24. value: str
  25. dict_val: Dict[str, List] = {}
  26. @pytest.fixture
  27. def TestObj():
  28. class TestObj(Base):
  29. foo: int
  30. bar: str
  31. return TestObj
  32. @pytest.fixture
  33. def ParentState(TestObj):
  34. class ParentState(BaseState):
  35. foo: int
  36. bar: int
  37. @computed_var
  38. def var_without_annotation(self):
  39. return TestObj
  40. return ParentState
  41. @pytest.fixture
  42. def ChildState(ParentState, TestObj):
  43. class ChildState(ParentState):
  44. @computed_var
  45. def var_without_annotation(self):
  46. return TestObj
  47. return ChildState
  48. @pytest.fixture
  49. def GrandChildState(ChildState, TestObj):
  50. class GrandChildState(ChildState):
  51. @computed_var
  52. def var_without_annotation(self):
  53. return TestObj
  54. return GrandChildState
  55. @pytest.fixture
  56. def StateWithAnyVar(TestObj):
  57. class StateWithAnyVar(BaseState):
  58. @computed_var
  59. def var_without_annotation(self) -> typing.Any:
  60. return TestObj
  61. return StateWithAnyVar
  62. @pytest.fixture
  63. def StateWithCorrectVarAnnotation():
  64. class StateWithCorrectVarAnnotation(BaseState):
  65. @computed_var
  66. def var_with_annotation(self) -> str:
  67. return "Correct annotation"
  68. return StateWithCorrectVarAnnotation
  69. @pytest.fixture
  70. def StateWithWrongVarAnnotation(TestObj):
  71. class StateWithWrongVarAnnotation(BaseState):
  72. @computed_var
  73. def var_with_annotation(self) -> str:
  74. return TestObj
  75. return StateWithWrongVarAnnotation
  76. @pytest.fixture
  77. def StateWithInitialComputedVar():
  78. class StateWithInitialComputedVar(BaseState):
  79. @computed_var(initial_value="Initial value")
  80. def var_with_initial_value(self) -> str:
  81. return "Runtime value"
  82. return StateWithInitialComputedVar
  83. @pytest.fixture
  84. def ChildWithInitialComputedVar(StateWithInitialComputedVar):
  85. class ChildWithInitialComputedVar(StateWithInitialComputedVar):
  86. @computed_var(initial_value="Initial value")
  87. def var_with_initial_value_child(self) -> str:
  88. return "Runtime value"
  89. return ChildWithInitialComputedVar
  90. @pytest.fixture
  91. def StateWithRuntimeOnlyVar():
  92. class StateWithRuntimeOnlyVar(BaseState):
  93. @computed_var(initial_value=None)
  94. def var_raises_at_runtime(self) -> str:
  95. raise ValueError("So nicht, mein Freund")
  96. return StateWithRuntimeOnlyVar
  97. @pytest.fixture
  98. def ChildWithRuntimeOnlyVar(StateWithRuntimeOnlyVar):
  99. class ChildWithRuntimeOnlyVar(StateWithRuntimeOnlyVar):
  100. @computed_var(initial_value="Initial value")
  101. def var_raises_at_runtime_child(self) -> str:
  102. raise ValueError("So nicht, mein Freund")
  103. return ChildWithRuntimeOnlyVar
  104. @pytest.mark.parametrize(
  105. "prop,expected",
  106. zip(
  107. test_vars,
  108. [
  109. "prop1",
  110. "key",
  111. "state.value",
  112. "state.local",
  113. "local2",
  114. ],
  115. ),
  116. )
  117. def test_full_name(prop, expected):
  118. """Test that the full name of a var is correct.
  119. Args:
  120. prop: The var to test.
  121. expected: The expected full name.
  122. """
  123. assert prop._var_full_name == expected
  124. @pytest.mark.parametrize(
  125. "prop,expected",
  126. zip(
  127. test_vars,
  128. ["{prop1}", "{key}", "{state.value}", "state.local", "local2"],
  129. ),
  130. )
  131. def test_str(prop, expected):
  132. """Test that the string representation of a var is correct.
  133. Args:
  134. prop: The var to test.
  135. expected: The expected string representation.
  136. """
  137. assert str(prop) == expected
  138. @pytest.mark.parametrize(
  139. "prop,expected",
  140. [
  141. (BaseVar(_var_name="p", _var_type=int), 0),
  142. (BaseVar(_var_name="p", _var_type=float), 0.0),
  143. (BaseVar(_var_name="p", _var_type=str), ""),
  144. (BaseVar(_var_name="p", _var_type=bool), False),
  145. (BaseVar(_var_name="p", _var_type=list), []),
  146. (BaseVar(_var_name="p", _var_type=dict), {}),
  147. (BaseVar(_var_name="p", _var_type=tuple), ()),
  148. (BaseVar(_var_name="p", _var_type=set), set()),
  149. ],
  150. )
  151. def test_default_value(prop, expected):
  152. """Test that the default value of a var is correct.
  153. Args:
  154. prop: The var to test.
  155. expected: The expected default value.
  156. """
  157. assert prop.get_default_value() == expected
  158. @pytest.mark.parametrize(
  159. "prop,expected",
  160. zip(
  161. test_vars,
  162. [
  163. "set_prop1",
  164. "set_key",
  165. "state.set_value",
  166. "state.set_local",
  167. "set_local2",
  168. ],
  169. ),
  170. )
  171. def test_get_setter(prop, expected):
  172. """Test that the name of the setter function of a var is correct.
  173. Args:
  174. prop: The var to test.
  175. expected: The expected name of the setter function.
  176. """
  177. assert prop.get_setter_name() == expected
  178. @pytest.mark.parametrize(
  179. "value,expected",
  180. [
  181. (None, None),
  182. (1, BaseVar(_var_name="1", _var_type=int, _var_is_local=True)),
  183. ("key", BaseVar(_var_name="key", _var_type=str, _var_is_local=True)),
  184. (3.14, BaseVar(_var_name="3.14", _var_type=float, _var_is_local=True)),
  185. ([1, 2, 3], BaseVar(_var_name="[1, 2, 3]", _var_type=list, _var_is_local=True)),
  186. (
  187. {"a": 1, "b": 2},
  188. BaseVar(_var_name='{"a": 1, "b": 2}', _var_type=dict, _var_is_local=True),
  189. ),
  190. ],
  191. )
  192. def test_create(value, expected):
  193. """Test the var create function.
  194. Args:
  195. value: The value to create a var from.
  196. expected: The expected name of the setter function.
  197. """
  198. prop = Var.create(value)
  199. if value is None:
  200. assert prop == expected
  201. else:
  202. assert prop.equals(expected) # type: ignore
  203. def test_create_type_error():
  204. """Test the var create function when inputs type error."""
  205. class ErrorType:
  206. pass
  207. value = ErrorType()
  208. with pytest.raises(TypeError):
  209. Var.create(value)
  210. def v(value) -> Var:
  211. val = (
  212. Var.create(json.dumps(value), _var_is_string=True, _var_is_local=False)
  213. if isinstance(value, str)
  214. else Var.create(value, _var_is_local=False)
  215. )
  216. assert val is not None
  217. return val
  218. def test_basic_operations(TestObj):
  219. """Test the var operations.
  220. Args:
  221. TestObj: The test object.
  222. """
  223. assert str(v(1) == v(2)) == "{((1) === (2))}"
  224. assert str(v(1) != v(2)) == "{((1) !== (2))}"
  225. assert str(v(1) < v(2)) == "{((1) < (2))}"
  226. assert str(v(1) <= v(2)) == "{((1) <= (2))}"
  227. assert str(v(1) > v(2)) == "{((1) > (2))}"
  228. assert str(v(1) >= v(2)) == "{((1) >= (2))}"
  229. assert str(v(1) + v(2)) == "{((1) + (2))}"
  230. assert str(v(1) - v(2)) == "{((1) - (2))}"
  231. assert str(v(1) * v(2)) == "{((1) * (2))}"
  232. assert str(v(1) / v(2)) == "{((1) / (2))}"
  233. assert str(v(1) // v(2)) == "{Math.floor((1) / (2))}"
  234. assert str(v(1) % v(2)) == "{((1) % (2))}"
  235. assert str(v(1) ** v(2)) == "{Math.pow((1) , (2))}"
  236. assert str(v(1) & v(2)) == "{((1) && (2))}"
  237. assert str(v(1) | v(2)) == "{((1) || (2))}"
  238. assert str(v([1, 2, 3])[v(0)]) == "{[1, 2, 3].at(0)}"
  239. assert str(v({"a": 1, "b": 2})["a"]) == '{{"a": 1, "b": 2}["a"]}'
  240. assert str(v("foo") == v("bar")) == '{(("foo") === ("bar"))}'
  241. assert (
  242. str(
  243. Var.create("foo", _var_is_local=False)
  244. == Var.create("bar", _var_is_local=False)
  245. )
  246. == "{((foo) === (bar))}"
  247. )
  248. assert (
  249. str(
  250. BaseVar(
  251. _var_name="foo", _var_type=str, _var_is_string=True, _var_is_local=True
  252. )
  253. == BaseVar(
  254. _var_name="bar", _var_type=str, _var_is_string=True, _var_is_local=True
  255. )
  256. )
  257. == "((`foo`) === (`bar`))"
  258. )
  259. assert (
  260. str(
  261. BaseVar(
  262. _var_name="foo",
  263. _var_type=TestObj,
  264. _var_is_string=True,
  265. _var_is_local=False,
  266. )
  267. ._var_set_state("state")
  268. .bar
  269. == BaseVar(
  270. _var_name="bar", _var_type=str, _var_is_string=True, _var_is_local=True
  271. )
  272. )
  273. == "{((state.foo.bar) === (`bar`))}"
  274. )
  275. assert (
  276. str(BaseVar(_var_name="foo", _var_type=TestObj)._var_set_state("state").bar)
  277. == "{state.foo.bar}"
  278. )
  279. assert str(abs(v(1))) == "{Math.abs(1)}"
  280. assert str(v([1, 2, 3]).length()) == "{[1, 2, 3].length}"
  281. assert str(v([1, 2]) + v([3, 4])) == "{spreadArraysOrObjects(([1, 2]) , ([3, 4]))}"
  282. # Tests for reverse operation
  283. assert str(v([1, 2, 3]).reverse()) == "{[...[1, 2, 3]].reverse()}"
  284. assert str(v(["1", "2", "3"]).reverse()) == '{[...["1", "2", "3"]].reverse()}'
  285. assert (
  286. str(BaseVar(_var_name="foo", _var_type=list)._var_set_state("state").reverse())
  287. == "{[...state.foo].reverse()}"
  288. )
  289. assert (
  290. str(BaseVar(_var_name="foo", _var_type=list).reverse())
  291. == "{[...foo].reverse()}"
  292. )
  293. assert str(BaseVar(_var_name="foo", _var_type=str)._type()) == "{typeof foo}" # type: ignore
  294. assert (
  295. str(BaseVar(_var_name="foo", _var_type=str)._type() == str) # type: ignore
  296. == "{((typeof foo) === (`string`))}"
  297. )
  298. assert (
  299. str(BaseVar(_var_name="foo", _var_type=str)._type() == str) # type: ignore
  300. == "{((typeof foo) === (`string`))}"
  301. )
  302. assert (
  303. str(BaseVar(_var_name="foo", _var_type=str)._type() == int) # type: ignore
  304. == "{((typeof foo) === (`number`))}"
  305. )
  306. assert (
  307. str(BaseVar(_var_name="foo", _var_type=str)._type() == list) # type: ignore
  308. == "{((typeof foo) === (`Array`))}"
  309. )
  310. assert (
  311. str(BaseVar(_var_name="foo", _var_type=str)._type() == float) # type: ignore
  312. == "{((typeof foo) === (`number`))}"
  313. )
  314. assert (
  315. str(BaseVar(_var_name="foo", _var_type=str)._type() == tuple) # type: ignore
  316. == "{((typeof foo) === (`Array`))}"
  317. )
  318. assert (
  319. str(BaseVar(_var_name="foo", _var_type=str)._type() == dict) # type: ignore
  320. == "{((typeof foo) === (`Object`))}"
  321. )
  322. assert (
  323. str(BaseVar(_var_name="foo", _var_type=str)._type() != str) # type: ignore
  324. == "{((typeof foo) !== (`string`))}"
  325. )
  326. assert (
  327. str(BaseVar(_var_name="foo", _var_type=str)._type() != int) # type: ignore
  328. == "{((typeof foo) !== (`number`))}"
  329. )
  330. assert (
  331. str(BaseVar(_var_name="foo", _var_type=str)._type() != list) # type: ignore
  332. == "{((typeof foo) !== (`Array`))}"
  333. )
  334. assert (
  335. str(BaseVar(_var_name="foo", _var_type=str)._type() != float) # type: ignore
  336. == "{((typeof foo) !== (`number`))}"
  337. )
  338. assert (
  339. str(BaseVar(_var_name="foo", _var_type=str)._type() != tuple) # type: ignore
  340. == "{((typeof foo) !== (`Array`))}"
  341. )
  342. assert (
  343. str(BaseVar(_var_name="foo", _var_type=str)._type() != dict) # type: ignore
  344. == "{((typeof foo) !== (`Object`))}"
  345. )
  346. @pytest.mark.parametrize(
  347. "var, expected",
  348. [
  349. (v([1, 2, 3]), "[1, 2, 3]"),
  350. (v(set([1, 2, 3])), "[1, 2, 3]"),
  351. (v(["1", "2", "3"]), '["1", "2", "3"]'),
  352. (BaseVar(_var_name="foo", _var_type=list)._var_set_state("state"), "state.foo"),
  353. (BaseVar(_var_name="foo", _var_type=list), "foo"),
  354. (v((1, 2, 3)), "[1, 2, 3]"),
  355. (v(("1", "2", "3")), '["1", "2", "3"]'),
  356. (
  357. BaseVar(_var_name="foo", _var_type=tuple)._var_set_state("state"),
  358. "state.foo",
  359. ),
  360. (BaseVar(_var_name="foo", _var_type=tuple), "foo"),
  361. ],
  362. )
  363. def test_list_tuple_contains(var, expected):
  364. assert str(var.contains(1)) == f"{{{expected}.includes(1)}}"
  365. assert str(var.contains("1")) == f'{{{expected}.includes("1")}}'
  366. assert str(var.contains(v(1))) == f"{{{expected}.includes(1)}}"
  367. assert str(var.contains(v("1"))) == f'{{{expected}.includes("1")}}'
  368. other_state_var = BaseVar(_var_name="other", _var_type=str)._var_set_state("state")
  369. other_var = BaseVar(_var_name="other", _var_type=str)
  370. assert str(var.contains(other_state_var)) == f"{{{expected}.includes(state.other)}}"
  371. assert str(var.contains(other_var)) == f"{{{expected}.includes(other)}}"
  372. @pytest.mark.parametrize(
  373. "var, expected",
  374. [
  375. (v("123"), json.dumps("123")),
  376. (BaseVar(_var_name="foo", _var_type=str)._var_set_state("state"), "state.foo"),
  377. (BaseVar(_var_name="foo", _var_type=str), "foo"),
  378. ],
  379. )
  380. def test_str_contains(var, expected):
  381. assert str(var.contains("1")) == f'{{{expected}.includes("1")}}'
  382. assert str(var.contains(v("1"))) == f'{{{expected}.includes("1")}}'
  383. other_state_var = BaseVar(_var_name="other", _var_type=str)._var_set_state("state")
  384. other_var = BaseVar(_var_name="other", _var_type=str)
  385. assert str(var.contains(other_state_var)) == f"{{{expected}.includes(state.other)}}"
  386. assert str(var.contains(other_var)) == f"{{{expected}.includes(other)}}"
  387. assert (
  388. str(var.contains("1", "hello")) == f'{{{expected}.some(e=>e[`hello`]==="1")}}'
  389. )
  390. @pytest.mark.parametrize(
  391. "var, expected",
  392. [
  393. (v({"a": 1, "b": 2}), '{"a": 1, "b": 2}'),
  394. (BaseVar(_var_name="foo", _var_type=dict)._var_set_state("state"), "state.foo"),
  395. (BaseVar(_var_name="foo", _var_type=dict), "foo"),
  396. ],
  397. )
  398. def test_dict_contains(var, expected):
  399. assert str(var.contains(1)) == f"{{{expected}.hasOwnProperty(1)}}"
  400. assert str(var.contains("1")) == f'{{{expected}.hasOwnProperty("1")}}'
  401. assert str(var.contains(v(1))) == f"{{{expected}.hasOwnProperty(1)}}"
  402. assert str(var.contains(v("1"))) == f'{{{expected}.hasOwnProperty("1")}}'
  403. other_state_var = BaseVar(_var_name="other", _var_type=str)._var_set_state("state")
  404. other_var = BaseVar(_var_name="other", _var_type=str)
  405. assert (
  406. str(var.contains(other_state_var))
  407. == f"{{{expected}.hasOwnProperty(state.other)}}"
  408. )
  409. assert str(var.contains(other_var)) == f"{{{expected}.hasOwnProperty(other)}}"
  410. @pytest.mark.parametrize(
  411. "var",
  412. [
  413. BaseVar(_var_name="list", _var_type=List[int]),
  414. BaseVar(_var_name="tuple", _var_type=Tuple[int, int]),
  415. BaseVar(_var_name="str", _var_type=str),
  416. ],
  417. )
  418. def test_var_indexing_lists(var):
  419. """Test that we can index into str, list or tuple vars.
  420. Args:
  421. var : The str, list or tuple base var.
  422. """
  423. # Test basic indexing.
  424. assert str(var[0]) == f"{{{var._var_name}.at(0)}}"
  425. assert str(var[1]) == f"{{{var._var_name}.at(1)}}"
  426. # Test negative indexing.
  427. assert str(var[-1]) == f"{{{var._var_name}.at(-1)}}"
  428. @pytest.mark.parametrize(
  429. "var, type_",
  430. [
  431. (BaseVar(_var_name="list", _var_type=List[int]), [int, int]),
  432. (BaseVar(_var_name="tuple", _var_type=Tuple[int, str]), [int, str]),
  433. ],
  434. )
  435. def test_var_indexing_types(var, type_):
  436. """Test that indexing returns valid types.
  437. Args:
  438. var : The list, typle base var.
  439. type_ : The type on indexed object.
  440. """
  441. assert var[2]._var_type == type_[0]
  442. assert var[3]._var_type == type_[1]
  443. def test_var_indexing_str():
  444. """Test that we can index into str vars."""
  445. str_var = BaseVar(_var_name="str", _var_type=str)
  446. # Test that indexing gives a type of Var[str].
  447. assert isinstance(str_var[0], Var)
  448. assert str_var[0]._var_type == str
  449. # Test basic indexing.
  450. assert str(str_var[0]) == "{str.at(0)}"
  451. assert str(str_var[1]) == "{str.at(1)}"
  452. # Test negative indexing.
  453. assert str(str_var[-1]) == "{str.at(-1)}"
  454. @pytest.mark.parametrize(
  455. "var, index",
  456. [
  457. (BaseVar(_var_name="lst", _var_type=List[int]), [1, 2]),
  458. (BaseVar(_var_name="lst", _var_type=List[int]), {"name": "dict"}),
  459. (BaseVar(_var_name="lst", _var_type=List[int]), {"set"}),
  460. (
  461. BaseVar(_var_name="lst", _var_type=List[int]),
  462. (
  463. 1,
  464. 2,
  465. ),
  466. ),
  467. (BaseVar(_var_name="lst", _var_type=List[int]), 1.5),
  468. (BaseVar(_var_name="lst", _var_type=List[int]), "str"),
  469. (
  470. BaseVar(_var_name="lst", _var_type=List[int]),
  471. BaseVar(_var_name="string_var", _var_type=str),
  472. ),
  473. (
  474. BaseVar(_var_name="lst", _var_type=List[int]),
  475. BaseVar(_var_name="float_var", _var_type=float),
  476. ),
  477. (
  478. BaseVar(_var_name="lst", _var_type=List[int]),
  479. BaseVar(_var_name="list_var", _var_type=List[int]),
  480. ),
  481. (
  482. BaseVar(_var_name="lst", _var_type=List[int]),
  483. BaseVar(_var_name="set_var", _var_type=Set[str]),
  484. ),
  485. (
  486. BaseVar(_var_name="lst", _var_type=List[int]),
  487. BaseVar(_var_name="dict_var", _var_type=Dict[str, str]),
  488. ),
  489. (BaseVar(_var_name="str", _var_type=str), [1, 2]),
  490. (BaseVar(_var_name="lst", _var_type=str), {"name": "dict"}),
  491. (BaseVar(_var_name="lst", _var_type=str), {"set"}),
  492. (
  493. BaseVar(_var_name="lst", _var_type=str),
  494. BaseVar(_var_name="string_var", _var_type=str),
  495. ),
  496. (
  497. BaseVar(_var_name="lst", _var_type=str),
  498. BaseVar(_var_name="float_var", _var_type=float),
  499. ),
  500. (BaseVar(_var_name="str", _var_type=Tuple[str]), [1, 2]),
  501. (BaseVar(_var_name="lst", _var_type=Tuple[str]), {"name": "dict"}),
  502. (BaseVar(_var_name="lst", _var_type=Tuple[str]), {"set"}),
  503. (
  504. BaseVar(_var_name="lst", _var_type=Tuple[str]),
  505. BaseVar(_var_name="string_var", _var_type=str),
  506. ),
  507. (
  508. BaseVar(_var_name="lst", _var_type=Tuple[str]),
  509. BaseVar(_var_name="float_var", _var_type=float),
  510. ),
  511. ],
  512. )
  513. def test_var_unsupported_indexing_lists(var, index):
  514. """Test unsupported indexing throws a type error.
  515. Args:
  516. var: The base var.
  517. index: The base var index.
  518. """
  519. with pytest.raises(TypeError):
  520. var[index]
  521. @pytest.mark.parametrize(
  522. "var",
  523. [
  524. BaseVar(_var_name="lst", _var_type=List[int]),
  525. BaseVar(_var_name="tuple", _var_type=Tuple[int, int]),
  526. BaseVar(_var_name="str", _var_type=str),
  527. ],
  528. )
  529. def test_var_list_slicing(var):
  530. """Test that we can slice into str, list or tuple vars.
  531. Args:
  532. var : The str, list or tuple base var.
  533. """
  534. assert str(var[:1]) == f"{{{var._var_name}.slice(0, 1)}}"
  535. assert str(var[:1]) == f"{{{var._var_name}.slice(0, 1)}}"
  536. assert str(var[:]) == f"{{{var._var_name}.slice(0, undefined)}}"
  537. def test_dict_indexing():
  538. """Test that we can index into dict vars."""
  539. dct = BaseVar(_var_name="dct", _var_type=Dict[str, int])
  540. # Check correct indexing.
  541. assert str(dct["a"]) == '{dct["a"]}'
  542. assert str(dct["asdf"]) == '{dct["asdf"]}'
  543. @pytest.mark.parametrize(
  544. "var, index",
  545. [
  546. (
  547. BaseVar(_var_name="dict", _var_type=Dict[str, str]),
  548. [1, 2],
  549. ),
  550. (
  551. BaseVar(_var_name="dict", _var_type=Dict[str, str]),
  552. {"name": "dict"},
  553. ),
  554. (
  555. BaseVar(_var_name="dict", _var_type=Dict[str, str]),
  556. {"set"},
  557. ),
  558. (
  559. BaseVar(_var_name="dict", _var_type=Dict[str, str]),
  560. (
  561. 1,
  562. 2,
  563. ),
  564. ),
  565. (
  566. BaseVar(_var_name="lst", _var_type=Dict[str, str]),
  567. BaseVar(_var_name="list_var", _var_type=List[int]),
  568. ),
  569. (
  570. BaseVar(_var_name="lst", _var_type=Dict[str, str]),
  571. BaseVar(_var_name="set_var", _var_type=Set[str]),
  572. ),
  573. (
  574. BaseVar(_var_name="lst", _var_type=Dict[str, str]),
  575. BaseVar(_var_name="dict_var", _var_type=Dict[str, str]),
  576. ),
  577. (
  578. BaseVar(_var_name="df", _var_type=DataFrame),
  579. [1, 2],
  580. ),
  581. (
  582. BaseVar(_var_name="df", _var_type=DataFrame),
  583. {"name": "dict"},
  584. ),
  585. (
  586. BaseVar(_var_name="df", _var_type=DataFrame),
  587. {"set"},
  588. ),
  589. (
  590. BaseVar(_var_name="df", _var_type=DataFrame),
  591. (
  592. 1,
  593. 2,
  594. ),
  595. ),
  596. (
  597. BaseVar(_var_name="df", _var_type=DataFrame),
  598. BaseVar(_var_name="list_var", _var_type=List[int]),
  599. ),
  600. (
  601. BaseVar(_var_name="df", _var_type=DataFrame),
  602. BaseVar(_var_name="set_var", _var_type=Set[str]),
  603. ),
  604. (
  605. BaseVar(_var_name="df", _var_type=DataFrame),
  606. BaseVar(_var_name="dict_var", _var_type=Dict[str, str]),
  607. ),
  608. ],
  609. )
  610. def test_var_unsupported_indexing_dicts(var, index):
  611. """Test unsupported indexing throws a type error.
  612. Args:
  613. var: The base var.
  614. index: The base var index.
  615. """
  616. with pytest.raises(TypeError):
  617. var[index]
  618. @pytest.mark.parametrize(
  619. "fixture,full_name",
  620. [
  621. ("ParentState", "parent_state.var_without_annotation"),
  622. ("ChildState", "parent_state__child_state.var_without_annotation"),
  623. (
  624. "GrandChildState",
  625. "parent_state__child_state__grand_child_state.var_without_annotation",
  626. ),
  627. ("StateWithAnyVar", "state_with_any_var.var_without_annotation"),
  628. ],
  629. )
  630. def test_computed_var_without_annotation_error(request, fixture, full_name):
  631. """Test that a type error is thrown when an attribute of a computed var is
  632. accessed without annotating the computed var.
  633. Args:
  634. request: Fixture Request.
  635. fixture: The state fixture.
  636. full_name: The full name of the state var.
  637. """
  638. with pytest.raises(TypeError) as err:
  639. state = request.getfixturevalue(fixture)
  640. state.var_without_annotation.foo
  641. assert (
  642. err.value.args[0]
  643. == f"You must provide an annotation for the state var `{full_name}`. Annotation cannot be `typing.Any`"
  644. )
  645. @pytest.mark.parametrize(
  646. "fixture,full_name",
  647. [
  648. (
  649. "StateWithCorrectVarAnnotation",
  650. "state_with_correct_var_annotation.var_with_annotation",
  651. ),
  652. (
  653. "StateWithWrongVarAnnotation",
  654. "state_with_wrong_var_annotation.var_with_annotation",
  655. ),
  656. ],
  657. )
  658. def test_computed_var_with_annotation_error(request, fixture, full_name):
  659. """Test that an Attribute error is thrown when a non-existent attribute of an annotated computed var is
  660. accessed or when the wrong annotation is provided to a computed var.
  661. Args:
  662. request: Fixture Request.
  663. fixture: The state fixture.
  664. full_name: The full name of the state var.
  665. """
  666. with pytest.raises(AttributeError) as err:
  667. state = request.getfixturevalue(fixture)
  668. state.var_with_annotation.foo
  669. assert (
  670. err.value.args[0]
  671. == f"The State var `{full_name}` has no attribute 'foo' or may have been annotated wrongly."
  672. )
  673. @pytest.mark.parametrize(
  674. "fixture,var_name,expected_initial,expected_runtime,raises_at_runtime",
  675. [
  676. (
  677. "StateWithInitialComputedVar",
  678. "var_with_initial_value",
  679. "Initial value",
  680. "Runtime value",
  681. False,
  682. ),
  683. (
  684. "ChildWithInitialComputedVar",
  685. "var_with_initial_value_child",
  686. "Initial value",
  687. "Runtime value",
  688. False,
  689. ),
  690. (
  691. "StateWithRuntimeOnlyVar",
  692. "var_raises_at_runtime",
  693. None,
  694. None,
  695. True,
  696. ),
  697. (
  698. "ChildWithRuntimeOnlyVar",
  699. "var_raises_at_runtime_child",
  700. "Initial value",
  701. None,
  702. True,
  703. ),
  704. ],
  705. )
  706. def test_state_with_initial_computed_var(
  707. request, fixture, var_name, expected_initial, expected_runtime, raises_at_runtime
  708. ):
  709. """Test that the initial and runtime values of a computed var are correct.
  710. Args:
  711. request: Fixture Request.
  712. fixture: The state fixture.
  713. var_name: The name of the computed var.
  714. expected_initial: The expected initial value of the computed var.
  715. expected_runtime: The expected runtime value of the computed var.
  716. raises_at_runtime: Whether the computed var is runtime only.
  717. """
  718. state = request.getfixturevalue(fixture)()
  719. state_name = state.get_full_name()
  720. initial_dict = state.dict(initial=True)[state_name]
  721. assert initial_dict[var_name] == expected_initial
  722. if raises_at_runtime:
  723. with pytest.raises(ValueError):
  724. state.dict()[state_name][var_name]
  725. else:
  726. runtime_dict = state.dict()[state_name]
  727. assert runtime_dict[var_name] == expected_runtime
  728. @pytest.mark.parametrize(
  729. "out, expected",
  730. [
  731. (f"{BaseVar(_var_name='var', _var_type=str)}", "${var}"),
  732. (
  733. f"testing f-string with {BaseVar(_var_name='myvar', _var_type=int)._var_set_state('state')}",
  734. 'testing f-string with $<reflex.Var>{"state": "state", "interpolations": [], "imports": {"/utils/context": [{"tag": "StateContexts", "is_default": false, "alias": null, "install": true, "render": true, "transpile": false}], "react": [{"tag": "useContext", "is_default": false, "alias": null, "install": true, "render": true, "transpile": false}]}, "hooks": {"const state = useContext(StateContexts.state)": null}, "string_length": 13}</reflex.Var>{state.myvar}',
  735. ),
  736. (
  737. f"testing local f-string {BaseVar(_var_name='x', _var_is_local=True, _var_type=str)}",
  738. "testing local f-string x",
  739. ),
  740. ],
  741. )
  742. def test_fstrings(out, expected):
  743. assert out == expected
  744. @pytest.mark.parametrize(
  745. ("value", "expect_state"),
  746. [
  747. ([1], ""),
  748. ({"a": 1}, ""),
  749. ([Var.create_safe(1)._var_set_state("foo")], "foo"),
  750. ({"a": Var.create_safe(1)._var_set_state("foo")}, "foo"),
  751. ],
  752. )
  753. def test_extract_state_from_container(value, expect_state):
  754. """Test that _var_state is extracted from containers containing BaseVar.
  755. Args:
  756. value: The value to create a var from.
  757. expect_state: The expected state.
  758. """
  759. assert Var.create_safe(value)._var_state == expect_state
  760. @pytest.mark.parametrize(
  761. "value",
  762. [
  763. "var",
  764. "\nvar",
  765. ],
  766. )
  767. def test_fstring_roundtrip(value):
  768. """Test that f-string roundtrip carries state.
  769. Args:
  770. value: The value to create a Var from.
  771. """
  772. var = BaseVar.create_safe(value)._var_set_state("state")
  773. rt_var = Var.create_safe(f"{var}")
  774. assert var._var_state == rt_var._var_state
  775. assert var._var_full_name_needs_state_prefix
  776. assert not rt_var._var_full_name_needs_state_prefix
  777. assert rt_var._var_name == var._var_full_name
  778. @pytest.mark.parametrize(
  779. "var",
  780. [
  781. BaseVar(_var_name="var", _var_type=int),
  782. BaseVar(_var_name="var", _var_type=float),
  783. BaseVar(_var_name="var", _var_type=str),
  784. BaseVar(_var_name="var", _var_type=bool),
  785. BaseVar(_var_name="var", _var_type=dict),
  786. BaseVar(_var_name="var", _var_type=tuple),
  787. BaseVar(_var_name="var", _var_type=set),
  788. BaseVar(_var_name="var", _var_type=None),
  789. ],
  790. )
  791. def test_unsupported_types_for_reverse(var):
  792. """Test that unsupported types for reverse throw a type error.
  793. Args:
  794. var: The base var.
  795. """
  796. with pytest.raises(TypeError) as err:
  797. var.reverse()
  798. assert err.value.args[0] == f"Cannot reverse non-list var var."
  799. @pytest.mark.parametrize(
  800. "var",
  801. [
  802. BaseVar(_var_name="var", _var_type=int),
  803. BaseVar(_var_name="var", _var_type=float),
  804. BaseVar(_var_name="var", _var_type=bool),
  805. BaseVar(_var_name="var", _var_type=None),
  806. ],
  807. )
  808. def test_unsupported_types_for_contains(var):
  809. """Test that unsupported types for contains throw a type error.
  810. Args:
  811. var: The base var.
  812. """
  813. with pytest.raises(TypeError) as err:
  814. assert var.contains(1)
  815. assert (
  816. err.value.args[0]
  817. == f"Var var of type {var._var_type} does not support contains check."
  818. )
  819. @pytest.mark.parametrize(
  820. "other",
  821. [
  822. BaseVar(_var_name="other", _var_type=int),
  823. BaseVar(_var_name="other", _var_type=float),
  824. BaseVar(_var_name="other", _var_type=bool),
  825. BaseVar(_var_name="other", _var_type=list),
  826. BaseVar(_var_name="other", _var_type=dict),
  827. BaseVar(_var_name="other", _var_type=tuple),
  828. BaseVar(_var_name="other", _var_type=set),
  829. ],
  830. )
  831. def test_unsupported_types_for_string_contains(other):
  832. with pytest.raises(TypeError) as err:
  833. assert BaseVar(_var_name="var", _var_type=str).contains(other)
  834. assert (
  835. err.value.args[0]
  836. == f"'in <string>' requires string as left operand, not {other._var_type}"
  837. )
  838. def test_unsupported_default_contains():
  839. with pytest.raises(TypeError) as err:
  840. assert 1 in BaseVar(_var_name="var", _var_type=str)
  841. assert (
  842. err.value.args[0]
  843. == "'in' operator not supported for Var types, use Var.contains() instead."
  844. )
  845. @pytest.mark.parametrize(
  846. "operand1_var,operand2_var,operators",
  847. [
  848. (
  849. Var.create(10),
  850. Var.create(5),
  851. [
  852. "+",
  853. "-",
  854. "/",
  855. "//",
  856. "*",
  857. "%",
  858. "**",
  859. ">",
  860. "<",
  861. "<=",
  862. ">=",
  863. "|",
  864. "&",
  865. ],
  866. ),
  867. (
  868. Var.create(10.5),
  869. Var.create(5),
  870. ["+", "-", "/", "//", "*", "%", "**", ">", "<", "<=", ">="],
  871. ),
  872. (
  873. Var.create(5),
  874. Var.create(True),
  875. [
  876. "+",
  877. "-",
  878. "/",
  879. "//",
  880. "*",
  881. "%",
  882. "**",
  883. ">",
  884. "<",
  885. "<=",
  886. ">=",
  887. "|",
  888. "&",
  889. ],
  890. ),
  891. (
  892. Var.create(10.5),
  893. Var.create(5.5),
  894. ["+", "-", "/", "//", "*", "%", "**", ">", "<", "<=", ">="],
  895. ),
  896. (
  897. Var.create(10.5),
  898. Var.create(True),
  899. ["+", "-", "/", "//", "*", "%", "**", ">", "<", "<=", ">="],
  900. ),
  901. (Var.create("10"), Var.create("5"), ["+", ">", "<", "<=", ">="]),
  902. (Var.create([10, 20]), Var.create([5, 6]), ["+", ">", "<", "<=", ">="]),
  903. (Var.create([10, 20]), Var.create(5), ["*"]),
  904. (Var.create([10, 20]), Var.create(True), ["*"]),
  905. (
  906. Var.create(True),
  907. Var.create(True),
  908. [
  909. "+",
  910. "-",
  911. "/",
  912. "//",
  913. "*",
  914. "%",
  915. "**",
  916. ">",
  917. "<",
  918. "<=",
  919. ">=",
  920. "|",
  921. "&",
  922. ],
  923. ),
  924. ],
  925. )
  926. def test_valid_var_operations(operand1_var: Var, operand2_var, operators: List[str]):
  927. """Test that operations do not raise a TypeError.
  928. Args:
  929. operand1_var: left operand.
  930. operand2_var: right operand.
  931. operators: list of supported operators.
  932. """
  933. for operator in operators:
  934. operand1_var.operation(op=operator, other=operand2_var)
  935. operand1_var.operation(op=operator, other=operand2_var, flip=True)
  936. @pytest.mark.parametrize(
  937. "operand1_var,operand2_var,operators",
  938. [
  939. (
  940. Var.create(10),
  941. Var.create(5),
  942. [
  943. "^",
  944. "<<",
  945. ">>",
  946. ],
  947. ),
  948. (
  949. Var.create(10.5),
  950. Var.create(5),
  951. [
  952. "|",
  953. "^",
  954. "<<",
  955. ">>",
  956. "&",
  957. ],
  958. ),
  959. (
  960. Var.create(10.5),
  961. Var.create(True),
  962. [
  963. "|",
  964. "^",
  965. "<<",
  966. ">>",
  967. "&",
  968. ],
  969. ),
  970. (
  971. Var.create(10.5),
  972. Var.create(5.5),
  973. [
  974. "|",
  975. "^",
  976. "<<",
  977. ">>",
  978. "&",
  979. ],
  980. ),
  981. (
  982. Var.create("10"),
  983. Var.create("5"),
  984. [
  985. "-",
  986. "/",
  987. "//",
  988. "*",
  989. "%",
  990. "**",
  991. "|",
  992. "^",
  993. "<<",
  994. ">>",
  995. "&",
  996. ],
  997. ),
  998. (
  999. Var.create([10, 20]),
  1000. Var.create([5, 6]),
  1001. [
  1002. "-",
  1003. "/",
  1004. "//",
  1005. "*",
  1006. "%",
  1007. "**",
  1008. "|",
  1009. "^",
  1010. "<<",
  1011. ">>",
  1012. "&",
  1013. ],
  1014. ),
  1015. (
  1016. Var.create([10, 20]),
  1017. Var.create(5),
  1018. [
  1019. "+",
  1020. "-",
  1021. "/",
  1022. "//",
  1023. "%",
  1024. "**",
  1025. ">",
  1026. "<",
  1027. "<=",
  1028. ">=",
  1029. "|",
  1030. "^",
  1031. "<<",
  1032. ">>",
  1033. "&",
  1034. ],
  1035. ),
  1036. (
  1037. Var.create([10, 20]),
  1038. Var.create(True),
  1039. [
  1040. "+",
  1041. "-",
  1042. "/",
  1043. "//",
  1044. "%",
  1045. "**",
  1046. ">",
  1047. "<",
  1048. "<=",
  1049. ">=",
  1050. "|",
  1051. "^",
  1052. "<<",
  1053. ">>",
  1054. "&",
  1055. ],
  1056. ),
  1057. (
  1058. Var.create([10, 20]),
  1059. Var.create("5"),
  1060. [
  1061. "+",
  1062. "-",
  1063. "/",
  1064. "//",
  1065. "*",
  1066. "%",
  1067. "**",
  1068. ">",
  1069. "<",
  1070. "<=",
  1071. ">=",
  1072. "|",
  1073. "^",
  1074. "<<",
  1075. ">>",
  1076. "&",
  1077. ],
  1078. ),
  1079. (
  1080. Var.create([10, 20]),
  1081. Var.create({"key": "value"}),
  1082. [
  1083. "+",
  1084. "-",
  1085. "/",
  1086. "//",
  1087. "*",
  1088. "%",
  1089. "**",
  1090. ">",
  1091. "<",
  1092. "<=",
  1093. ">=",
  1094. "|",
  1095. "^",
  1096. "<<",
  1097. ">>",
  1098. "&",
  1099. ],
  1100. ),
  1101. (
  1102. Var.create([10, 20]),
  1103. Var.create(5.5),
  1104. [
  1105. "+",
  1106. "-",
  1107. "/",
  1108. "//",
  1109. "*",
  1110. "%",
  1111. "**",
  1112. ">",
  1113. "<",
  1114. "<=",
  1115. ">=",
  1116. "|",
  1117. "^",
  1118. "<<",
  1119. ">>",
  1120. "&",
  1121. ],
  1122. ),
  1123. (
  1124. Var.create({"key": "value"}),
  1125. Var.create({"another_key": "another_value"}),
  1126. [
  1127. "+",
  1128. "-",
  1129. "/",
  1130. "//",
  1131. "*",
  1132. "%",
  1133. "**",
  1134. ">",
  1135. "<",
  1136. "<=",
  1137. ">=",
  1138. "|",
  1139. "^",
  1140. "<<",
  1141. ">>",
  1142. "&",
  1143. ],
  1144. ),
  1145. (
  1146. Var.create({"key": "value"}),
  1147. Var.create(5),
  1148. [
  1149. "+",
  1150. "-",
  1151. "/",
  1152. "//",
  1153. "*",
  1154. "%",
  1155. "**",
  1156. ">",
  1157. "<",
  1158. "<=",
  1159. ">=",
  1160. "|",
  1161. "^",
  1162. "<<",
  1163. ">>",
  1164. "&",
  1165. ],
  1166. ),
  1167. (
  1168. Var.create({"key": "value"}),
  1169. Var.create(True),
  1170. [
  1171. "+",
  1172. "-",
  1173. "/",
  1174. "//",
  1175. "*",
  1176. "%",
  1177. "**",
  1178. ">",
  1179. "<",
  1180. "<=",
  1181. ">=",
  1182. "|",
  1183. "^",
  1184. "<<",
  1185. ">>",
  1186. "&",
  1187. ],
  1188. ),
  1189. (
  1190. Var.create({"key": "value"}),
  1191. Var.create(5.5),
  1192. [
  1193. "+",
  1194. "-",
  1195. "/",
  1196. "//",
  1197. "*",
  1198. "%",
  1199. "**",
  1200. ">",
  1201. "<",
  1202. "<=",
  1203. ">=",
  1204. "|",
  1205. "^",
  1206. "<<",
  1207. ">>",
  1208. "&",
  1209. ],
  1210. ),
  1211. (
  1212. Var.create({"key": "value"}),
  1213. Var.create("5"),
  1214. [
  1215. "+",
  1216. "-",
  1217. "/",
  1218. "//",
  1219. "*",
  1220. "%",
  1221. "**",
  1222. ">",
  1223. "<",
  1224. "<=",
  1225. ">=",
  1226. "|",
  1227. "^",
  1228. "<<",
  1229. ">>",
  1230. "&",
  1231. ],
  1232. ),
  1233. ],
  1234. )
  1235. def test_invalid_var_operations(operand1_var: Var, operand2_var, operators: List[str]):
  1236. for operator in operators:
  1237. with pytest.raises(TypeError):
  1238. operand1_var.operation(op=operator, other=operand2_var)
  1239. with pytest.raises(TypeError):
  1240. operand1_var.operation(op=operator, other=operand2_var, flip=True)
  1241. @pytest.mark.parametrize(
  1242. "var, expected",
  1243. [
  1244. (Var.create("string_value", _var_is_string=True), "`string_value`"),
  1245. (Var.create(1), "1"),
  1246. (Var.create([1, 2, 3]), "[1, 2, 3]"),
  1247. (Var.create({"foo": "bar"}), '{"foo": "bar"}'),
  1248. (Var.create(ATestState.value, _var_is_string=True), "a_test_state.value"),
  1249. (
  1250. Var.create(f"{ATestState.value} string", _var_is_string=True),
  1251. "`${a_test_state.value} string`",
  1252. ),
  1253. (Var.create(ATestState.dict_val), "a_test_state.dict_val"),
  1254. ],
  1255. )
  1256. def test_var_name_unwrapped(var, expected):
  1257. assert var._var_name_unwrapped == expected