test_var.py 5.7 KB

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