test_var.py 44 KB

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