test_state.py 18 KB

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