test_state.py 18 KB

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