test_state.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. from typing import Dict, List
  2. import pytest
  3. from plotly.graph_objects import Figure
  4. from pynecone import utils
  5. from pynecone.base import Base
  6. from pynecone.constants import RouteVar
  7. from pynecone.event import Event
  8. from pynecone.state import State
  9. from pynecone.var import BaseVar, ComputedVar
  10. class Object(Base):
  11. """A test object fixture."""
  12. prop1: int = 42
  13. prop2: str = "hello"
  14. class TestState(State):
  15. """A test state."""
  16. # Set this class as not test one
  17. __test__ = False
  18. num1: int
  19. num2: float = 3.14
  20. key: str
  21. array: List[float] = [1, 2, 3.14]
  22. mapping: Dict[str, List[int]] = {"a": [1, 2, 3], "b": [4, 5, 6]}
  23. obj: Object = Object()
  24. complex: Dict[int, Object] = {1: Object(), 2: Object()}
  25. fig: Figure = Figure()
  26. @ComputedVar
  27. def sum(self) -> float:
  28. """Dynamically sum the numbers.
  29. Returns:
  30. The sum of the numbers.
  31. """
  32. return self.num1 + self.num2
  33. @ComputedVar
  34. def upper(self) -> str:
  35. """Uppercase the key.
  36. Returns:
  37. The uppercased key.
  38. """
  39. return self.key.upper()
  40. def do_something(self):
  41. """Do something."""
  42. pass
  43. class ChildState(TestState):
  44. """A child state fixture."""
  45. value: str
  46. count: int = 23
  47. def change_both(self, value: str, count: int):
  48. """Change both the value and count.
  49. Args:
  50. value: The new value.
  51. count: The new count.
  52. """
  53. self.value = value.upper()
  54. self.count = count * 2
  55. class ChildState2(TestState):
  56. """A child state fixture."""
  57. value: str
  58. class GrandchildState(ChildState):
  59. """A grandchild state fixture."""
  60. value2: str
  61. def do_nothing(self):
  62. """Do something."""
  63. pass
  64. @pytest.fixture
  65. def test_state() -> TestState:
  66. """A state.
  67. Returns:
  68. A test state.
  69. """
  70. return TestState() # type: ignore
  71. @pytest.fixture
  72. def child_state(test_state) -> ChildState:
  73. """A child state.
  74. Args:
  75. test_state: A test state.
  76. Returns:
  77. A test child state.
  78. """
  79. child_state = test_state.get_substate(["child_state"])
  80. assert child_state is not None
  81. return child_state
  82. @pytest.fixture
  83. def child_state2(test_state) -> ChildState2:
  84. """A second child state.
  85. Args:
  86. test_state: A test state.
  87. Returns:
  88. A second test child state.
  89. """
  90. child_state2 = test_state.get_substate(["child_state2"])
  91. assert child_state2 is not None
  92. return child_state2
  93. @pytest.fixture
  94. def grandchild_state(child_state) -> GrandchildState:
  95. """A state.
  96. Args:
  97. child_state: A child state.
  98. Returns:
  99. A test state.
  100. """
  101. grandchild_state = child_state.get_substate(["grandchild_state"])
  102. assert grandchild_state is not None
  103. return grandchild_state
  104. def test_base_class_vars(test_state):
  105. """Test that the class vars are set correctly.
  106. Args:
  107. test_state: A state.
  108. """
  109. fields = test_state.get_fields()
  110. cls = type(test_state)
  111. for field in fields:
  112. if field in (
  113. "parent_state",
  114. "substates",
  115. "dirty_vars",
  116. "dirty_substates",
  117. "router_data",
  118. ):
  119. continue
  120. prop = getattr(cls, field)
  121. assert isinstance(prop, BaseVar)
  122. assert prop.name == field
  123. assert cls.num1.type_ == int
  124. assert cls.num2.type_ == float
  125. assert cls.key.type_ == str
  126. def test_computed_class_var(test_state):
  127. """Test that the class computed vars are set correctly.
  128. Args:
  129. test_state: A state.
  130. """
  131. cls = type(test_state)
  132. vars = [(prop.name, prop.type_) for prop in cls.computed_vars.values()]
  133. assert ("sum", float) in vars
  134. assert ("upper", str) in vars
  135. def test_class_vars(test_state):
  136. """Test that the class vars are set correctly.
  137. Args:
  138. test_state: A state.
  139. """
  140. cls = type(test_state)
  141. assert set(cls.vars.keys()) == {
  142. "num1",
  143. "num2",
  144. "key",
  145. "array",
  146. "mapping",
  147. "obj",
  148. "complex",
  149. "sum",
  150. "upper",
  151. "fig",
  152. }
  153. def test_default_value(test_state):
  154. """Test that the default value of a var is correct.
  155. Args:
  156. test_state: A state.
  157. """
  158. assert test_state.num1 == 0
  159. assert test_state.num2 == 3.14
  160. assert test_state.key == ""
  161. assert test_state.sum == 3.14
  162. assert test_state.upper == ""
  163. def test_computed_vars(test_state):
  164. """Test that the computed var is computed correctly.
  165. Args:
  166. test_state: A state.
  167. """
  168. test_state.num1 = 1
  169. test_state.num2 = 4
  170. assert test_state.sum == 5
  171. test_state.key = "hello world"
  172. assert test_state.upper == "HELLO WORLD"
  173. def test_dict(test_state):
  174. """Test that the dict representation of a state is correct.
  175. Args:
  176. test_state: A state.
  177. """
  178. substates = {"child_state", "child_state2"}
  179. assert set(test_state.dict().keys()) == set(test_state.vars.keys()) | substates
  180. assert (
  181. set(test_state.dict(include_computed=False).keys())
  182. == set(test_state.base_vars) | substates
  183. )
  184. def test_default_setters(test_state):
  185. """Test that we can set default values.
  186. Args:
  187. test_state: A state.
  188. """
  189. for prop_name in test_state.base_vars:
  190. # Each base var should have a default setter.
  191. assert hasattr(test_state, f"set_{prop_name}")
  192. def test_class_indexing_with_vars():
  193. """Test that we can index into a state var with another var."""
  194. prop = TestState.array[TestState.num1]
  195. assert str(prop) == "{test_state.array.at(test_state.num1)}"
  196. prop = TestState.mapping["a"][TestState.num1]
  197. assert str(prop) == '{test_state.mapping["a"].at(test_state.num1)}'
  198. def test_class_attributes():
  199. """Test that we can get class attributes."""
  200. prop = TestState.obj.prop1
  201. assert str(prop) == "{test_state.obj.prop1}"
  202. prop = TestState.complex[1].prop1
  203. assert str(prop) == "{test_state.complex[1].prop1}"
  204. def test_get_parent_state():
  205. """Test getting the parent state."""
  206. assert TestState.get_parent_state() is None
  207. assert ChildState.get_parent_state() == TestState
  208. assert ChildState2.get_parent_state() == TestState
  209. assert GrandchildState.get_parent_state() == ChildState
  210. def test_get_substates():
  211. """Test getting the substates."""
  212. assert TestState.get_substates() == {ChildState, ChildState2}
  213. assert ChildState.get_substates() == {GrandchildState}
  214. assert ChildState2.get_substates() == set()
  215. assert GrandchildState.get_substates() == set()
  216. def test_get_name():
  217. """Test getting the name of a state."""
  218. assert TestState.get_name() == "test_state"
  219. assert ChildState.get_name() == "child_state"
  220. assert ChildState2.get_name() == "child_state2"
  221. assert GrandchildState.get_name() == "grandchild_state"
  222. def test_get_full_name():
  223. """Test getting the full name."""
  224. assert TestState.get_full_name() == "test_state"
  225. assert ChildState.get_full_name() == "test_state.child_state"
  226. assert ChildState2.get_full_name() == "test_state.child_state2"
  227. assert GrandchildState.get_full_name() == "test_state.child_state.grandchild_state"
  228. def test_get_class_substate():
  229. """Test getting the substate of a class."""
  230. assert TestState.get_class_substate(("child_state",)) == ChildState
  231. assert TestState.get_class_substate(("child_state2",)) == ChildState2
  232. assert ChildState.get_class_substate(("grandchild_state",)) == GrandchildState
  233. assert (
  234. TestState.get_class_substate(("child_state", "grandchild_state"))
  235. == GrandchildState
  236. )
  237. with pytest.raises(ValueError):
  238. TestState.get_class_substate(("invalid_child",))
  239. with pytest.raises(ValueError):
  240. TestState.get_class_substate(
  241. (
  242. "child_state",
  243. "invalid_child",
  244. )
  245. )
  246. def test_get_class_var():
  247. """Test getting the var of a class."""
  248. assert TestState.get_class_var(("num1",)) == TestState.num1
  249. assert TestState.get_class_var(("num2",)) == TestState.num2
  250. assert ChildState.get_class_var(("value",)) == ChildState.value
  251. assert GrandchildState.get_class_var(("value2",)) == GrandchildState.value2
  252. assert TestState.get_class_var(("child_state", "value")) == ChildState.value
  253. assert (
  254. TestState.get_class_var(("child_state", "grandchild_state", "value2"))
  255. == GrandchildState.value2
  256. )
  257. assert (
  258. ChildState.get_class_var(("grandchild_state", "value2"))
  259. == GrandchildState.value2
  260. )
  261. with pytest.raises(ValueError):
  262. TestState.get_class_var(("invalid_var",))
  263. with pytest.raises(ValueError):
  264. TestState.get_class_var(
  265. (
  266. "child_state",
  267. "invalid_var",
  268. )
  269. )
  270. def test_set_class_var():
  271. """Test setting the var of a class."""
  272. with pytest.raises(AttributeError):
  273. TestState.num3 # type: ignore
  274. TestState._set_var(BaseVar(name="num3", type_=int).set_state(TestState))
  275. var = TestState.num3 # type: ignore
  276. assert var.name == "num3"
  277. assert var.type_ == int
  278. assert var.state == TestState.get_full_name()
  279. def test_set_parent_and_substates(test_state, child_state, grandchild_state):
  280. """Test setting the parent and substates.
  281. Args:
  282. test_state: A state.
  283. child_state: A child state.
  284. grandchild_state: A grandchild state.
  285. """
  286. assert len(test_state.substates) == 2
  287. assert set(test_state.substates) == {"child_state", "child_state2"}
  288. assert child_state.parent_state == test_state
  289. assert len(child_state.substates) == 1
  290. assert set(child_state.substates) == {"grandchild_state"}
  291. assert grandchild_state.parent_state == child_state
  292. assert len(grandchild_state.substates) == 0
  293. def test_get_child_attribute(test_state, child_state, child_state2, grandchild_state):
  294. """Test getting the attribute of a state.
  295. Args:
  296. test_state: A state.
  297. child_state: A child state.
  298. child_state2: A child state.
  299. grandchild_state: A grandchild state.
  300. """
  301. assert test_state.num1 == 0
  302. assert child_state.value == ""
  303. assert child_state2.value == ""
  304. assert child_state.count == 23
  305. assert grandchild_state.value2 == ""
  306. with pytest.raises(AttributeError):
  307. test_state.invalid
  308. with pytest.raises(AttributeError):
  309. test_state.child_state.invalid
  310. with pytest.raises(AttributeError):
  311. test_state.child_state.grandchild_state.invalid
  312. def test_set_child_attribute(test_state, child_state, grandchild_state):
  313. """Test setting the attribute of a state.
  314. Args:
  315. test_state: A state.
  316. child_state: A child state.
  317. grandchild_state: A grandchild state.
  318. """
  319. test_state.num1 = 10
  320. assert test_state.num1 == 10
  321. assert child_state.num1 == 10
  322. assert grandchild_state.num1 == 10
  323. grandchild_state.num1 = 5
  324. assert test_state.num1 == 5
  325. assert child_state.num1 == 5
  326. assert grandchild_state.num1 == 5
  327. child_state.value = "test"
  328. assert child_state.value == "test"
  329. assert grandchild_state.value == "test"
  330. grandchild_state.value = "test2"
  331. assert child_state.value == "test2"
  332. assert grandchild_state.value == "test2"
  333. grandchild_state.value2 = "test3"
  334. assert grandchild_state.value2 == "test3"
  335. def test_get_substate(test_state, child_state, child_state2, grandchild_state):
  336. """Test getting the substate of a state.
  337. Args:
  338. test_state: A state.
  339. child_state: A child state.
  340. child_state2: A child state.
  341. grandchild_state: A grandchild state.
  342. """
  343. assert test_state.get_substate(("child_state",)) == child_state
  344. assert test_state.get_substate(("child_state2",)) == child_state2
  345. assert (
  346. test_state.get_substate(("child_state", "grandchild_state")) == grandchild_state
  347. )
  348. assert child_state.get_substate(("grandchild_state",)) == grandchild_state
  349. with pytest.raises(ValueError):
  350. test_state.get_substate(("invalid",))
  351. with pytest.raises(ValueError):
  352. test_state.get_substate(("child_state", "invalid"))
  353. with pytest.raises(ValueError):
  354. test_state.get_substate(("child_state", "grandchild_state", "invalid"))
  355. def test_set_dirty_var(test_state):
  356. """Test changing state vars marks the value as dirty.
  357. Args:
  358. test_state: A state.
  359. """
  360. # Initially there should be no dirty vars.
  361. assert test_state.dirty_vars == set()
  362. # Setting a var should mark it as dirty.
  363. test_state.num1 = 1
  364. assert test_state.dirty_vars == {"num1"}
  365. # Setting another var should mark it as dirty.
  366. test_state.num2 = 2
  367. assert test_state.dirty_vars == {"num1", "num2"}
  368. # Cleaning the state should remove all dirty vars.
  369. test_state.clean()
  370. assert test_state.dirty_vars == set()
  371. def test_set_dirty_substate(test_state, child_state, child_state2, grandchild_state):
  372. """Test changing substate vars marks the value as dirty.
  373. Args:
  374. test_state: A state.
  375. child_state: A child state.
  376. child_state2: A child state.
  377. grandchild_state: A grandchild state.
  378. """
  379. # Initially there should be no dirty vars.
  380. assert test_state.dirty_vars == set()
  381. assert child_state.dirty_vars == set()
  382. assert child_state2.dirty_vars == set()
  383. assert grandchild_state.dirty_vars == set()
  384. # Setting a var should mark it as dirty.
  385. child_state.value = "test"
  386. assert child_state.dirty_vars == {"value"}
  387. assert test_state.dirty_substates == {"child_state"}
  388. assert child_state.dirty_substates == set()
  389. # Cleaning the parent state should remove the dirty substate.
  390. test_state.clean()
  391. assert test_state.dirty_substates == set()
  392. assert child_state.dirty_vars == set()
  393. # Setting a var on the grandchild should bubble up.
  394. grandchild_state.value2 = "test2"
  395. assert child_state.dirty_substates == {"grandchild_state"}
  396. assert test_state.dirty_substates == {"child_state"}
  397. # Cleaning the middle state should keep the parent state dirty.
  398. child_state.clean()
  399. assert test_state.dirty_substates == {"child_state"}
  400. assert child_state.dirty_substates == set()
  401. assert grandchild_state.dirty_vars == set()
  402. def test_reset(test_state, child_state):
  403. """Test resetting the state.
  404. Args:
  405. test_state: A state.
  406. child_state: A child state.
  407. """
  408. # Set some values.
  409. test_state.num1 = 1
  410. test_state.num2 = 2
  411. child_state.value = "test"
  412. # Reset the state.
  413. test_state.reset()
  414. # The values should be reset.
  415. assert test_state.num1 == 0
  416. assert test_state.num2 == 3.14
  417. assert child_state.value == ""
  418. # The dirty vars should be reset.
  419. assert test_state.dirty_vars == set()
  420. assert child_state.dirty_vars == set()
  421. # The dirty substates should be reset.
  422. assert test_state.dirty_substates == set()
  423. @pytest.mark.asyncio
  424. async def test_process_event_simple(test_state):
  425. """Test processing an event.
  426. Args:
  427. test_state: A state.
  428. """
  429. assert test_state.num1 == 0
  430. event = Event(token="t", name="set_num1", payload={"value": 69})
  431. update = await test_state.process(event)
  432. # The event should update the value.
  433. assert test_state.num1 == 69
  434. # The delta should contain the changes, including computed vars.
  435. assert update.delta == {"test_state": {"num1": 69, "sum": 72.14, "upper": ""}}
  436. assert update.events == []
  437. @pytest.mark.asyncio
  438. async def test_process_event_substate(test_state, child_state, grandchild_state):
  439. """Test processing an event on a substate.
  440. Args:
  441. test_state: A state.
  442. child_state: A child state.
  443. grandchild_state: A grandchild state.
  444. """
  445. # Events should bubble down to the substate.
  446. assert child_state.value == ""
  447. assert child_state.count == 23
  448. event = Event(
  449. token="t", name="child_state.change_both", payload={"value": "hi", "count": 12}
  450. )
  451. update = await test_state.process(event)
  452. assert child_state.value == "HI"
  453. assert child_state.count == 24
  454. assert update.delta == {
  455. "test_state.child_state": {"value": "HI", "count": 24},
  456. "test_state": {"sum": 3.14, "upper": ""},
  457. }
  458. test_state.clean()
  459. # Test with the granchild state.
  460. assert grandchild_state.value2 == ""
  461. event = Event(
  462. token="t",
  463. name="child_state.grandchild_state.set_value2",
  464. payload={"value": "new"},
  465. )
  466. update = await test_state.process(event)
  467. assert grandchild_state.value2 == "new"
  468. assert update.delta == {
  469. "test_state.child_state.grandchild_state": {"value2": "new"},
  470. "test_state": {"sum": 3.14, "upper": ""},
  471. }
  472. def test_format_event_handler():
  473. """Test formatting an event handler."""
  474. assert (
  475. utils.format_event_handler(TestState.do_something) == "test_state.do_something" # type: ignore
  476. )
  477. assert (
  478. utils.format_event_handler(ChildState.change_both) # type: ignore
  479. == "test_state.child_state.change_both"
  480. )
  481. assert (
  482. utils.format_event_handler(GrandchildState.do_nothing) # type: ignore
  483. == "test_state.child_state.grandchild_state.do_nothing"
  484. )
  485. def test_get_token(test_state):
  486. assert test_state.get_token() == ""
  487. token = "b181904c-3953-4a79-dc18-ae9518c22f05"
  488. test_state.router_data = {RouteVar.CLIENT_TOKEN: token}
  489. assert test_state.get_token() == token
  490. def test_get_current_page(test_state):
  491. assert test_state.get_current_page() == ""
  492. route = "mypage/subpage"
  493. test_state.router_data = {RouteVar.PATH: route}
  494. assert test_state.get_current_page() == route
  495. def test_get_query_params(test_state):
  496. assert test_state.get_query_params() == {}
  497. params = {"p1": "a", "p2": "b"}
  498. test_state.router_data = {RouteVar.QUERY: params}
  499. assert test_state.get_query_params() == params
  500. def test_add_var(test_state):
  501. test_state.add_var("dynamic_int", int, 42)
  502. assert test_state.dynamic_int == 42
  503. test_state.add_var("dynamic_list", List[int], [5, 10])
  504. assert test_state.dynamic_list == [5, 10]
  505. assert test_state.dynamic_list == [5, 10]
  506. # how to test that one?
  507. # test_state.dynamic_list.append(15)
  508. # assert test_state.dynamic_list == [5, 10, 15]
  509. test_state.add_var("dynamic_dict", Dict[str, int], {"k1": 5, "k2": 10})
  510. assert test_state.dynamic_dict == {"k1": 5, "k2": 10}
  511. assert test_state.dynamic_dict == {"k1": 5, "k2": 10}