test_var.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. from typing import Dict, List
  2. import pytest
  3. from pynecone.base import Base
  4. from pynecone.var import BaseVar, Var
  5. test_vars = [
  6. BaseVar(name="prop1", type_=int),
  7. BaseVar(name="key", type_=str),
  8. BaseVar(name="value", type_=str, state="state"),
  9. BaseVar(name="local", type_=str, state="state", is_local=True),
  10. BaseVar(name="local2", type_=str, is_local=True),
  11. ]
  12. @pytest.fixture
  13. def TestObj():
  14. class TestObj(Base):
  15. foo: int
  16. bar: str
  17. return TestObj
  18. @pytest.mark.parametrize(
  19. "prop,expected",
  20. zip(
  21. test_vars,
  22. [
  23. "prop1",
  24. "key",
  25. "state.value",
  26. "state.local",
  27. "local2",
  28. ],
  29. ),
  30. )
  31. def test_full_name(prop, expected):
  32. """Test that the full name of a var is correct.
  33. Args:
  34. prop: The var to test.
  35. expected: The expected full name.
  36. """
  37. assert prop.full_name == expected
  38. @pytest.mark.parametrize(
  39. "prop,expected",
  40. zip(
  41. test_vars,
  42. ["{prop1}", "{key}", "{state.value}", "state.local", "local2"],
  43. ),
  44. )
  45. def test_str(prop, expected):
  46. """Test that the string representation of a var is correct.
  47. Args:
  48. prop: The var to test.
  49. expected: The expected string representation.
  50. """
  51. assert str(prop) == expected
  52. @pytest.mark.parametrize(
  53. "prop,expected",
  54. [
  55. (BaseVar(name="p", type_=int), 0),
  56. (BaseVar(name="p", type_=float), 0.0),
  57. (BaseVar(name="p", type_=str), ""),
  58. (BaseVar(name="p", type_=bool), False),
  59. (BaseVar(name="p", type_=list), []),
  60. (BaseVar(name="p", type_=dict), {}),
  61. (BaseVar(name="p", type_=tuple), ()),
  62. (BaseVar(name="p", type_=set), set()),
  63. ],
  64. )
  65. def test_default_value(prop, expected):
  66. """Test that the default value of a var is correct.
  67. Args:
  68. prop: The var to test.
  69. expected: The expected default value.
  70. """
  71. assert prop.get_default_value() == expected
  72. @pytest.mark.parametrize(
  73. "prop,expected",
  74. zip(
  75. test_vars,
  76. [
  77. "set_prop1",
  78. "set_key",
  79. "state.set_value",
  80. "state.set_local",
  81. "set_local2",
  82. ],
  83. ),
  84. )
  85. def test_get_setter(prop, expected):
  86. """Test that the name of the setter function of a var is correct.
  87. Args:
  88. prop: The var to test.
  89. expected: The expected name of the setter function.
  90. """
  91. assert prop.get_setter_name() == expected
  92. @pytest.mark.parametrize(
  93. "value,expected",
  94. [
  95. (None, None),
  96. (1, BaseVar(name="1", type_=int, is_local=True)),
  97. ("key", BaseVar(name="key", type_=str, is_local=True)),
  98. (3.14, BaseVar(name="3.14", type_=float, is_local=True)),
  99. ([1, 2, 3], BaseVar(name="[1, 2, 3]", type_=list, is_local=True)),
  100. (
  101. {"a": 1, "b": 2},
  102. BaseVar(name='{"a": 1, "b": 2}', type_=dict, is_local=True),
  103. ),
  104. ],
  105. )
  106. def test_create(value, expected):
  107. """Test the var create function.
  108. Args:
  109. value: The value to create a var from.
  110. expected: The expected name of the setter function.
  111. """
  112. prop = Var.create(value)
  113. if value is None:
  114. assert prop == expected
  115. else:
  116. assert prop.equals(expected) # type: ignore
  117. def v(value) -> Var:
  118. val = Var.create(value)
  119. assert val is not None
  120. return val
  121. def test_basic_operations(TestObj):
  122. """Test the var operations.
  123. Args:
  124. TestObj: The test object.
  125. """
  126. assert str(v(1) == v(2)) == "{(1 == 2)}"
  127. assert str(v(1) != v(2)) == "{(1 != 2)}"
  128. assert str(v(1) < v(2)) == "{(1 < 2)}"
  129. assert str(v(1) <= v(2)) == "{(1 <= 2)}"
  130. assert str(v(1) > v(2)) == "{(1 > 2)}"
  131. assert str(v(1) >= v(2)) == "{(1 >= 2)}"
  132. assert str(v(1) + v(2)) == "{(1 + 2)}"
  133. assert str(v(1) - v(2)) == "{(1 - 2)}"
  134. assert str(v(1) * v(2)) == "{(1 * 2)}"
  135. assert str(v(1) / v(2)) == "{(1 / 2)}"
  136. assert str(v(1) // v(2)) == "{Math.floor(1 / 2)}"
  137. assert str(v(1) % v(2)) == "{(1 % 2)}"
  138. assert str(v(1) ** v(2)) == "{Math.pow(1 , 2)}"
  139. assert str(v(1) & v(2)) == "{(1 && 2)}"
  140. assert str(v(1) | v(2)) == "{(1 || 2)}"
  141. assert str(v([1, 2, 3])[v(0)]) == "{[1, 2, 3].at(0)}"
  142. assert str(v({"a": 1, "b": 2})["a"]) == '{{"a": 1, "b": 2}["a"]}'
  143. assert (
  144. str(BaseVar(name="foo", state="state", type_=TestObj).bar) == "{state.foo.bar}"
  145. )
  146. assert str(abs(v(1))) == "{Math.abs(1)}"
  147. assert str(v([1, 2, 3]).length()) == "{[1, 2, 3].length}"
  148. def test_var_indexing_lists():
  149. """Test that we can index into list vars."""
  150. lst = BaseVar(name="lst", type_=List[int])
  151. # Test basic indexing.
  152. assert str(lst[0]) == "{lst.at(0)}"
  153. assert str(lst[1]) == "{lst.at(1)}"
  154. # Test negative indexing.
  155. assert str(lst[-1]) == "{lst.at(-1)}"
  156. # Test non-integer indexing raises an error.
  157. with pytest.raises(TypeError):
  158. lst["a"]
  159. with pytest.raises(TypeError):
  160. lst[1.5]
  161. def test_var_list_slicing():
  162. """Test that we can slice into list vars."""
  163. lst = BaseVar(name="lst", type_=List[int])
  164. assert str(lst[0:1]) == "{lst.slice(0, 1)}"
  165. assert str(lst[:1]) == "{lst.slice(0, 1)}"
  166. assert str(lst[0:]) == "{lst.slice(0, undefined)}"
  167. def test_dict_indexing():
  168. """Test that we can index into dict vars."""
  169. dct = BaseVar(name="dct", type_=Dict[str, int])
  170. # Check correct indexing.
  171. assert str(dct["a"]) == '{dct["a"]}'
  172. assert str(dct["asdf"]) == '{dct["asdf"]}'