test_var.py 33 KB

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