blob: c4137098e5d58a575c52e6f3c673b6a7a0dda7bc [file] [log] [blame]
Walter Dörwald1dde95d2003-12-08 11:38:45 +00001from test import test_support, seq_tests
2
3class TupleTest(seq_tests.CommonTest):
4 type2test = tuple
5
6 def test_constructors(self):
7 super(TupleTest, self).test_len()
8 # calling built-in types without argument must return empty
9 self.assertEqual(tuple(), ())
10
11 def test_truth(self):
12 super(TupleTest, self).test_truth()
13 self.assert_(not ())
14 self.assert_((42, ))
15
16 def test_len(self):
17 super(TupleTest, self).test_len()
18 self.assertEqual(len(()), 0)
19 self.assertEqual(len((0,)), 1)
20 self.assertEqual(len((0, 1, 2)), 3)
21
22 def test_iadd(self):
23 super(TupleTest, self).test_iadd()
24 u = (0, 1)
25 u2 = u
26 u += (2, 3)
27 self.assert_(u is not u2)
28
29 def test_imul(self):
30 super(TupleTest, self).test_imul()
31 u = (0, 1)
32 u2 = u
33 u *= 3
34 self.assert_(u is not u2)
35
36 def test_tupleresizebug(self):
37 # Check that a specific bug in _PyTuple_Resize() is squashed.
38 def f():
39 for i in range(1000):
40 yield i
41 self.assertEqual(list(tuple(f())), range(1000))
42
Raymond Hettinger41bd0222004-06-01 06:36:24 +000043 def test_hash(self):
44 # See SF bug 942952: Weakness in tuple hash
45 # The hash should:
46 # be non-commutative
47 # should spread-out closely spaced values
48 # should not exhibit cancellation in tuples like (x,(x,y))
49 # should be distinct from element hashes: hash(x)!=hash((x,))
50 # This test exercises those cases.
Tim Peters1f4bcf92004-06-01 18:58:04 +000051 # For a pure random hash and N=50, the expected number of occupied
52 # buckets when tossing 252,600 balls into 2**32 buckets
53 # is 252,592.6, or about 7.4 expected collisions. The
54 # standard deviation is 2.73. On a box with 64-bit hash
55 # codes, no collisions are expected. Here we accept no
56 # more than 15 collisions. Any worse and the hash function
57 # is sorely suspect.
Raymond Hettinger41bd0222004-06-01 06:36:24 +000058
59 N=50
60 base = range(N)
61 xp = [(i, j) for i in base for j in base]
62 inps = base + [(i, j) for i in base for j in xp] + \
63 [(i, j) for i in xp for j in base] + xp + zip(base)
64 collisions = len(inps) - len(set(map(hash, inps)))
65 self.assert_(collisions <= 15)
Walter Dörwald1dde95d2003-12-08 11:38:45 +000066
Raymond Hettinger5ea7e312004-09-30 07:47:20 +000067 def test_repr(self):
68 l0 = tuple()
69 l2 = (0, 1, 2)
70 a0 = self.type2test(l0)
71 a2 = self.type2test(l2)
72
73 self.assertEqual(str(a0), repr(l0))
74 self.assertEqual(str(a2), repr(l2))
75 self.assertEqual(repr(a0), "()")
76 self.assertEqual(repr(a2), "(0, 1, 2)")
77
Walter Dörwald1dde95d2003-12-08 11:38:45 +000078def test_main():
79 test_support.run_unittest(TupleTest)
80
81if __name__=="__main__":
82 test_main()