test_var.py 41 KB

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