test_var.py 43 KB

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