test_state.py 18 KB

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