Skip to content

Commit 313242b

Browse files
committed
Add tests for __index__ function
Add tests for __index__ in list, tuple, string
1 parent 9cc7591 commit 313242b

File tree

3 files changed

+91
-0
lines changed

3 files changed

+91
-0
lines changed

py/tests/list.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,4 +111,34 @@
111111
assertRaises(TypeError, lambda: list.sort(s5, key=1))
112112
assertRaises(TypeError, lambda: list.sort(1))
113113

114+
class Index:
115+
def __index__(self):
116+
return 1
117+
118+
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
119+
b = Index()
120+
assert a[b] == 1
121+
assert a[b:10] == a[1:10]
122+
assert a[10:b:-1] == a[10:1:-1]
123+
124+
class NonIntegerIndex:
125+
def __index__(self):
126+
return 1.1
127+
128+
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
129+
b = NonIntegerIndex()
130+
try:
131+
a[b]
132+
except TypeError:
133+
pass
134+
else:
135+
assert False, "TypeError not raised"
136+
137+
try:
138+
a[b:10]
139+
except TypeError:
140+
pass
141+
else:
142+
assert False, "TypeError not raised"
143+
114144
doc="finished"

py/tests/string.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -886,4 +886,35 @@ def index(s, i):
886886
assert uni[7:7:2] == ''
887887
assert uni[7:7:3] == ''
888888

889+
class Index:
890+
def __index__(self):
891+
return 1
892+
893+
a = '012345678910'
894+
b = Index()
895+
assert a[b] == '1'
896+
assert a[b:10] == a[1:10]
897+
assert a[10:b:-1] == a[10:1:-1]
898+
899+
class NonIntegerIndex:
900+
def __index__(self):
901+
return 1.1
902+
903+
a = '012345678910'
904+
b = NonIntegerIndex()
905+
try:
906+
a[b]
907+
except TypeError:
908+
pass
909+
else:
910+
assert False, "TypeError not raised"
911+
912+
try:
913+
a[b:10]
914+
except TypeError:
915+
pass
916+
else:
917+
assert False, "TypeError not raised"
918+
919+
889920
doc="finished"

py/tests/tuple.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,34 @@
2020
assert a * 0 == ()
2121
assert a * -1 == ()
2222

23+
class Index:
24+
def __index__(self):
25+
return 1
26+
27+
a = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
28+
b = Index()
29+
assert a[b] == 1
30+
assert a[b:10] == a[1:10]
31+
assert a[10:b:-1] == a[10:1:-1]
32+
33+
class NonIntegerIndex:
34+
def __index__(self):
35+
return 1.1
36+
37+
a = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
38+
b = NonIntegerIndex()
39+
try:
40+
a[b]
41+
except TypeError:
42+
pass
43+
else:
44+
assert False, "TypeError not raised"
45+
46+
try:
47+
a[b:10]
48+
except TypeError:
49+
pass
50+
else:
51+
assert False, "TypeError not raised"
52+
2353
doc="finished"

0 commit comments

Comments
 (0)