test_var.py 50 KB

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