test_var.py 46 KB

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