test_foreach.py 7.5 KB

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