Update version number and release date.
[python/dscho.git] / Lib / test / test_unpack.py
bloba8fd09c633e2893b322d7c022f4ca379a07a99fc
1 from test.test_support import TestFailed, verbose
3 t = (1, 2, 3)
4 l = [4, 5, 6]
6 class Seq:
7 def __getitem__(self, i):
8 if i >= 0 and i < 3: return i
9 raise IndexError
11 a = -1
12 b = -1
13 c = -1
15 # unpack tuple
16 if verbose:
17 print 'unpack tuple'
18 a, b, c = t
19 if a != 1 or b != 2 or c != 3:
20 raise TestFailed
22 # unpack list
23 if verbose:
24 print 'unpack list'
25 a, b, c = l
26 if a != 4 or b != 5 or c != 6:
27 raise TestFailed
29 # unpack implied tuple
30 if verbose:
31 print 'unpack implied tuple'
32 a, b, c = 7, 8, 9
33 if a != 7 or b != 8 or c != 9:
34 raise TestFailed
36 # unpack string... fun!
37 if verbose:
38 print 'unpack string'
39 a, b, c = 'one'
40 if a != 'o' or b != 'n' or c != 'e':
41 raise TestFailed
43 # unpack generic sequence
44 if verbose:
45 print 'unpack sequence'
46 a, b, c = Seq()
47 if a != 0 or b != 1 or c != 2:
48 raise TestFailed
50 # single element unpacking, with extra syntax
51 if verbose:
52 print 'unpack single tuple/list'
53 st = (99,)
54 sl = [100]
55 a, = st
56 if a != 99:
57 raise TestFailed
58 b, = sl
59 if b != 100:
60 raise TestFailed
62 # now for some failures
64 # unpacking non-sequence
65 if verbose:
66 print 'unpack non-sequence'
67 try:
68 a, b, c = 7
69 raise TestFailed
70 except TypeError:
71 pass
74 # unpacking tuple of wrong size
75 if verbose:
76 print 'unpack tuple wrong size'
77 try:
78 a, b = t
79 raise TestFailed
80 except ValueError:
81 pass
83 # unpacking list of wrong size
84 if verbose:
85 print 'unpack list wrong size'
86 try:
87 a, b = l
88 raise TestFailed
89 except ValueError:
90 pass
93 # unpacking sequence too short
94 if verbose:
95 print 'unpack sequence too short'
96 try:
97 a, b, c, d = Seq()
98 raise TestFailed
99 except ValueError:
100 pass
103 # unpacking sequence too long
104 if verbose:
105 print 'unpack sequence too long'
106 try:
107 a, b = Seq()
108 raise TestFailed
109 except ValueError:
110 pass
113 # unpacking a sequence where the test for too long raises a different
114 # kind of error
115 class BozoError(Exception):
116 pass
118 class BadSeq:
119 def __getitem__(self, i):
120 if i >= 0 and i < 3:
121 return i
122 elif i == 3:
123 raise BozoError
124 else:
125 raise IndexError
128 # trigger code while not expecting an IndexError
129 if verbose:
130 print 'unpack sequence too long, wrong error'
131 try:
132 a, b, c, d, e = BadSeq()
133 raise TestFailed
134 except BozoError:
135 pass
137 # trigger code while expecting an IndexError
138 if verbose:
139 print 'unpack sequence too short, wrong error'
140 try:
141 a, b, c = BadSeq()
142 raise TestFailed
143 except BozoError:
144 pass