blob: a3f40dd07d62e63f910b827c2bb23b49bf4f042d [file] [log] [blame]
Walter Dörwald1dde95d2003-12-08 11:38:45 +00001import unittest
2from test import test_support, seq_tests
3
4class TupleTest(seq_tests.CommonTest):
5 type2test = tuple
6
7 def test_constructors(self):
8 super(TupleTest, self).test_len()
9 # calling built-in types without argument must return empty
10 self.assertEqual(tuple(), ())
11
12 def test_truth(self):
13 super(TupleTest, self).test_truth()
14 self.assert_(not ())
15 self.assert_((42, ))
16
17 def test_len(self):
18 super(TupleTest, self).test_len()
19 self.assertEqual(len(()), 0)
20 self.assertEqual(len((0,)), 1)
21 self.assertEqual(len((0, 1, 2)), 3)
22
23 def test_iadd(self):
24 super(TupleTest, self).test_iadd()
25 u = (0, 1)
26 u2 = u
27 u += (2, 3)
28 self.assert_(u is not u2)
29
30 def test_imul(self):
31 super(TupleTest, self).test_imul()
32 u = (0, 1)
33 u2 = u
34 u *= 3
35 self.assert_(u is not u2)
36
37 def test_tupleresizebug(self):
38 # Check that a specific bug in _PyTuple_Resize() is squashed.
39 def f():
40 for i in range(1000):
41 yield i
42 self.assertEqual(list(tuple(f())), range(1000))
43
Raymond Hettinger41bd0222004-06-01 06:36:24 +000044 def test_hash(self):
45 # See SF bug 942952: Weakness in tuple hash
46 # The hash should:
47 # be non-commutative
48 # should spread-out closely spaced values
49 # should not exhibit cancellation in tuples like (x,(x,y))
50 # should be distinct from element hashes: hash(x)!=hash((x,))
51 # This test exercises those cases.
52 # For a pure random hash and N=50, the expected number of collisions
53 # is 7.3. Here we allow twice that number.
54 # Any worse and the hash function is sorely suspect.
55
56 N=50
57 base = range(N)
58 xp = [(i, j) for i in base for j in base]
59 inps = base + [(i, j) for i in base for j in xp] + \
60 [(i, j) for i in xp for j in base] + xp + zip(base)
61 collisions = len(inps) - len(set(map(hash, inps)))
62 self.assert_(collisions <= 15)
Walter Dörwald1dde95d2003-12-08 11:38:45 +000063
64def test_main():
65 test_support.run_unittest(TupleTest)
66
67if __name__=="__main__":
68 test_main()