test_foreach.py 8.6 KB

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