test_state.py 17 KB

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