test_tag.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. from typing import Any, Dict, List
  2. import pytest
  3. from pynecone.components.tags import CondTag, Tag
  4. from pynecone.event import EVENT_ARG, EventChain, EventHandler, EventSpec
  5. from pynecone.vars import BaseVar, Var
  6. def mock_event(arg):
  7. pass
  8. @pytest.mark.parametrize(
  9. "prop,formatted",
  10. [
  11. ("string", '"string"'),
  12. ("{wrapped_string}", "{wrapped_string}"),
  13. (True, "{true}"),
  14. (False, "{false}"),
  15. (123, "{123}"),
  16. (3.14, "{3.14}"),
  17. ([1, 2, 3], "{[1, 2, 3]}"),
  18. (["a", "b", "c"], '{["a", "b", "c"]}'),
  19. ({"a": 1, "b": 2, "c": 3}, '{{"a": 1, "b": 2, "c": 3}}'),
  20. (
  21. EventChain(events=[EventSpec(handler=EventHandler(fn=mock_event))]),
  22. '{() => Event([E("mock_event", {})])}',
  23. ),
  24. (
  25. EventChain(
  26. events=[
  27. EventSpec(
  28. handler=EventHandler(fn=mock_event),
  29. local_args=(EVENT_ARG,),
  30. args=((Var.create_safe("arg"), EVENT_ARG.target.value),),
  31. )
  32. ]
  33. ),
  34. '{(_e) => Event([E("mock_event", {arg:_e.target.value})])}',
  35. ),
  36. ({"a": "red", "b": "blue"}, '{{"a": "red", "b": "blue"}}'),
  37. (BaseVar(name="var", type_="int"), "{var}"),
  38. (
  39. BaseVar(
  40. name="_",
  41. type_=Any,
  42. state="",
  43. is_local=True,
  44. is_string=False,
  45. ),
  46. "{_}",
  47. ),
  48. (BaseVar(name='state.colors["a"]', type_="str"), '{state.colors["a"]}'),
  49. ({"a": BaseVar(name="val", type_="str")}, '{{"a": val}}'),
  50. ({"a": BaseVar(name='"val"', type_="str")}, '{{"a": "val"}}'),
  51. (
  52. {"a": BaseVar(name='state.colors["val"]', type_="str")},
  53. '{{"a": state.colors["val"]}}',
  54. ),
  55. ],
  56. )
  57. def test_format_prop(prop: Var, formatted: str):
  58. """Test that the formatted value of an prop is correct.
  59. Args:
  60. prop: The prop to test.
  61. formatted: The expected formatted value.
  62. """
  63. assert Tag.format_prop(prop) == formatted
  64. @pytest.mark.parametrize(
  65. "props,test_props",
  66. [
  67. ({}, []),
  68. ({"key": 1}, ["key={1}"]),
  69. ({"key": "value"}, ['key="value"']),
  70. ({"key": True, "key2": "value2"}, ["key={true}", 'key2="value2"']),
  71. ],
  72. )
  73. def test_format_props(props: Dict[str, Var], test_props: List):
  74. """Test that the formatted props are correct.
  75. Args:
  76. props: The props to test.
  77. test_props: The expected props.
  78. """
  79. tag_props = Tag(props=props).format_props()
  80. for i, tag_prop in enumerate(tag_props):
  81. assert tag_prop == test_props[i]
  82. @pytest.mark.parametrize(
  83. "prop,valid",
  84. [
  85. (1, True),
  86. (3.14, True),
  87. ("string", True),
  88. (False, True),
  89. ([], True),
  90. ({}, False),
  91. (None, False),
  92. ],
  93. )
  94. def test_is_valid_prop(prop: Var, valid: bool):
  95. """Test that the prop is valid.
  96. Args:
  97. prop: The prop to test.
  98. valid: The expected validity of the prop.
  99. """
  100. assert Tag.is_valid_prop(prop) == valid
  101. def test_add_props():
  102. """Test that the props are added."""
  103. tag = Tag().add_props(key="value", key2=42, invalid=None, invalid2={})
  104. assert tag.props["key"] == Var.create("value")
  105. assert tag.props["key2"] == Var.create(42)
  106. assert "invalid" not in tag.props
  107. assert "invalid2" not in tag.props
  108. @pytest.mark.parametrize(
  109. "tag,expected",
  110. [
  111. (Tag(), {"name": "", "contents": "", "props": {}}),
  112. (Tag(name="br"), {"name": "br", "contents": "", "props": {}}),
  113. (Tag(contents="hello"), {"name": "", "contents": "hello", "props": {}}),
  114. (
  115. Tag(name="h1", contents="hello"),
  116. {"name": "h1", "contents": "hello", "props": {}},
  117. ),
  118. (
  119. Tag(name="box", props={"color": "red", "textAlign": "center"}),
  120. {
  121. "name": "box",
  122. "contents": "",
  123. "props": {"color": "red", "textAlign": "center"},
  124. },
  125. ),
  126. (
  127. Tag(
  128. name="box",
  129. props={"color": "red", "textAlign": "center"},
  130. contents="text",
  131. ),
  132. {
  133. "name": "box",
  134. "contents": "text",
  135. "props": {"color": "red", "textAlign": "center"},
  136. },
  137. ),
  138. ],
  139. )
  140. def test_format_tag(tag: Tag, expected: Dict):
  141. """Test that the tag dict is correct.
  142. Args:
  143. tag: The tag to test.
  144. expected: The expected tag dictionary.
  145. """
  146. tag_dict = dict(tag)
  147. assert tag_dict["name"] == expected["name"]
  148. assert tag_dict["contents"] == expected["contents"]
  149. assert tag_dict["props"] == expected["props"]
  150. def test_format_cond_tag():
  151. """Test that the cond tag dict is correct."""
  152. tag = CondTag(
  153. true_value=dict(Tag(name="h1", contents="True content")),
  154. false_value=dict(Tag(name="h2", contents="False content")),
  155. cond=BaseVar(name="logged_in", type_=bool),
  156. )
  157. tag_dict = dict(tag)
  158. cond, true_value, false_value = (
  159. tag_dict["cond"],
  160. tag_dict["true_value"],
  161. tag_dict["false_value"],
  162. )
  163. assert cond == "logged_in"
  164. assert true_value["name"] == "h1"
  165. assert true_value["contents"] == "True content"
  166. assert false_value["name"] == "h2"
  167. assert false_value["contents"] == "False content"