test_var.py 31 KB

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