Skip to content

Commit 9ee72dd

Browse files
committed
Add tests for __index__
Add tests for __index__ function in list, string, tuple
1 parent 7c3d9ea commit 9ee72dd

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
@@ -39,4 +39,34 @@
3939
assert a * 0 == []
4040
assert a * -1 == []
4141

42+
class Index:
43+
def __index__(self):
44+
return 1
45+
46+
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
47+
b = Index()
48+
assert a[b] == 1
49+
assert a[b:10] == a[1:10]
50+
assert a[10:b:-1] == a[10:1:-1]
51+
52+
class NonIntegerIndex:
53+
def __index__(self):
54+
return 1.1
55+
56+
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
57+
b = NonIntegerIndex()
58+
try:
59+
a[b]
60+
except TypeError:
61+
pass
62+
else:
63+
assert False, "TypeError not raised"
64+
65+
try:
66+
a[b:10]
67+
except TypeError:
68+
pass
69+
else:
70+
assert False, "TypeError not raised"
71+
4272
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)