blob: 929f85316438fb7dc53cab74a7e2da91961010de [file] [log] [blame]
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001from test import support, seq_tests
Zachary Wareac28b792015-12-04 23:32:23 -06002import unittest
Walter Dörwald1dde95d2003-12-08 11:38:45 +00003
Antoine Pitrou3a652b12009-03-23 18:52:06 +00004import gc
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00005import pickle
Antoine Pitrou3a652b12009-03-23 18:52:06 +00006
Walter Dörwald1dde95d2003-12-08 11:38:45 +00007class TupleTest(seq_tests.CommonTest):
8 type2test = tuple
9
Terry Jan Reedyffff1442014-08-02 01:30:37 -040010 def test_getitem_error(self):
11 msg = "tuple indices must be integers or slices"
12 with self.assertRaisesRegex(TypeError, msg):
13 ()['a']
14
Walter Dörwald1dde95d2003-12-08 11:38:45 +000015 def test_constructors(self):
Éric Araujoa63c2402010-12-23 19:13:05 +000016 super().test_constructors()
Walter Dörwald1dde95d2003-12-08 11:38:45 +000017 # calling built-in types without argument must return empty
18 self.assertEqual(tuple(), ())
Christian Heimes81ee3ef2008-05-04 22:42:01 +000019 t0_3 = (0, 1, 2, 3)
20 t0_3_bis = tuple(t0_3)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000021 self.assertTrue(t0_3 is t0_3_bis)
Christian Heimes81ee3ef2008-05-04 22:42:01 +000022 self.assertEqual(tuple([]), ())
23 self.assertEqual(tuple([0, 1, 2, 3]), (0, 1, 2, 3))
24 self.assertEqual(tuple(''), ())
25 self.assertEqual(tuple('spam'), ('s', 'p', 'a', 'm'))
Serhiy Storchaka58d23e62017-03-06 00:53:39 +020026 self.assertEqual(tuple(x for x in range(10) if x % 2),
27 (1, 3, 5, 7, 9))
28
29 def test_keyword_args(self):
Serhiy Storchaka2e564242017-03-06 17:01:06 +020030 with self.assertRaisesRegex(TypeError, 'keyword argument'):
31 tuple(sequence=())
Walter Dörwald1dde95d2003-12-08 11:38:45 +000032
33 def test_truth(self):
Guido van Rossumcd16bf62007-06-13 18:07:49 +000034 super().test_truth()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000035 self.assertTrue(not ())
36 self.assertTrue((42, ))
Walter Dörwald1dde95d2003-12-08 11:38:45 +000037
38 def test_len(self):
Guido van Rossumcd16bf62007-06-13 18:07:49 +000039 super().test_len()
Walter Dörwald1dde95d2003-12-08 11:38:45 +000040 self.assertEqual(len(()), 0)
41 self.assertEqual(len((0,)), 1)
42 self.assertEqual(len((0, 1, 2)), 3)
43
44 def test_iadd(self):
Guido van Rossumcd16bf62007-06-13 18:07:49 +000045 super().test_iadd()
Walter Dörwald1dde95d2003-12-08 11:38:45 +000046 u = (0, 1)
47 u2 = u
48 u += (2, 3)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000049 self.assertTrue(u is not u2)
Walter Dörwald1dde95d2003-12-08 11:38:45 +000050
51 def test_imul(self):
Guido van Rossumcd16bf62007-06-13 18:07:49 +000052 super().test_imul()
Walter Dörwald1dde95d2003-12-08 11:38:45 +000053 u = (0, 1)
54 u2 = u
55 u *= 3
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000056 self.assertTrue(u is not u2)
Walter Dörwald1dde95d2003-12-08 11:38:45 +000057
58 def test_tupleresizebug(self):
59 # Check that a specific bug in _PyTuple_Resize() is squashed.
60 def f():
61 for i in range(1000):
62 yield i
Guido van Rossum805365e2007-05-07 22:24:25 +000063 self.assertEqual(list(tuple(f())), list(range(1000)))
Walter Dörwald1dde95d2003-12-08 11:38:45 +000064
jdemeyeraeb1be52018-10-28 02:06:38 +020065 # Various tests for hashing of tuples to check that we get few collisions.
66 #
67 # Earlier versions of the tuple hash algorithm had collisions
68 # reported at:
69 # - https://bugs.python.org/issue942952
70 # - https://bugs.python.org/issue34751
71 #
72 # Notes:
73 # - The hash of tuples is deterministic: if the test passes once on a given
74 # system, it will always pass. So the probabilities mentioned in the
75 # test_hash functions below should be interpreted assuming that the
76 # hashes are random.
77 # - Due to the structure in the testsuite inputs, collisions are not
78 # independent. For example, if hash((a,b)) == hash((c,d)), then also
79 # hash((a,b,x)) == hash((c,d,x)). But the quoted probabilities assume
80 # independence anyway.
81 # - We limit the hash to 32 bits in the tests to have a good test on
82 # 64-bit systems too. Furthermore, this is also a sanity check that the
83 # lower 32 bits of a 64-bit hash are sufficiently random too.
84 def test_hash1(self):
85 # Check for hash collisions between small integers in range(50) and
86 # certain tuples and nested tuples of such integers.
Raymond Hettinger41bd0222004-06-01 06:36:24 +000087 N=50
Guido van Rossum805365e2007-05-07 22:24:25 +000088 base = list(range(N))
Raymond Hettinger41bd0222004-06-01 06:36:24 +000089 xp = [(i, j) for i in base for j in base]
90 inps = base + [(i, j) for i in base for j in xp] + \
Guido van Rossum801f0d72006-08-24 19:48:10 +000091 [(i, j) for i in xp for j in base] + xp + list(zip(base))
jdemeyeraeb1be52018-10-28 02:06:38 +020092 self.assertEqual(len(inps), 252600)
93 hashes = set(hash(x) % 2**32 for x in inps)
94 collisions = len(inps) - len(hashes)
95
96 # For a pure random 32-bit hash and N = 252,600 test items, the
97 # expected number of collisions equals
98 #
99 # 2**(-32) * N(N-1)/2 = 7.4
100 #
101 # We allow up to 15 collisions, which suffices to make the test
102 # pass with 99.5% confidence.
103 self.assertLessEqual(collisions, 15)
104
105 def test_hash2(self):
106 # Check for hash collisions between small integers (positive and
107 # negative), tuples and nested tuples of such integers.
108
109 # All numbers in the interval [-n, ..., n] except -1 because
110 # hash(-1) == hash(-2).
111 n = 5
112 A = [x for x in range(-n, n+1) if x != -1]
113
114 B = A + [(a,) for a in A]
115
116 L2 = [(a,b) for a in A for b in A]
117 L3 = L2 + [(a,b,c) for a in A for b in A for c in A]
118 L4 = L3 + [(a,b,c,d) for a in A for b in A for c in A for d in A]
119
120 # T = list of testcases. These consist of all (possibly nested
121 # at most 2 levels deep) tuples containing at most 4 items from
122 # the set A.
123 T = A
124 T += [(a,) for a in B + L4]
125 T += [(a,b) for a in L3 for b in B]
126 T += [(a,b) for a in L2 for b in L2]
127 T += [(a,b) for a in B for b in L3]
128 T += [(a,b,c) for a in B for b in B for c in L2]
129 T += [(a,b,c) for a in B for b in L2 for c in B]
130 T += [(a,b,c) for a in L2 for b in B for c in B]
131 T += [(a,b,c,d) for a in B for b in B for c in B for d in B]
132 self.assertEqual(len(T), 345130)
133 hashes = set(hash(x) % 2**32 for x in T)
134 collisions = len(T) - len(hashes)
135
136 # For a pure random 32-bit hash and N = 345,130 test items, the
137 # expected number of collisions equals
138 #
139 # 2**(-32) * N(N-1)/2 = 13.9
140 #
141 # We allow up to 20 collisions, which suffices to make the test
142 # pass with 95.5% confidence.
143 self.assertLessEqual(collisions, 20)
144
145 def test_hash3(self):
146 # Check for hash collisions between tuples containing 0.0 and 0.5.
147 # The hashes of 0.0 and 0.5 itself differ only in one high bit.
148 # So this implicitly tests propagation of high bits to low bits.
149 from itertools import product
150 T = list(product([0.0, 0.5], repeat=18))
151 self.assertEqual(len(T), 262144)
152 hashes = set(hash(x) % 2**32 for x in T)
153 collisions = len(T) - len(hashes)
154
155 # For a pure random 32-bit hash and N = 262,144 test items, the
156 # expected number of collisions equals
157 #
158 # 2**(-32) * N(N-1)/2 = 8.0
159 #
160 # We allow up to 15 collisions, which suffices to make the test
161 # pass with 99.1% confidence.
162 self.assertLessEqual(collisions, 15)
Walter Dörwald1dde95d2003-12-08 11:38:45 +0000163
Raymond Hettinger5ea7e312004-09-30 07:47:20 +0000164 def test_repr(self):
165 l0 = tuple()
166 l2 = (0, 1, 2)
167 a0 = self.type2test(l0)
168 a2 = self.type2test(l2)
169
170 self.assertEqual(str(a0), repr(l0))
171 self.assertEqual(str(a2), repr(l2))
172 self.assertEqual(repr(a0), "()")
173 self.assertEqual(repr(a2), "(0, 1, 2)")
174
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000175 def _not_tracked(self, t):
176 # Nested tuples can take several collections to untrack
177 gc.collect()
178 gc.collect()
179 self.assertFalse(gc.is_tracked(t), t)
180
181 def _tracked(self, t):
182 self.assertTrue(gc.is_tracked(t), t)
183 gc.collect()
184 gc.collect()
185 self.assertTrue(gc.is_tracked(t), t)
186
Benjamin Peterson02d78062010-06-27 22:44:51 +0000187 @support.cpython_only
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000188 def test_track_literals(self):
189 # Test GC-optimization of tuple literals
190 x, y, z = 1.5, "a", []
191
192 self._not_tracked(())
193 self._not_tracked((1,))
194 self._not_tracked((1, 2))
195 self._not_tracked((1, 2, "a"))
196 self._not_tracked((1, 2, (None, True, False, ()), int))
197 self._not_tracked((object(),))
198 self._not_tracked(((1, x), y, (2, 3)))
199
200 # Tuples with mutable elements are always tracked, even if those
201 # elements are not tracked right now.
202 self._tracked(([],))
203 self._tracked(([1],))
204 self._tracked(({},))
205 self._tracked((set(),))
206 self._tracked((x, y, z))
207
208 def check_track_dynamic(self, tp, always_track):
209 x, y, z = 1.5, "a", []
210
211 check = self._tracked if always_track else self._not_tracked
212 check(tp())
213 check(tp([]))
214 check(tp(set()))
215 check(tp([1, x, y]))
216 check(tp(obj for obj in [1, x, y]))
217 check(tp(set([1, x, y])))
218 check(tp(tuple([obj]) for obj in [1, x, y]))
219 check(tuple(tp([obj]) for obj in [1, x, y]))
220
221 self._tracked(tp([z]))
222 self._tracked(tp([[x, y]]))
223 self._tracked(tp([{x: y}]))
224 self._tracked(tp(obj for obj in [x, y, z]))
225 self._tracked(tp(tuple([obj]) for obj in [x, y, z]))
226 self._tracked(tuple(tp([obj]) for obj in [x, y, z]))
227
Benjamin Peterson02d78062010-06-27 22:44:51 +0000228 @support.cpython_only
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000229 def test_track_dynamic(self):
230 # Test GC-optimization of dynamically constructed tuples.
231 self.check_track_dynamic(tuple, False)
232
Benjamin Peterson02d78062010-06-27 22:44:51 +0000233 @support.cpython_only
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000234 def test_track_subtypes(self):
235 # Tuple subtypes must always be tracked
236 class MyTuple(tuple):
237 pass
238 self.check_track_dynamic(MyTuple, True)
239
Benjamin Peterson02d78062010-06-27 22:44:51 +0000240 @support.cpython_only
Antoine Pitrou6b7dfc92009-12-12 19:18:27 +0000241 def test_bug7466(self):
242 # Trying to untrack an unfinished tuple could crash Python
243 self._not_tracked(tuple(gc.collect() for i in range(101)))
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000244
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200245 def test_repr_large(self):
246 # Check the repr of large list objects
247 def check(n):
248 l = (0,) * n
249 s = repr(l)
250 self.assertEqual(s,
251 '(' + ', '.join(['0'] * n) + ')')
252 check(10) # check our checking code
253 check(1000000)
254
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000255 def test_iterator_pickle(self):
256 # Userlist iterators don't support pickling yet since
257 # they are based on generators.
258 data = self.type2test([4, 5, 6, 7])
Serhiy Storchakabad12572014-12-15 14:03:42 +0200259 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
260 itorg = iter(data)
261 d = pickle.dumps(itorg, proto)
262 it = pickle.loads(d)
263 self.assertEqual(type(itorg), type(it))
264 self.assertEqual(self.type2test(it), self.type2test(data))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000265
Serhiy Storchakabad12572014-12-15 14:03:42 +0200266 it = pickle.loads(d)
267 next(it)
268 d = pickle.dumps(it, proto)
269 self.assertEqual(self.type2test(it), self.type2test(data)[1:])
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000270
271 def test_reversed_pickle(self):
272 data = self.type2test([4, 5, 6, 7])
Serhiy Storchakabad12572014-12-15 14:03:42 +0200273 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
274 itorg = reversed(data)
275 d = pickle.dumps(itorg, proto)
276 it = pickle.loads(d)
277 self.assertEqual(type(itorg), type(it))
278 self.assertEqual(self.type2test(it), self.type2test(reversed(data)))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000279
Serhiy Storchakabad12572014-12-15 14:03:42 +0200280 it = pickle.loads(d)
281 next(it)
282 d = pickle.dumps(it, proto)
283 self.assertEqual(self.type2test(it), self.type2test(reversed(data))[1:])
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000284
Martin v. Löwis4c1730d2012-08-01 10:32:11 +0200285 def test_no_comdat_folding(self):
286 # Issue 8847: In the PGO build, the MSVC linker's COMDAT folding
287 # optimization causes failures in code that relies on distinct
288 # function addresses.
289 class T(tuple): pass
290 with self.assertRaises(TypeError):
291 [3,] + T((1,2))
292
Raymond Hettingere5bb5512014-03-30 10:12:09 -0700293 def test_lexicographic_ordering(self):
294 # Issue 21100
295 a = self.type2test([1, 2])
296 b = self.type2test([1, 2, 0])
297 c = self.type2test([1, 3])
298 self.assertLess(a, b)
299 self.assertLess(b, c)
300
Zachary Ware38c707e2015-04-13 15:00:43 -0500301if __name__ == "__main__":
302 unittest.main()