1+ from typing import Dict , List
2+
13import pytest
24
35from pynecone .base import Base
@@ -135,18 +137,18 @@ def test_create(value, expected):
135137 assert prop .equals (expected ) # type: ignore
136138
137139
140+ def v (value ) -> Var :
141+ val = Var .create (value )
142+ assert val is not None
143+ return val
144+
145+
138146def test_basic_operations (TestObj ):
139147 """Test the var operations.
140148
141149 Args:
142150 TestObj: The test object.
143151 """
144-
145- def v (value ) -> Var :
146- val = Var .create (value )
147- assert val is not None
148- return val
149-
150152 assert str (v (1 ) == v (2 )) == "{(1 == 2)}"
151153 assert str (v (1 ) != v (2 )) == "{(1 != 2)}"
152154 assert str (v (1 ) < v (2 )) == "{(1 < 2)}"
@@ -162,8 +164,46 @@ def v(value) -> Var:
162164 assert str (v (1 ) ** v (2 )) == "{Math.pow(1 , 2)}"
163165 assert str (v (1 ) & v (2 )) == "{(1 && 2)}"
164166 assert str (v (1 ) | v (2 )) == "{(1 || 2)}"
165- assert str (v ([1 , 2 , 3 ])[v (0 )]) == "{[1, 2, 3][0] }"
167+ assert str (v ([1 , 2 , 3 ])[v (0 )]) == "{[1, 2, 3].at(0) }"
166168 assert str (v ({"a" : 1 , "b" : 2 })["a" ]) == '{{"a": 1, "b": 2}["a"]}'
167169 assert (
168170 str (BaseVar (name = "foo" , state = "state" , type_ = TestObj ).bar ) == "{state.foo.bar}"
169171 )
172+ assert str (abs (v (1 ))) == "{Math.abs(1)}"
173+ assert str (v ([1 , 2 , 3 ]).length ()) == "{[1, 2, 3].length}"
174+
175+
176+ def test_var_indexing_lists ():
177+ """Test that we can index into list vars."""
178+ lst = BaseVar (name = "lst" , type_ = List [int ])
179+
180+ # Test basic indexing.
181+ assert str (lst [0 ]) == "{lst.at(0)}"
182+ assert str (lst [1 ]) == "{lst.at(1)}"
183+
184+ # Test negative indexing.
185+ assert str (lst [- 1 ]) == "{lst.at(-1)}"
186+
187+ # Test non-integer indexing raises an error.
188+ with pytest .raises (TypeError ):
189+ lst ["a" ]
190+ with pytest .raises (TypeError ):
191+ lst [1.5 ]
192+
193+
194+ def test_var_list_slicing ():
195+ """Test that we can slice into list vars."""
196+ lst = BaseVar (name = "lst" , type_ = List [int ])
197+
198+ assert str (lst [0 :1 ]) == "{lst.slice(0, 1)}"
199+ assert str (lst [:1 ]) == "{lst.slice(0, 1)}"
200+ assert str (lst [0 :]) == "{lst.slice(0, undefined)}"
201+
202+
203+ def test_dict_indexing ():
204+ """Test that we can index into dict vars."""
205+ dct = BaseVar (name = "dct" , type_ = Dict [str , int ])
206+
207+ # Check correct indexing.
208+ assert str (dct ["a" ]) == '{dct["a"]}'
209+ assert str (dct ["asdf" ]) == '{dct["asdf"]}'
0 commit comments