test_tag.py 5.4 KB

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