blob: 25324c053a3fb87d0663114baaba7c27728722b8 [file] [log] [blame]
Barry Warsaw09f95471997-08-25 22:17:45 +00001from test_support import *
2
3t = (1, 2, 3)
4l = [4, 5, 6]
5
6class Seq:
7 def __getitem__(self, i):
Guido van Rossum41360a41998-03-26 19:42:58 +00008 if i >= 0 and i < 3: return i
9 raise IndexError
Barry Warsaw09f95471997-08-25 22:17:45 +000010
11a = -1
12b = -1
13c = -1
14
15# unpack tuple
16if verbose:
17 print 'unpack tuple'
18a, b, c = t
19if a <> 1 or b <> 2 or c <> 3:
20 raise TestFailed
21
22# unpack list
23if verbose:
24 print 'unpack list'
25a, b, c = l
26if a <> 4 or b <> 5 or c <> 6:
27 raise TestFailed
28
29# unpack implied tuple
30if verbose:
31 print 'unpack implied tuple'
32a, b, c = 7, 8, 9
33if a <> 7 or b <> 8 or c <> 9:
34 raise TestFailed
35
36# unpack string... fun!
37if verbose:
38 print 'unpack string'
39a, b, c = 'one'
40if a <> 'o' or b <> 'n' or c <> 'e':
41 raise TestFailed
42
43# unpack generic sequence
44if verbose:
45 print 'unpack sequence'
46a, b, c = Seq()
47if a <> 0 or b <> 1 or c <> 2:
48 raise TestFailed
49
50# now for some failures
51
52# unpacking non-sequence
53if verbose:
54 print 'unpack non-sequence'
55try:
56 a, b, c = 7
57 raise TestFailed
58except TypeError:
59 pass
60
61
62# unpacking tuple of wrong size
63if verbose:
64 print 'unpack tuple wrong size'
65try:
66 a, b = t
67 raise TestFailed
68except ValueError:
69 pass
70
71# unpacking list of wrong size
72if verbose:
73 print 'unpack list wrong size'
74try:
75 a, b = l
76 raise TestFailed
77except ValueError:
78 pass
79
80
81# unpacking sequence too short
82if verbose:
83 print 'unpack sequence too short'
84try:
85 a, b, c, d = Seq()
86 raise TestFailed
87except ValueError:
88 pass
89
90
91# unpacking sequence too long
92if verbose:
93 print 'unpack sequence too long'
94try:
95 a, b = Seq()
96 raise TestFailed
97except ValueError:
98 pass
99
100
101# unpacking a sequence where the test for too long raises a different
102# kind of error
Fred Drakeb65b0062000-08-18 14:50:20 +0000103class BozoError(Exception):
104 pass
Barry Warsaw09f95471997-08-25 22:17:45 +0000105
106class BadSeq:
107 def __getitem__(self, i):
Guido van Rossum41360a41998-03-26 19:42:58 +0000108 if i >= 0 and i < 3:
109 return i
110 elif i == 3:
111 raise BozoError
112 else:
113 raise IndexError
Barry Warsaw09f95471997-08-25 22:17:45 +0000114
115
116# trigger code while not expecting an IndexError
117if verbose:
118 print 'unpack sequence too long, wrong error'
119try:
120 a, b, c, d, e = BadSeq()
121 raise TestFailed
122except BozoError:
123 pass
124
125# trigger code while expecting an IndexError
126if verbose:
127 print 'unpack sequence too short, wrong error'
128try:
129 a, b, c = BadSeq()
130 raise TestFailed
131except BozoError:
132 pass