test_var.py 39 KB

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