test_state.py 17 KB

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