Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(30448)

Delta Between Two Patch Sets: Lib/test/test_hmac.py

Issue 16510: Using appropriate checks in tests
Left Patch Set: Created 5 years, 10 months ago
Right Patch Set: Created 5 years, 7 months ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
Left: Side by side diff | Download
Right: Side by side diff | Download
« no previous file with change/comment | « Lib/test/test_gzip.py ('k') | Lib/test/test_inspect.py » ('j') | no next file with change/comment »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
LEFTRIGHT
1 import functools
1 import hmac 2 import hmac
2 import hashlib 3 import hashlib
3 import unittest 4 import unittest
4 import warnings 5 import warnings
5 from test import support 6 from test import support
6 7
8
9 def ignore_warning(func):
10 @functools.wraps(func)
11 def wrapper(*args, **kwargs):
12 with warnings.catch_warnings():
13 warnings.filterwarnings("ignore",
14 category=PendingDeprecationWarning)
15 return func(*args, **kwargs)
16 return wrapper
17
18
7 class TestVectorsTestCase(unittest.TestCase): 19 class TestVectorsTestCase(unittest.TestCase):
8 20
9 def test_md5_vectors(self): 21 def test_md5_vectors(self):
10 # Test the HMAC module against test vectors from the RFC. 22 # Test the HMAC module against test vectors from the RFC.
11 23
12 def md5test(key, data, digest): 24 def md5test(key, data, digest):
13 h = hmac.HMAC(key, data) 25 h = hmac.HMAC(key, data, digestmod=hashlib.md5)
14 self.assertEqual(h.hexdigest().upper(), digest.upper()) 26 self.assertEqual(h.hexdigest().upper(), digest.upper())
27 self.assertEqual(h.name, "hmac-md5")
28 self.assertEqual(h.digest_size, 16)
29 self.assertEqual(h.block_size, 64)
30
31 h = hmac.HMAC(key, data, digestmod='md5')
32 self.assertEqual(h.hexdigest().upper(), digest.upper())
33 self.assertEqual(h.name, "hmac-md5")
34 self.assertEqual(h.digest_size, 16)
35 self.assertEqual(h.block_size, 64)
36
15 37
16 md5test(b"\x0b" * 16, 38 md5test(b"\x0b" * 16,
17 b"Hi There", 39 b"Hi There",
18 "9294727A3638BB1C13F48EF8158BFC9D") 40 "9294727A3638BB1C13F48EF8158BFC9D")
19 41
20 md5test(b"Jefe", 42 md5test(b"Jefe",
21 b"what do ya want for nothing?", 43 b"what do ya want for nothing?",
22 "750c783e6ab0b503eaa86e310a5db738") 44 "750c783e6ab0b503eaa86e310a5db738")
23 45
24 md5test(b"\xaa" * 16, 46 md5test(b"\xaa" * 16,
(...skipping 14 matching lines...) Expand all
39 61
40 md5test(b"\xaa" * 80, 62 md5test(b"\xaa" * 80,
41 (b"Test Using Larger Than Block-Size Key " 63 (b"Test Using Larger Than Block-Size Key "
42 b"and Larger Than One Block-Size Data"), 64 b"and Larger Than One Block-Size Data"),
43 "6f630fad67cda0ee1fb1f562db3aa53e") 65 "6f630fad67cda0ee1fb1f562db3aa53e")
44 66
45 def test_sha_vectors(self): 67 def test_sha_vectors(self):
46 def shatest(key, data, digest): 68 def shatest(key, data, digest):
47 h = hmac.HMAC(key, data, digestmod=hashlib.sha1) 69 h = hmac.HMAC(key, data, digestmod=hashlib.sha1)
48 self.assertEqual(h.hexdigest().upper(), digest.upper()) 70 self.assertEqual(h.hexdigest().upper(), digest.upper())
71 self.assertEqual(h.name, "hmac-sha1")
72 self.assertEqual(h.digest_size, 20)
73 self.assertEqual(h.block_size, 64)
74
75 h = hmac.HMAC(key, data, digestmod='sha1')
76 self.assertEqual(h.hexdigest().upper(), digest.upper())
77 self.assertEqual(h.name, "hmac-sha1")
78 self.assertEqual(h.digest_size, 20)
79 self.assertEqual(h.block_size, 64)
80
49 81
50 shatest(b"\x0b" * 20, 82 shatest(b"\x0b" * 20,
51 b"Hi There", 83 b"Hi There",
52 "b617318655057264e28bc0b6fb378c8ef146be00") 84 "b617318655057264e28bc0b6fb378c8ef146be00")
53 85
54 shatest(b"Jefe", 86 shatest(b"Jefe",
55 b"what do ya want for nothing?", 87 b"what do ya want for nothing?",
56 "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79") 88 "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79")
57 89
58 shatest(b"\xAA" * 20, 90 shatest(b"\xAA" * 20,
(...skipping 10 matching lines...) Expand all
69 101
70 shatest(b"\xAA" * 80, 102 shatest(b"\xAA" * 80,
71 b"Test Using Larger Than Block-Size Key - Hash Key First", 103 b"Test Using Larger Than Block-Size Key - Hash Key First",
72 "aa4ae5e15272d00e95705637ce8a3b55ed402112") 104 "aa4ae5e15272d00e95705637ce8a3b55ed402112")
73 105
74 shatest(b"\xAA" * 80, 106 shatest(b"\xAA" * 80,
75 (b"Test Using Larger Than Block-Size Key " 107 (b"Test Using Larger Than Block-Size Key "
76 b"and Larger Than One Block-Size Data"), 108 b"and Larger Than One Block-Size Data"),
77 "e8e99d0f45237d786d6bbaa7965c7808bbff1a91") 109 "e8e99d0f45237d786d6bbaa7965c7808bbff1a91")
78 110
79 def _rfc4231_test_cases(self, hashfunc): 111 def _rfc4231_test_cases(self, hashfunc, hash_name, digest_size, block_size):
80 def hmactest(key, data, hexdigests): 112 def hmactest(key, data, hexdigests):
113 hmac_name = "hmac-" + hash_name
81 h = hmac.HMAC(key, data, digestmod=hashfunc) 114 h = hmac.HMAC(key, data, digestmod=hashfunc)
82 self.assertEqual(h.hexdigest().lower(), hexdigests[hashfunc]) 115 self.assertEqual(h.hexdigest().lower(), hexdigests[hashfunc])
116 self.assertEqual(h.name, hmac_name)
117 self.assertEqual(h.digest_size, digest_size)
118 self.assertEqual(h.block_size, block_size)
119
120 h = hmac.HMAC(key, data, digestmod=hash_name)
121 self.assertEqual(h.hexdigest().lower(), hexdigests[hashfunc])
122 self.assertEqual(h.name, hmac_name)
123 self.assertEqual(h.digest_size, digest_size)
124 self.assertEqual(h.block_size, block_size)
125
83 126
84 # 4.2. Test Case 1 127 # 4.2. Test Case 1
85 hmactest(key = b'\x0b'*20, 128 hmactest(key = b'\x0b'*20,
86 data = b'Hi There', 129 data = b'Hi There',
87 hexdigests = { 130 hexdigests = {
88 hashlib.sha224: '896fb1128abbdf196832107cd49df33f' 131 hashlib.sha224: '896fb1128abbdf196832107cd49df33f'
89 '47b4b1169912ba4f53684b22', 132 '47b4b1169912ba4f53684b22',
90 hashlib.sha256: 'b0344c61d8db38535ca8afceaf0bf12b' 133 hashlib.sha256: 'b0344c61d8db38535ca8afceaf0bf12b'
91 '881dc200c9833da726e9376c2e32cff7', 134 '881dc200c9833da726e9376c2e32cff7',
92 hashlib.sha384: 'afd03944d84895626b0825f4ab46907f' 135 hashlib.sha384: 'afd03944d84895626b0825f4ab46907f'
(...skipping 89 matching lines...) Expand 10 before | Expand all | Expand 10 after
182 hashlib.sha384: '6617178e941f020d351e2f254e8fd32c' 225 hashlib.sha384: '6617178e941f020d351e2f254e8fd32c'
183 '602420feb0b8fb9adccebb82461e99c5' 226 '602420feb0b8fb9adccebb82461e99c5'
184 'a678cc31e799176d3860e6110c46523e', 227 'a678cc31e799176d3860e6110c46523e',
185 hashlib.sha512: 'e37b6a775dc87dbaa4dfa9f96e5e3ffd' 228 hashlib.sha512: 'e37b6a775dc87dbaa4dfa9f96e5e3ffd'
186 'debd71f8867289865df5a32d20cdc944' 229 'debd71f8867289865df5a32d20cdc944'
187 'b6022cac3c4982b10d5eeb55c3e4de15' 230 'b6022cac3c4982b10d5eeb55c3e4de15'
188 '134676fb6de0446065c97440fa8c6a58', 231 '134676fb6de0446065c97440fa8c6a58',
189 }) 232 })
190 233
191 def test_sha224_rfc4231(self): 234 def test_sha224_rfc4231(self):
192 self._rfc4231_test_cases(hashlib.sha224) 235 self._rfc4231_test_cases(hashlib.sha224, 'sha224', 28, 64)
193 236
194 def test_sha256_rfc4231(self): 237 def test_sha256_rfc4231(self):
195 self._rfc4231_test_cases(hashlib.sha256) 238 self._rfc4231_test_cases(hashlib.sha256, 'sha256', 32, 64)
196 239
197 def test_sha384_rfc4231(self): 240 def test_sha384_rfc4231(self):
198 self._rfc4231_test_cases(hashlib.sha384) 241 self._rfc4231_test_cases(hashlib.sha384, 'sha384', 48, 128)
199 242
200 def test_sha512_rfc4231(self): 243 def test_sha512_rfc4231(self):
201 self._rfc4231_test_cases(hashlib.sha512) 244 self._rfc4231_test_cases(hashlib.sha512, 'sha512', 64, 128)
202 245
203 def test_legacy_block_size_warnings(self): 246 def test_legacy_block_size_warnings(self):
204 class MockCrazyHash(object): 247 class MockCrazyHash(object):
205 """Ain't no block_size attribute here.""" 248 """Ain't no block_size attribute here."""
206 def __init__(self, *args): 249 def __init__(self, *args):
207 self._x = hashlib.sha1(*args) 250 self._x = hashlib.sha1(*args)
208 self.digest_size = self._x.digest_size 251 self.digest_size = self._x.digest_size
209 def update(self, v): 252 def update(self, v):
210 self._x.update(v) 253 self._x.update(v)
211 def digest(self): 254 def digest(self):
212 return self._x.digest() 255 return self._x.digest()
213 256
214 with warnings.catch_warnings(): 257 with warnings.catch_warnings():
215 warnings.simplefilter('error', RuntimeWarning) 258 warnings.simplefilter('error', RuntimeWarning)
216 with self.assertRaises(RuntimeWarning): 259 with self.assertRaises(RuntimeWarning):
217 hmac.HMAC(b'a', b'b', digestmod=MockCrazyHash) 260 hmac.HMAC(b'a', b'b', digestmod=MockCrazyHash)
218 self.fail('Expected warning about missing block_size') 261 self.fail('Expected warning about missing block_size')
219 262
220 MockCrazyHash.block_size = 1 263 MockCrazyHash.block_size = 1
221 with self.assertRaises(RuntimeWarning): 264 with self.assertRaises(RuntimeWarning):
222 hmac.HMAC(b'a', b'b', digestmod=MockCrazyHash) 265 hmac.HMAC(b'a', b'b', digestmod=MockCrazyHash)
223 self.fail('Expected warning about small block_size') 266 self.fail('Expected warning about small block_size')
224 267
268 def test_with_digestmod_warning(self):
269 with self.assertWarns(PendingDeprecationWarning):
270 key = b"\x0b" * 16
271 data = b"Hi There"
272 digest = "9294727A3638BB1C13F48EF8158BFC9D"
273 h = hmac.HMAC(key, data)
274 self.assertEqual(h.hexdigest().upper(), digest)
225 275
226 276
227 class ConstructorTestCase(unittest.TestCase): 277 class ConstructorTestCase(unittest.TestCase):
228 278
279 @ignore_warning
229 def test_normal(self): 280 def test_normal(self):
230 # Standard constructor call. 281 # Standard constructor call.
231 failed = 0 282 failed = 0
232 try: 283 try:
233 h = hmac.HMAC(b"key") 284 h = hmac.HMAC(b"key")
234 except: 285 except Exception:
235 self.fail("Standard constructor call raised exception.") 286 self.fail("Standard constructor call raised exception.")
236 287
288 @ignore_warning
237 def test_with_str_key(self): 289 def test_with_str_key(self):
238 # Pass a key of type str, which is an error, because it expects a key 290 # Pass a key of type str, which is an error, because it expects a key
239 # of type bytes 291 # of type bytes
240 with self.assertRaises(TypeError): 292 with self.assertRaises(TypeError):
241 h = hmac.HMAC("key") 293 h = hmac.HMAC("key")
242 294
295 @ignore_warning
243 def test_dot_new_with_str_key(self): 296 def test_dot_new_with_str_key(self):
244 # Pass a key of type str, which is an error, because it expects a key 297 # Pass a key of type str, which is an error, because it expects a key
245 # of type bytes 298 # of type bytes
246 with self.assertRaises(TypeError): 299 with self.assertRaises(TypeError):
247 h = hmac.new("key") 300 h = hmac.new("key")
248 301
302 @ignore_warning
249 def test_withtext(self): 303 def test_withtext(self):
250 # Constructor call with text. 304 # Constructor call with text.
251 try: 305 try:
252 h = hmac.HMAC(b"key", b"hash this!") 306 h = hmac.HMAC(b"key", b"hash this!")
253 except: 307 except Exception:
254 self.fail("Constructor call with text argument raised exception.") 308 self.fail("Constructor call with text argument raised exception.")
309 self.assertEqual(h.hexdigest(), '34325b639da4cfd95735b381e28cb864')
255 310
256 def test_with_bytearray(self): 311 def test_with_bytearray(self):
257 try: 312 try:
258 h = hmac.HMAC(bytearray(b"key"), bytearray(b"hash this!")) 313 h = hmac.HMAC(bytearray(b"key"), bytearray(b"hash this!"),
259 self.assertEqual(h.hexdigest(), '34325b639da4cfd95735b381e28cb864') 314 digestmod="md5")
260 except: 315 except Exception:
261 self.fail("Constructor call with bytearray arguments raised exceptio n.") 316 self.fail("Constructor call with bytearray arguments raised exceptio n.")
317 self.assertEqual(h.hexdigest(), '34325b639da4cfd95735b381e28cb864')
262 318
263 def test_with_memoryview_msg(self): 319 def test_with_memoryview_msg(self):
264 try: 320 try:
265 h = hmac.HMAC(b"key", memoryview(b"hash this!")) 321 h = hmac.HMAC(b"key", memoryview(b"hash this!"), digestmod="md5")
266 self.assertEqual(h.hexdigest(), '34325b639da4cfd95735b381e28cb864') 322 except Exception:
267 except:
268 self.fail("Constructor call with memoryview msg raised exception.") 323 self.fail("Constructor call with memoryview msg raised exception.")
324 self.assertEqual(h.hexdigest(), '34325b639da4cfd95735b381e28cb864')
269 325
270 def test_withmodule(self): 326 def test_withmodule(self):
271 # Constructor call with text and digest module. 327 # Constructor call with text and digest module.
272 try: 328 try:
273 h = hmac.HMAC(b"key", b"", hashlib.sha1) 329 h = hmac.HMAC(b"key", b"", hashlib.sha1)
274 except: 330 except Exception:
275 self.fail("Constructor call with hashlib.sha1 raised exception.") 331 self.fail("Constructor call with hashlib.sha1 raised exception.")
276 332
277 class SanityTestCase(unittest.TestCase): 333 class SanityTestCase(unittest.TestCase):
278 334
335 @ignore_warning
279 def test_default_is_md5(self): 336 def test_default_is_md5(self):
280 # Testing if HMAC defaults to MD5 algorithm. 337 # Testing if HMAC defaults to MD5 algorithm.
281 # NOTE: this whitebox test depends on the hmac class internals 338 # NOTE: this whitebox test depends on the hmac class internals
282 h = hmac.HMAC(b"key") 339 h = hmac.HMAC(b"key")
283 self.assertEqual(h.digest_cons, hashlib.md5) 340 self.assertEqual(h.digest_cons, hashlib.md5)
284 341
285 def test_exercise_all_methods(self): 342 def test_exercise_all_methods(self):
286 # Exercising all methods once. 343 # Exercising all methods once.
287 # This must not raise any exceptions 344 # This must not raise any exceptions
288 try: 345 try:
289 h = hmac.HMAC(b"my secret key") 346 h = hmac.HMAC(b"my secret key", digestmod="md5")
290 h.update(b"compute the hash of this text!") 347 h.update(b"compute the hash of this text!")
291 dig = h.digest() 348 dig = h.digest()
292 dig = h.hexdigest() 349 dig = h.hexdigest()
293 h2 = h.copy() 350 h2 = h.copy()
294 except: 351 except Exception:
295 self.fail("Exception raised during normal usage of HMAC class.") 352 self.fail("Exception raised during normal usage of HMAC class.")
296 353
297 class CopyTestCase(unittest.TestCase): 354 class CopyTestCase(unittest.TestCase):
298 355
299 def test_attributes(self): 356 def test_attributes(self):
300 # Testing if attributes are of same type. 357 # Testing if attributes are of same type.
301 h1 = hmac.HMAC(b"key") 358 h1 = hmac.HMAC(b"key", digestmod="md5")
302 h2 = h1.copy() 359 h2 = h1.copy()
303 self.assertEqual(h1.digest_cons, h2.digest_cons, 360 self.assertEqual(h1.digest_cons, h2.digest_cons,
304 "digest constructors don't match.") 361 "digest constructors don't match.")
305 self.assertEqual(type(h1.inner), type(h2.inner), 362 self.assertEqual(type(h1.inner), type(h2.inner),
306 "Types of inner don't match.") 363 "Types of inner don't match.")
307 self.assertEqual(type(h1.outer), type(h2.outer), 364 self.assertEqual(type(h1.outer), type(h2.outer),
308 "Types of outer don't match.") 365 "Types of outer don't match.")
309 366
310 def test_realcopy(self): 367 def test_realcopy(self):
311 # Testing if the copy method created a real copy. 368 # Testing if the copy method created a real copy.
312 h1 = hmac.HMAC(b"key") 369 h1 = hmac.HMAC(b"key", digestmod="md5")
313 h2 = h1.copy() 370 h2 = h1.copy()
314 # Using "is" in case somebody has overridden __eq__/__ne__. 371 # Using "is" in case somebody has overridden __eq__/__ne__.
315 self.assertIsNot(h1, h2, "No real copy of the HMAC instance.") 372 self.assertIsNot(h1, h2, "No real copy of the HMAC instance.")
316 self.assertIsNot(h1.inner, h2.inner, 373 self.assertIsNot(h1.inner, h2.inner,
317 "No real copy of the attribute 'inner'.") 374 "No real copy of the attribute 'inner'.")
318 self.assertIsNot(h1.outer, h2.outer, 375 self.assertIsNot(h1.outer, h2.outer,
319 "No real copy of the attribute 'outer'.") 376 "No real copy of the attribute 'outer'.")
320 377
321 def test_equality(self): 378 def test_equality(self):
322 # Testing if the copy has the same digests. 379 # Testing if the copy has the same digests.
323 h1 = hmac.HMAC(b"key") 380 h1 = hmac.HMAC(b"key", digestmod="md5")
324 h1.update(b"some random text") 381 h1.update(b"some random text")
325 h2 = h1.copy() 382 h2 = h1.copy()
326 self.assertEqual(h1.digest(), h2.digest(), 383 self.assertEqual(h1.digest(), h2.digest(),
327 "Digest of copy doesn't match original digest.") 384 "Digest of copy doesn't match original digest.")
328 self.assertEqual(h1.hexdigest(), h2.hexdigest(), 385 self.assertEqual(h1.hexdigest(), h2.hexdigest(),
329 "Hexdigest of copy doesn't match original hexdigest.") 386 "Hexdigest of copy doesn't match original hexdigest.")
330 387
331 class CompareDigestTestCase(unittest.TestCase): 388 class CompareDigestTestCase(unittest.TestCase):
332 389
333 def test_compare_digest(self): 390 def test_compare_digest(self):
(...skipping 106 matching lines...) Expand 10 before | Expand all | Expand 10 after
440 support.run_unittest( 497 support.run_unittest(
441 TestVectorsTestCase, 498 TestVectorsTestCase,
442 ConstructorTestCase, 499 ConstructorTestCase,
443 SanityTestCase, 500 SanityTestCase,
444 CopyTestCase, 501 CopyTestCase,
445 CompareDigestTestCase 502 CompareDigestTestCase
446 ) 503 )
447 504
448 if __name__ == "__main__": 505 if __name__ == "__main__":
449 test_main() 506 test_main()
LEFTRIGHT

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+