test_state.py 20 KB

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