1
0

test_foreach.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. from typing import Dict, List, Set, Tuple
  2. import pytest
  3. from reflex.components import box, foreach, text, theme
  4. from reflex.components.core import Foreach
  5. from reflex.state import BaseState
  6. try:
  7. # When pydantic v2 is installed
  8. from pydantic.v1 import ValidationError # type: ignore
  9. except ImportError:
  10. from pydantic import ValidationError
  11. class ForEachState(BaseState):
  12. """A state for testing the ForEach component."""
  13. colors_list: List[str] = ["red", "yellow"]
  14. nested_colors_list: List[List[str]] = [["red", "yellow"], ["blue", "green"]]
  15. colors_dict_list: List[Dict[str, str]] = [
  16. {
  17. "name": "red",
  18. },
  19. {"name": "yellow"},
  20. ]
  21. colors_nested_dict_list: List[Dict[str, List[str]]] = [{"shades": ["light-red"]}]
  22. primary_color: Dict[str, str] = {"category": "primary", "name": "red"}
  23. color_with_shades: Dict[str, List[str]] = {
  24. "red": ["orange", "yellow"],
  25. "yellow": ["orange", "green"],
  26. }
  27. nested_colors_with_shades: Dict[str, Dict[str, List[Dict[str, str]]]] = {
  28. "primary": {"red": [{"shade": "dark"}]}
  29. }
  30. color_tuple: Tuple[str, str] = (
  31. "red",
  32. "yellow",
  33. )
  34. colors_set: Set[str] = {"red", "green"}
  35. bad_annotation_list: list = [["red", "orange"], ["yellow", "blue"]]
  36. def display_color(color):
  37. return box(text(color))
  38. def display_color_name(color):
  39. return box(text(color["name"]))
  40. def display_shade(color):
  41. return box(text(color["shades"][0]))
  42. def display_primary_colors(color):
  43. return box(text(color[0]), text(color[1]))
  44. def display_color_with_shades(color):
  45. return box(text(color[0]), text(color[1][0]))
  46. def display_nested_color_with_shades(color):
  47. return box(text(color[0]), text(color[1]["red"][0]["shade"]))
  48. def show_shade(item):
  49. return text(item[1][0]["shade"])
  50. def display_nested_color_with_shades_v2(color):
  51. return box(text(foreach(color[1], show_shade)))
  52. def display_color_tuple(color):
  53. return box(text(color, "tuple"))
  54. def display_colors_set(color):
  55. return box(text(color, "set"))
  56. def display_nested_list_element(element: str, index: int):
  57. return box(text(element[index]))
  58. seen_index_vars = set()
  59. @pytest.mark.parametrize(
  60. "state_var, render_fn, render_dict",
  61. [
  62. (
  63. ForEachState.colors_list,
  64. display_color,
  65. {
  66. "iterable_state": "for_each_state.colors_list",
  67. "iterable_type": "list",
  68. },
  69. ),
  70. (
  71. ForEachState.colors_dict_list,
  72. display_color_name,
  73. {
  74. "iterable_state": "for_each_state.colors_dict_list",
  75. "iterable_type": "list",
  76. },
  77. ),
  78. (
  79. ForEachState.colors_nested_dict_list,
  80. display_shade,
  81. {
  82. "iterable_state": "for_each_state.colors_nested_dict_list",
  83. "iterable_type": "list",
  84. },
  85. ),
  86. (
  87. ForEachState.primary_color,
  88. display_primary_colors,
  89. {
  90. "iterable_state": "for_each_state.primary_color",
  91. "iterable_type": "dict",
  92. },
  93. ),
  94. (
  95. ForEachState.color_with_shades,
  96. display_color_with_shades,
  97. {
  98. "iterable_state": "for_each_state.color_with_shades",
  99. "iterable_type": "dict",
  100. },
  101. ),
  102. (
  103. ForEachState.nested_colors_with_shades,
  104. display_nested_color_with_shades,
  105. {
  106. "iterable_state": "for_each_state.nested_colors_with_shades",
  107. "iterable_type": "dict",
  108. },
  109. ),
  110. (
  111. ForEachState.nested_colors_with_shades,
  112. display_nested_color_with_shades_v2,
  113. {
  114. "iterable_state": "for_each_state.nested_colors_with_shades",
  115. "iterable_type": "dict",
  116. },
  117. ),
  118. (
  119. ForEachState.color_tuple,
  120. display_color_tuple,
  121. {
  122. "iterable_state": "for_each_state.color_tuple",
  123. "iterable_type": "tuple",
  124. },
  125. ),
  126. (
  127. ForEachState.colors_set,
  128. display_colors_set,
  129. {
  130. "iterable_state": "for_each_state.colors_set",
  131. "iterable_type": "set",
  132. },
  133. ),
  134. (
  135. ForEachState.nested_colors_list,
  136. lambda el, i: display_nested_list_element(el, i),
  137. {
  138. "iterable_state": "for_each_state.nested_colors_list",
  139. "iterable_type": "list",
  140. },
  141. ),
  142. ],
  143. )
  144. def test_foreach_render(state_var, render_fn, render_dict):
  145. """Test that the foreach component renders without error.
  146. Args:
  147. state_var: the state var.
  148. render_fn: The render callable
  149. render_dict: return dict on calling `component.render`
  150. """
  151. component = Foreach.create(state_var, render_fn)
  152. rend = component.render()
  153. assert rend["iterable_state"] == render_dict["iterable_state"]
  154. assert rend["iterable_type"] == render_dict["iterable_type"]
  155. # Make sure the index vars are unique.
  156. arg_index = rend["arg_index"]
  157. assert arg_index._var_name not in seen_index_vars
  158. assert arg_index._var_type == int
  159. seen_index_vars.add(arg_index._var_name)
  160. def test_foreach_apply_theme():
  161. """Test that the foreach component applies the theme."""
  162. tag = Foreach.create(ForEachState.colors_list, display_color) # type: ignore
  163. _theme = theme()
  164. tag.apply_theme(_theme)
  165. assert tag.theme == _theme
  166. tag.render()
  167. def test_foreach_bad_annotations():
  168. """Test that the foreach component raises a TypeError if the iterable is of type Any."""
  169. with pytest.raises(TypeError):
  170. Foreach.create(
  171. ForEachState.bad_annotation_list, # type: ignore
  172. lambda sublist: Foreach.create(sublist, lambda color: text(color)),
  173. )
  174. def test_foreach_no_param_in_signature():
  175. """Test that the foreach component raises a TypeError if no parameters are passed."""
  176. with pytest.raises(ValidationError):
  177. Foreach.create(
  178. ForEachState.colors_list, # type: ignore
  179. lambda: text("color"),
  180. )