1
0

mutation.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. """Test states for mutable vars."""
  2. from typing import Dict, List, Set, Union
  3. from sqlalchemy import ARRAY, JSON, String
  4. from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
  5. import reflex as rx
  6. from reflex.state import BaseState
  7. from reflex.utils.serializers import serializer
  8. class DictMutationTestState(BaseState):
  9. """A state for testing ReflexDict mutation."""
  10. # plain dict
  11. details = {"name": "Tommy"}
  12. def add_age(self):
  13. """Add an age to the dict."""
  14. self.details.update({"age": 20}) # pyright: ignore [reportCallIssue, reportArgumentType]
  15. def change_name(self):
  16. """Change the name in the dict."""
  17. self.details["name"] = "Jenny"
  18. def remove_last_detail(self):
  19. """Remove the last item in the dict."""
  20. self.details.popitem()
  21. def clear_details(self):
  22. """Clear the dict."""
  23. self.details.clear()
  24. def remove_name(self):
  25. """Remove the name from the dict."""
  26. del self.details["name"]
  27. def pop_out_age(self):
  28. """Pop out the age from the dict."""
  29. self.details.pop("age")
  30. # dict in list
  31. address = [{"home": "home address"}, {"work": "work address"}]
  32. def remove_home_address(self):
  33. """Remove the home address from dict in the list."""
  34. self.address[0].pop("home")
  35. def add_street_to_home_address(self):
  36. """Set street key in the dict in the list."""
  37. self.address[0]["street"] = "street address"
  38. # nested dict
  39. friend_in_nested_dict = {"name": "Nikhil", "friend": {"name": "Alek"}}
  40. def change_friend_name(self):
  41. """Change the friend's name in the nested dict."""
  42. self.friend_in_nested_dict["friend"]["name"] = "Tommy"
  43. def remove_friend(self):
  44. """Remove the friend from the nested dict."""
  45. self.friend_in_nested_dict.pop("friend")
  46. def add_friend_age(self):
  47. """Add an age to the friend in the nested dict."""
  48. self.friend_in_nested_dict["friend"]["age"] = 30
  49. class ListMutationTestState(BaseState):
  50. """A state for testing ReflexList mutation."""
  51. # plain list
  52. plain_friends = ["Tommy"]
  53. def make_friend(self):
  54. """Add a friend to the list."""
  55. self.plain_friends.append("another-fd")
  56. def change_first_friend(self):
  57. """Change the first friend in the list."""
  58. self.plain_friends[0] = "Jenny"
  59. def unfriend_all_friends(self):
  60. """Unfriend all friends in the list."""
  61. self.plain_friends.clear()
  62. def unfriend_first_friend(self):
  63. """Unfriend the first friend in the list."""
  64. del self.plain_friends[0]
  65. def remove_last_friend(self):
  66. """Remove the last friend in the list."""
  67. self.plain_friends.pop()
  68. def make_friends_with_colleagues(self):
  69. """Add list of friends to the list."""
  70. colleagues = ["Peter", "Jimmy"]
  71. self.plain_friends.extend(colleagues)
  72. def remove_tommy(self):
  73. """Remove Tommy from the list."""
  74. self.plain_friends.remove("Tommy")
  75. # list in dict
  76. friends_in_dict = {"Tommy": ["Jenny"]}
  77. def remove_jenny_from_tommy(self):
  78. """Remove Jenny from Tommy's friends list."""
  79. self.friends_in_dict["Tommy"].remove("Jenny")
  80. def add_jimmy_to_tommy_friends(self):
  81. """Add Jimmy to Tommy's friends list."""
  82. self.friends_in_dict["Tommy"].append("Jimmy")
  83. def tommy_has_no_fds(self):
  84. """Clear Tommy's friends list."""
  85. self.friends_in_dict["Tommy"].clear()
  86. # nested list
  87. friends_in_nested_list = [["Tommy"], ["Jenny"]]
  88. def remove_first_group(self):
  89. """Remove the first group of friends from the nested list."""
  90. self.friends_in_nested_list.pop(0)
  91. def remove_first_person_from_first_group(self):
  92. """Remove the first person from the first group of friends in the nested list."""
  93. self.friends_in_nested_list[0].pop(0)
  94. def add_jimmy_to_second_group(self):
  95. """Add Jimmy to the second group of friends in the nested list."""
  96. self.friends_in_nested_list[1].append("Jimmy")
  97. class OtherBase(rx.Base):
  98. """A Base model with a str field."""
  99. bar: str = ""
  100. class CustomVar(rx.Base):
  101. """A Base model with multiple fields."""
  102. foo: str = ""
  103. array: List[str] = []
  104. hashmap: Dict[str, str] = {}
  105. test_set: Set[str] = set()
  106. custom: OtherBase = OtherBase()
  107. class MutableSQLABase(DeclarativeBase):
  108. """SQLAlchemy base model for mutable vars."""
  109. pass
  110. class MutableSQLAModel(MutableSQLABase):
  111. """SQLAlchemy model for mutable vars."""
  112. __tablename__: str = "mutable_test_state"
  113. id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
  114. strlist: Mapped[List[str]] = mapped_column(ARRAY(String))
  115. hashmap: Mapped[Dict[str, str]] = mapped_column(JSON)
  116. test_set: Mapped[Set[str]] = mapped_column(ARRAY(String))
  117. @serializer
  118. def serialize_mutable_sqla_model(
  119. model: MutableSQLAModel,
  120. ) -> Dict[str, Union[List[str], Dict[str, str]]]:
  121. """Serialize the MutableSQLAModel.
  122. Args:
  123. model: The MutableSQLAModel instance to serialize.
  124. Returns:
  125. The serialized model.
  126. """
  127. return {"strlist": model.strlist, "hashmap": model.hashmap}
  128. class MutableTestState(BaseState):
  129. """A test state."""
  130. array: List[Union[str, int, List, Dict[str, str]]] = [
  131. "value",
  132. [1, 2, 3],
  133. {"key": "value"},
  134. ]
  135. hashmap: Dict[str, Union[List, str, Dict[str, Union[str, Dict]]]] = {
  136. "key": ["list", "of", "values"],
  137. "another_key": "another_value",
  138. "third_key": {"key": "value"},
  139. }
  140. test_set: Set[Union[str, int]] = {1, 2, 3, 4, "five"}
  141. custom: CustomVar = CustomVar()
  142. _be_custom: CustomVar = CustomVar()
  143. sqla_model: MutableSQLAModel = MutableSQLAModel(
  144. strlist=["a", "b", "c"],
  145. hashmap={"key": "value"},
  146. test_set={"one", "two", "three"},
  147. )
  148. def reassign_mutables(self):
  149. """Assign mutable fields to different values."""
  150. self.array = ["modified_value", [1, 2, 3], {"mod_key": "mod_value"}]
  151. self.hashmap = {
  152. "mod_key": ["list", "of", "values"],
  153. "mod_another_key": "another_value",
  154. "mod_third_key": {"key": "value"},
  155. }
  156. self.test_set = {1, 2, 3, 4, "five"}
  157. self.sqla_model = MutableSQLAModel(
  158. strlist=["d", "e", "f"],
  159. hashmap={"key": "value"},
  160. test_set={"one", "two", "three"},
  161. )