test_foreach.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. from typing import Dict, List, Set, Tuple, Union
  2. import pytest
  3. from reflex.components import box, el, foreach, text
  4. from reflex.components.component import Component
  5. from reflex.components.core.foreach import Foreach, ForeachRenderError, ForeachVarError
  6. from reflex.state import BaseState, ComponentState
  7. from reflex.vars import Var
  8. class ForEachState(BaseState):
  9. """A state for testing the ForEach component."""
  10. colors_list: List[str] = ["red", "yellow"]
  11. nested_colors_list: List[List[str]] = [["red", "yellow"], ["blue", "green"]]
  12. colors_dict_list: List[Dict[str, str]] = [
  13. {
  14. "name": "red",
  15. },
  16. {"name": "yellow"},
  17. ]
  18. colors_nested_dict_list: List[Dict[str, List[str]]] = [{"shades": ["light-red"]}]
  19. primary_color: Dict[str, str] = {"category": "primary", "name": "red"}
  20. color_with_shades: Dict[str, List[str]] = {
  21. "red": ["orange", "yellow"],
  22. "yellow": ["orange", "green"],
  23. }
  24. nested_colors_with_shades: Dict[str, Dict[str, List[Dict[str, str]]]] = {
  25. "primary": {"red": [{"shade": "dark"}]}
  26. }
  27. color_tuple: Tuple[str, str] = (
  28. "red",
  29. "yellow",
  30. )
  31. colors_set: Set[str] = {"red", "green"}
  32. bad_annotation_list: list = [["red", "orange"], ["yellow", "blue"]]
  33. color_index_tuple: Tuple[int, str] = (0, "red")
  34. class TestComponentState(ComponentState):
  35. """A test component state."""
  36. foo: bool
  37. @classmethod
  38. def get_component(cls, *children, **props) -> Component:
  39. """Get the component.
  40. Args:
  41. children: The children components.
  42. props: The component props.
  43. Returns:
  44. The component.
  45. """
  46. return el.div(*children, **props)
  47. def display_color(color):
  48. assert color._var_type == str
  49. return box(text(color))
  50. def display_color_name(color):
  51. assert color._var_type == Dict[str, str]
  52. return box(text(color["name"]))
  53. def display_shade(color):
  54. assert color._var_type == Dict[str, List[str]]
  55. return box(text(color["shades"][0]))
  56. def display_primary_colors(color):
  57. assert color._var_type == Tuple[str, str]
  58. return box(text(color[0]), text(color[1]))
  59. def display_color_with_shades(color):
  60. assert color._var_type == Tuple[str, List[str]]
  61. return box(text(color[0]), text(color[1][0]))
  62. def display_nested_color_with_shades(color):
  63. assert color._var_type == Tuple[str, Dict[str, List[Dict[str, str]]]]
  64. return box(text(color[0]), text(color[1]["red"][0]["shade"]))
  65. def show_shade(item):
  66. return text(item[1][0]["shade"])
  67. def display_nested_color_with_shades_v2(color):
  68. assert color._var_type == Tuple[str, Dict[str, List[Dict[str, str]]]]
  69. return box(text(foreach(color[1], show_shade)))
  70. def display_color_tuple(color):
  71. assert color._var_type == str
  72. return box(text(color))
  73. def display_colors_set(color):
  74. assert color._var_type == str
  75. return box(text(color))
  76. def display_nested_list_element(element: Var[str], index: Var[int]):
  77. assert element._var_type == List[str]
  78. assert index._var_type == int
  79. return box(text(element[index]))
  80. def display_color_index_tuple(color):
  81. assert color._var_type == Union[int, str]
  82. return box(text(color))
  83. seen_index_vars = set()
  84. @pytest.mark.parametrize(
  85. "state_var, render_fn, render_dict",
  86. [
  87. (
  88. ForEachState.colors_list,
  89. display_color,
  90. {
  91. "iterable_state": "for_each_state.colors_list",
  92. "iterable_type": "list",
  93. },
  94. ),
  95. (
  96. ForEachState.colors_dict_list,
  97. display_color_name,
  98. {
  99. "iterable_state": "for_each_state.colors_dict_list",
  100. "iterable_type": "list",
  101. },
  102. ),
  103. (
  104. ForEachState.colors_nested_dict_list,
  105. display_shade,
  106. {
  107. "iterable_state": "for_each_state.colors_nested_dict_list",
  108. "iterable_type": "list",
  109. },
  110. ),
  111. (
  112. ForEachState.primary_color,
  113. display_primary_colors,
  114. {
  115. "iterable_state": "for_each_state.primary_color",
  116. "iterable_type": "dict",
  117. },
  118. ),
  119. (
  120. ForEachState.color_with_shades,
  121. display_color_with_shades,
  122. {
  123. "iterable_state": "for_each_state.color_with_shades",
  124. "iterable_type": "dict",
  125. },
  126. ),
  127. (
  128. ForEachState.nested_colors_with_shades,
  129. display_nested_color_with_shades,
  130. {
  131. "iterable_state": "for_each_state.nested_colors_with_shades",
  132. "iterable_type": "dict",
  133. },
  134. ),
  135. (
  136. ForEachState.nested_colors_with_shades,
  137. display_nested_color_with_shades_v2,
  138. {
  139. "iterable_state": "for_each_state.nested_colors_with_shades",
  140. "iterable_type": "dict",
  141. },
  142. ),
  143. (
  144. ForEachState.color_tuple,
  145. display_color_tuple,
  146. {
  147. "iterable_state": "for_each_state.color_tuple",
  148. "iterable_type": "tuple",
  149. },
  150. ),
  151. (
  152. ForEachState.colors_set,
  153. display_colors_set,
  154. {
  155. "iterable_state": "for_each_state.colors_set",
  156. "iterable_type": "set",
  157. },
  158. ),
  159. (
  160. ForEachState.nested_colors_list,
  161. lambda el, i: display_nested_list_element(el, i),
  162. {
  163. "iterable_state": "for_each_state.nested_colors_list",
  164. "iterable_type": "list",
  165. },
  166. ),
  167. (
  168. ForEachState.color_index_tuple,
  169. display_color_index_tuple,
  170. {
  171. "iterable_state": "for_each_state.color_index_tuple",
  172. "iterable_type": "tuple",
  173. },
  174. ),
  175. ],
  176. )
  177. def test_foreach_render(state_var, render_fn, render_dict):
  178. """Test that the foreach component renders without error.
  179. Args:
  180. state_var: the state var.
  181. render_fn: The render callable
  182. render_dict: return dict on calling `component.render`
  183. """
  184. component = Foreach.create(state_var, render_fn)
  185. rend = component.render()
  186. assert rend["iterable_state"] == render_dict["iterable_state"]
  187. assert rend["iterable_type"] == render_dict["iterable_type"]
  188. # Make sure the index vars are unique.
  189. arg_index = rend["arg_index"]
  190. assert isinstance(arg_index, Var)
  191. assert arg_index._var_name not in seen_index_vars
  192. assert arg_index._var_type == int
  193. seen_index_vars.add(arg_index._var_name)
  194. def test_foreach_bad_annotations():
  195. """Test that the foreach component raises a ForeachVarError if the iterable is of type Any."""
  196. with pytest.raises(ForeachVarError):
  197. Foreach.create(
  198. ForEachState.bad_annotation_list,
  199. lambda sublist: Foreach.create(sublist, lambda color: text(color)),
  200. )
  201. def test_foreach_no_param_in_signature():
  202. """Test that the foreach component raises a ForeachRenderError if no parameters are passed."""
  203. with pytest.raises(ForeachRenderError):
  204. Foreach.create(
  205. ForEachState.colors_list,
  206. lambda: text("color"),
  207. )
  208. def test_foreach_too_many_params_in_signature():
  209. """Test that the foreach component raises a ForeachRenderError if too many parameters are passed."""
  210. with pytest.raises(ForeachRenderError):
  211. Foreach.create(
  212. ForEachState.colors_list,
  213. lambda color, index, extra: text(color),
  214. )
  215. def test_foreach_component_styles():
  216. """Test that the foreach component works with global component styles."""
  217. component = el.div(
  218. foreach(
  219. ForEachState.colors_list,
  220. display_color,
  221. )
  222. )
  223. component._add_style_recursive({box: {"color": "red"}})
  224. assert 'css={{"color": "red"}}' in str(component)
  225. def test_foreach_component_state():
  226. """Test that using a component state to render in the foreach raises an error."""
  227. with pytest.raises(TypeError):
  228. Foreach.create(
  229. ForEachState.colors_list,
  230. TestComponentState.create,
  231. )