blob: c0470d6018b13f0ea8c6c87cb682003de7040ada [file] [log] [blame]
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001# Test hashlib module
2#
3# $Id$
4#
Benjamin Peterson46a99002010-01-09 18:45:30 +00005# Copyright (C) 2005-2010 Gregory P. Smith (greg@krypto.org)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00006# Licensed to PSF under a Contributor Agreement.
7#
8
Benjamin Petersona28e7022010-01-09 18:53:06 +00009import array
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000010import hashlib
Benjamin Petersona28e7022010-01-09 18:53:06 +000011import itertools
Antoine Pitrou019ff192012-05-16 16:41:26 +020012import os
Gregory P. Smithcd54e542010-01-03 00:29:15 +000013import sys
Gregory P. Smith3f61d612009-05-04 00:45:33 +000014try:
15 import threading
16except ImportError:
17 threading = None
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000018import unittest
Gregory P. Smithcd54e542010-01-03 00:29:15 +000019import warnings
Benjamin Petersonee8712c2008-05-20 21:35:26 +000020from test import support
Antoine Pitrou94190bb2011-10-04 10:22:36 +020021from test.support import _4G, bigmemtest
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000022
Gregory P. Smithcd54e542010-01-03 00:29:15 +000023# Were we compiled --with-pydebug or with #define Py_DEBUG?
24COMPILED_WITH_PYDEBUG = hasattr(sys, 'gettotalrefcount')
25
26
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000027def hexstr(s):
Guido van Rossum5ed033b2007-07-09 14:29:40 +000028 assert isinstance(s, bytes), repr(s)
Guido van Rossum558ca842007-07-10 20:31:05 +000029 h = "0123456789abcdef"
30 r = ''
Guido van Rossum5ed033b2007-07-09 14:29:40 +000031 for i in s:
Guido van Rossum558ca842007-07-10 20:31:05 +000032 r += h[(i >> 4) & 0xF] + h[i & 0xF]
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000033 return r
34
35
36class HashLibTestCase(unittest.TestCase):
37 supported_hash_names = ( 'md5', 'MD5', 'sha1', 'SHA1',
38 'sha224', 'SHA224', 'sha256', 'SHA256',
39 'sha384', 'SHA384', 'sha512', 'SHA512' )
40
Antoine Pitrou019ff192012-05-16 16:41:26 +020041 # Issue #14693: fallback modules are always compiled under POSIX
42 _warn_on_extension_import = os.name == 'posix' or COMPILED_WITH_PYDEBUG
Gregory P. Smithcd54e542010-01-03 00:29:15 +000043
44 def _conditional_import_module(self, module_name):
45 """Import a module and return a reference to it or None on failure."""
46 try:
47 exec('import '+module_name)
48 except ImportError as error:
49 if self._warn_on_extension_import:
50 warnings.warn('Did a C extension fail to compile? %s' % error)
51 return locals().get(module_name)
52
53 def __init__(self, *args, **kwargs):
54 algorithms = set()
55 for algorithm in self.supported_hash_names:
56 algorithms.add(algorithm.lower())
57 self.constructors_to_test = {}
58 for algorithm in algorithms:
59 self.constructors_to_test[algorithm] = set()
60
61 # For each algorithm, test the direct constructor and the use
62 # of hashlib.new given the algorithm name.
63 for algorithm, constructors in self.constructors_to_test.items():
64 constructors.add(getattr(hashlib, algorithm))
65 def _test_algorithm_via_hashlib_new(data=None, _alg=algorithm):
66 if data is None:
67 return hashlib.new(_alg)
68 return hashlib.new(_alg, data)
69 constructors.add(_test_algorithm_via_hashlib_new)
70
71 _hashlib = self._conditional_import_module('_hashlib')
72 if _hashlib:
73 # These two algorithms should always be present when this module
74 # is compiled. If not, something was compiled wrong.
75 assert hasattr(_hashlib, 'openssl_md5')
76 assert hasattr(_hashlib, 'openssl_sha1')
77 for algorithm, constructors in self.constructors_to_test.items():
78 constructor = getattr(_hashlib, 'openssl_'+algorithm, None)
79 if constructor:
80 constructors.add(constructor)
81
82 _md5 = self._conditional_import_module('_md5')
83 if _md5:
Gregory P. Smithb04ded42010-01-03 00:38:10 +000084 self.constructors_to_test['md5'].add(_md5.md5)
85 _sha1 = self._conditional_import_module('_sha1')
86 if _sha1:
87 self.constructors_to_test['sha1'].add(_sha1.sha1)
Gregory P. Smithcd54e542010-01-03 00:29:15 +000088 _sha256 = self._conditional_import_module('_sha256')
89 if _sha256:
90 self.constructors_to_test['sha224'].add(_sha256.sha224)
91 self.constructors_to_test['sha256'].add(_sha256.sha256)
92 _sha512 = self._conditional_import_module('_sha512')
93 if _sha512:
94 self.constructors_to_test['sha384'].add(_sha512.sha384)
95 self.constructors_to_test['sha512'].add(_sha512.sha512)
96
97 super(HashLibTestCase, self).__init__(*args, **kwargs)
98
Christian Heimes65aa5732013-07-30 15:33:30 +020099 @property
100 def hash_constructors(self):
101 constructors = self.constructors_to_test.values()
102 return itertools.chain.from_iterable(constructors)
103
Benjamin Petersona28e7022010-01-09 18:53:06 +0000104 def test_hash_array(self):
105 a = array.array("b", range(10))
Christian Heimes65aa5732013-07-30 15:33:30 +0200106 for cons in self.hash_constructors:
Benjamin Petersona28e7022010-01-09 18:53:06 +0000107 c = cons(a)
108 c.hexdigest()
109
Gregory P. Smith13b55292010-09-06 08:30:23 +0000110 def test_algorithms_guaranteed(self):
111 self.assertEqual(hashlib.algorithms_guaranteed,
Raymond Hettingerbf1d2bc2011-01-24 04:52:27 +0000112 set(_algo for _algo in self.supported_hash_names
Gregory P. Smith86508cc2010-03-01 02:05:26 +0000113 if _algo.islower()))
114
Gregory P. Smith13b55292010-09-06 08:30:23 +0000115 def test_algorithms_available(self):
116 self.assertTrue(set(hashlib.algorithms_guaranteed).
117 issubset(hashlib.algorithms_available))
118
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000119 def test_unknown_hash(self):
Amaury Forgeot d'Arc3a3dc172012-06-29 01:53:13 +0200120 self.assertRaises(ValueError, hashlib.new, 'spam spam spam spam spam')
121 self.assertRaises(TypeError, hashlib.new, 1)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000122
Gregory P. Smith12c9d022011-05-14 15:15:49 -0700123 def test_get_builtin_constructor(self):
124 get_builtin_constructor = hashlib.__dict__[
125 '__get_builtin_constructor']
126 self.assertRaises(ValueError, get_builtin_constructor, 'test')
127 try:
128 import _md5
129 except ImportError:
130 pass
131 # This forces an ImportError for "import _md5" statements
132 sys.modules['_md5'] = None
133 try:
134 self.assertRaises(ValueError, get_builtin_constructor, 'md5')
135 finally:
136 if '_md5' in locals():
137 sys.modules['_md5'] = _md5
138 else:
139 del sys.modules['_md5']
Gregory P. Smith76c28f72012-07-21 21:19:53 -0700140 self.assertRaises(TypeError, get_builtin_constructor, 3)
Gregory P. Smith12c9d022011-05-14 15:15:49 -0700141
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000142 def test_hexdigest(self):
Christian Heimes65aa5732013-07-30 15:33:30 +0200143 for cons in self.hash_constructors:
144 h = cons()
Guido van Rossum5ed033b2007-07-09 14:29:40 +0000145 assert isinstance(h.digest(), bytes), name
146 self.assertEqual(hexstr(h.digest()), h.hexdigest())
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000147
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000148 def test_large_update(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000149 aas = b'a' * 128
150 bees = b'b' * 127
151 cees = b'c' * 126
Christian Heimes65aa5732013-07-30 15:33:30 +0200152 dees = b'd' * 2048 # HASHLIB_GIL_MINSIZE
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000153
Christian Heimes65aa5732013-07-30 15:33:30 +0200154 for cons in self.hash_constructors:
155 m1 = cons()
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000156 m1.update(aas)
157 m1.update(bees)
158 m1.update(cees)
Christian Heimes65aa5732013-07-30 15:33:30 +0200159 m1.update(dees)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000160
Christian Heimes65aa5732013-07-30 15:33:30 +0200161 m2 = cons()
162 m2.update(aas + bees + cees + dees)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000163 self.assertEqual(m1.digest(), m2.digest())
164
Christian Heimes65aa5732013-07-30 15:33:30 +0200165 m3 = cons(aas + bees + cees + dees)
166 self.assertEqual(m1.digest(), m3.digest())
167
168 # verify copy() doesn't touch original
169 m4 = cons(aas + bees + cees)
170 m4_digest = m4.digest()
171 m4_copy = m4.copy()
172 m4_copy.update(dees)
173 self.assertEqual(m1.digest(), m4_copy.digest())
174 self.assertEqual(m4.digest(), m4_digest)
175
176 def check(self, name, data, hexdigest):
177 hexdigest = hexdigest.lower()
Gregory P. Smithcd54e542010-01-03 00:29:15 +0000178 constructors = self.constructors_to_test[name]
179 # 2 is for hashlib.name(...) and hashlib.new(name, ...)
180 self.assertGreaterEqual(len(constructors), 2)
181 for hash_object_constructor in constructors:
Christian Heimes65aa5732013-07-30 15:33:30 +0200182 m = hash_object_constructor(data)
183 computed = m.hexdigest()
Gregory P. Smithcd54e542010-01-03 00:29:15 +0000184 self.assertEqual(
Christian Heimes65aa5732013-07-30 15:33:30 +0200185 computed, hexdigest,
Gregory P. Smithcd54e542010-01-03 00:29:15 +0000186 "Hash algorithm %s constructed using %s returned hexdigest"
187 " %r for %d byte input data that should have hashed to %r."
188 % (name, hash_object_constructor,
Christian Heimes65aa5732013-07-30 15:33:30 +0200189 computed, len(data), hexdigest))
190 computed = m.digest()
191 digest = bytes.fromhex(hexdigest)
192 self.assertEqual(computed, digest)
193 self.assertEqual(len(digest), m.digest_size)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000194
Gregory P. Smith365a1862009-02-12 07:35:29 +0000195 def check_no_unicode(self, algorithm_name):
196 # Unicode objects are not allowed as input.
Gregory P. Smithcd54e542010-01-03 00:29:15 +0000197 constructors = self.constructors_to_test[algorithm_name]
198 for hash_object_constructor in constructors:
199 self.assertRaises(TypeError, hash_object_constructor, 'spam')
Gregory P. Smith365a1862009-02-12 07:35:29 +0000200
201 def test_no_unicode(self):
202 self.check_no_unicode('md5')
203 self.check_no_unicode('sha1')
204 self.check_no_unicode('sha224')
205 self.check_no_unicode('sha256')
206 self.check_no_unicode('sha384')
207 self.check_no_unicode('sha512')
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000208
Christian Heimes65aa5732013-07-30 15:33:30 +0200209 def check_blocksize_name(self, name, block_size=0, digest_size=0):
210 constructors = self.constructors_to_test[name]
211 for hash_object_constructor in constructors:
212 m = hash_object_constructor()
213 self.assertEqual(m.block_size, block_size)
214 self.assertEqual(m.digest_size, digest_size)
215 self.assertEqual(len(m.digest()), digest_size)
216 self.assertEqual(m.name.lower(), name.lower())
217 self.assertIn(name.split("_")[0], repr(m).lower())
218
219 def test_blocksize_name(self):
220 self.check_blocksize_name('md5', 64, 16)
221 self.check_blocksize_name('sha1', 64, 20)
222 self.check_blocksize_name('sha224', 64, 28)
223 self.check_blocksize_name('sha256', 64, 32)
224 self.check_blocksize_name('sha384', 128, 48)
225 self.check_blocksize_name('sha512', 128, 64)
226
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000227 def test_case_md5_0(self):
Guido van Rossum558ca842007-07-10 20:31:05 +0000228 self.check('md5', b'', 'd41d8cd98f00b204e9800998ecf8427e')
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000229
230 def test_case_md5_1(self):
Guido van Rossum558ca842007-07-10 20:31:05 +0000231 self.check('md5', b'abc', '900150983cd24fb0d6963f7d28e17f72')
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000232
233 def test_case_md5_2(self):
Guido van Rossum5ed033b2007-07-09 14:29:40 +0000234 self.check('md5',
235 b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
Guido van Rossum558ca842007-07-10 20:31:05 +0000236 'd174ab98d277d9f5a5611c2c9f419d9f')
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000237
Serhiy Storchaka4847e4e2014-01-10 13:37:54 +0200238 @unittest.skipIf(sys.maxsize < _4G + 5, 'test cannot run on 32-bit systems')
239 @bigmemtest(size=_4G + 5, memuse=1, dry_run=False)
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000240 def test_case_md5_huge(self, size):
Serhiy Storchaka4847e4e2014-01-10 13:37:54 +0200241 self.check('md5', b'A'*size, 'c9af2dff37468ce5dfee8f2cfc0a9c6d')
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000242
Serhiy Storchaka4847e4e2014-01-10 13:37:54 +0200243 @unittest.skipIf(sys.maxsize < _4G - 1, 'test cannot run on 32-bit systems')
244 @bigmemtest(size=_4G - 1, memuse=1, dry_run=False)
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000245 def test_case_md5_uintmax(self, size):
Serhiy Storchaka4847e4e2014-01-10 13:37:54 +0200246 self.check('md5', b'A'*size, '28138d306ff1b8281f1a9067e1a1a2b3')
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000247
248 # use the three examples from Federal Information Processing Standards
249 # Publication 180-1, Secure Hash Standard, 1995 April 17
250 # http://www.itl.nist.gov/div897/pubs/fip180-1.htm
251
252 def test_case_sha1_0(self):
Guido van Rossum5ed033b2007-07-09 14:29:40 +0000253 self.check('sha1', b"",
Guido van Rossum558ca842007-07-10 20:31:05 +0000254 "da39a3ee5e6b4b0d3255bfef95601890afd80709")
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000255
256 def test_case_sha1_1(self):
Guido van Rossum5ed033b2007-07-09 14:29:40 +0000257 self.check('sha1', b"abc",
Guido van Rossum558ca842007-07-10 20:31:05 +0000258 "a9993e364706816aba3e25717850c26c9cd0d89d")
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000259
260 def test_case_sha1_2(self):
Guido van Rossum5ed033b2007-07-09 14:29:40 +0000261 self.check('sha1',
262 b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
Guido van Rossum558ca842007-07-10 20:31:05 +0000263 "84983e441c3bd26ebaae4aa1f95129e5e54670f1")
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000264
265 def test_case_sha1_3(self):
Guido van Rossum5ed033b2007-07-09 14:29:40 +0000266 self.check('sha1', b"a" * 1000000,
Guido van Rossum558ca842007-07-10 20:31:05 +0000267 "34aa973cd4c4daa4f61eeb2bdbad27316534016f")
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000268
269
270 # use the examples from Federal Information Processing Standards
271 # Publication 180-2, Secure Hash Standard, 2002 August 1
272 # http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
273
274 def test_case_sha224_0(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000275 self.check('sha224', b"",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000276 "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f")
277
278 def test_case_sha224_1(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000279 self.check('sha224', b"abc",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000280 "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7")
281
282 def test_case_sha224_2(self):
283 self.check('sha224',
Guido van Rossume22905a2007-08-27 23:09:25 +0000284 b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000285 "75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525")
286
287 def test_case_sha224_3(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000288 self.check('sha224', b"a" * 1000000,
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000289 "20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67")
290
291
292 def test_case_sha256_0(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000293 self.check('sha256', b"",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000294 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
295
296 def test_case_sha256_1(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000297 self.check('sha256', b"abc",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000298 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
299
300 def test_case_sha256_2(self):
301 self.check('sha256',
Guido van Rossume22905a2007-08-27 23:09:25 +0000302 b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000303 "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1")
304
305 def test_case_sha256_3(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000306 self.check('sha256', b"a" * 1000000,
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000307 "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0")
308
309
310 def test_case_sha384_0(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000311 self.check('sha384', b"",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000312 "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da"+
313 "274edebfe76f65fbd51ad2f14898b95b")
314
315 def test_case_sha384_1(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000316 self.check('sha384', b"abc",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000317 "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed"+
318 "8086072ba1e7cc2358baeca134c825a7")
319
320 def test_case_sha384_2(self):
321 self.check('sha384',
Guido van Rossume22905a2007-08-27 23:09:25 +0000322 b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn"+
323 b"hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000324 "09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712"+
325 "fcc7c71a557e2db966c3e9fa91746039")
326
327 def test_case_sha384_3(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000328 self.check('sha384', b"a" * 1000000,
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000329 "9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b"+
330 "07b8b3dc38ecc4ebae97ddd87f3d8985")
331
332
333 def test_case_sha512_0(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000334 self.check('sha512', b"",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000335 "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce"+
336 "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e")
337
338 def test_case_sha512_1(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000339 self.check('sha512', b"abc",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000340 "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a"+
341 "2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f")
342
343 def test_case_sha512_2(self):
344 self.check('sha512',
Guido van Rossume22905a2007-08-27 23:09:25 +0000345 b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn"+
346 b"hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000347 "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018"+
348 "501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909")
349
350 def test_case_sha512_3(self):
Guido van Rossume22905a2007-08-27 23:09:25 +0000351 self.check('sha512', b"a" * 1000000,
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000352 "e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb"+
353 "de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b")
354
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000355 def test_gil(self):
356 # Check things work fine with an input larger than the size required
357 # for multithreaded operation (which is hardwired to 2048).
358 gil_minsize = 2048
359
Christian Heimes65aa5732013-07-30 15:33:30 +0200360 for cons in self.hash_constructors:
361 m = cons()
362 m.update(b'1')
363 m.update(b'#' * gil_minsize)
364 m.update(b'1')
365
366 m = cons(b'x' * gil_minsize)
367 m.update(b'1')
368
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000369 m = hashlib.md5()
370 m.update(b'1')
371 m.update(b'#' * gil_minsize)
372 m.update(b'1')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000373 self.assertEqual(m.hexdigest(), 'cb1e1a2cbc80be75e19935d621fb9b21')
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000374
375 m = hashlib.md5(b'x' * gil_minsize)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000376 self.assertEqual(m.hexdigest(), 'cfb767f225d58469c5de3632a8803958')
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000377
Victor Stinner45df8202010-04-28 22:31:17 +0000378 @unittest.skipUnless(threading, 'Threading required for this test.')
379 @support.reap_threads
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000380 def test_threaded_hashing(self):
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000381 # Updating the same hash object from several threads at once
382 # using data chunk sizes containing the same byte sequences.
383 #
384 # If the internal locks are working to prevent multiple
385 # updates on the same object from running at once, the resulting
386 # hash will be the same as doing it single threaded upfront.
387 hasher = hashlib.sha1()
388 num_threads = 5
389 smallest_data = b'swineflu'
390 data = smallest_data*200000
391 expected_hash = hashlib.sha1(data*num_threads).hexdigest()
392
393 def hash_in_chunks(chunk_size, event):
394 index = 0
395 while index < len(data):
396 hasher.update(data[index:index+chunk_size])
397 index += chunk_size
398 event.set()
399
400 events = []
401 for threadnum in range(num_threads):
402 chunk_size = len(data) // (10**threadnum)
403 assert chunk_size > 0
404 assert chunk_size % len(smallest_data) == 0
405 event = threading.Event()
406 events.append(event)
407 threading.Thread(target=hash_in_chunks,
408 args=(chunk_size, event)).start()
409
410 for event in events:
411 event.wait()
412
413 self.assertEqual(expected_hash, hasher.hexdigest())
414
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000415def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000416 support.run_unittest(HashLibTestCase)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000417
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000418if __name__ == "__main__":
419 test_main()