comparison cutils/crcmod/python2/test.py @ 180:d038f0a9ba49

Vendored crcmod2 into sub-package "cutils.crcmod" as pure-Python implementation of additional "digests": CRC sums. Running python -m cutils.crcmod.test works successfully.
author Franz Glasner <fzglas.hg@dom66.de>
date Mon, 13 Jan 2025 04:09:35 +0100
parents
children 5c5c0c5a7402
comparison
equal deleted inserted replaced
179:53614a724bf0 180:d038f0a9ba49
1 #-----------------------------------------------------------------------------
2 # Copyright (c) 2010 Raymond L. Buvel
3 # Copyright (c) 2010 Craig McQueen
4 #
5 # Permission is hereby granted, free of charge, to any person obtaining a copy
6 # of this software and associated documentation files (the "Software"), to deal
7 # in the Software without restriction, including without limitation the rights
8 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 # copies of the Software, and to permit persons to whom the Software is
10 # furnished to do so, subject to the following conditions:
11 #
12 # The above copyright notice and this permission notice shall be included in
13 # all copies or substantial portions of the Software.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 # SOFTWARE.
22 #-----------------------------------------------------------------------------
23 '''Unit tests for crcmod functionality'''
24
25
26 from __future__ import absolute_import
27
28 import unittest
29 import binascii
30
31 from .crcmod import mkCrcFun, Crc
32 from .crcmod import _usingExtension
33 from .predefined import PredefinedCrc
34 from .predefined import mkPredefinedCrcFun
35 from .predefined import _crc_definitions as _predefined_crc_definitions
36
37
38 #-----------------------------------------------------------------------------
39 # This polynomial was chosen because it is the product of two irreducible
40 # polynomials.
41 # g8 = (x^7+x+1)*(x+1)
42 g8 = 0x185
43
44 #-----------------------------------------------------------------------------
45 # The following reproduces all of the entries in the Numerical Recipes table.
46 # This is the standard CCITT polynomial.
47 g16 = 0x11021
48
49 #-----------------------------------------------------------------------------
50 g24 = 0x15D6DCB
51
52 #-----------------------------------------------------------------------------
53 # This is the standard AUTODIN-II polynomial which appears to be used in a
54 # wide variety of standards and applications.
55 g32 = 0x104C11DB7
56
57
58 #-----------------------------------------------------------------------------
59 # I was able to locate a couple of 64-bit polynomials on the web. To make it
60 # easier to input the representation, define a function that builds a
61 # polynomial from a list of the bits that need to be turned on.
62
63 def polyFromBits(bits):
64 p = 0L
65 for n in bits:
66 p = p | (1L << n)
67 return p
68
69 # The following is from the paper "An Improved 64-bit Cyclic Redundancy Check
70 # for Protein Sequences" by David T. Jones
71
72 g64a = polyFromBits([64, 63, 61, 59, 58, 56, 55, 52, 49, 48, 47, 46, 44, 41,
73 37, 36, 34, 32, 31, 28, 26, 23, 22, 19, 16, 13, 12, 10, 9, 6, 4,
74 3, 0])
75
76 # The following is from Standard ECMA-182 "Data Interchange on 12,7 mm 48-Track
77 # Magnetic Tape Cartridges -DLT1 Format-", December 1992.
78
79 g64b = polyFromBits([64, 62, 57, 55, 54, 53, 52, 47, 46, 45, 40, 39, 38, 37,
80 35, 33, 32, 31, 29, 27, 24, 23, 22, 21, 19, 17, 13, 12, 10, 9, 7,
81 4, 1, 0])
82
83 #-----------------------------------------------------------------------------
84 # This class is used to check the CRC calculations against a direct
85 # implementation using polynomial division.
86
87 class poly:
88 '''Class implementing polynomials over the field of integers mod 2'''
89 def __init__(self,p):
90 p = long(p)
91 if p < 0: raise ValueError('invalid polynomial')
92 self.p = p
93
94 def __long__(self):
95 return self.p
96
97 def __eq__(self,other):
98 return self.p == other.p
99
100 def __ne__(self,other):
101 return self.p != other.p
102
103 # To allow sorting of polynomials, use their long integer form for
104 # comparison
105 def __cmp__(self,other):
106 return cmp(self.p, other.p)
107
108 def __nonzero__(self):
109 return self.p != 0L
110
111 def __neg__(self):
112 return self # These polynomials are their own inverse under addition
113
114 def __invert__(self):
115 n = max(self.deg() + 1, 1)
116 x = (1L << n) - 1
117 return poly(self.p ^ x)
118
119 def __add__(self,other):
120 return poly(self.p ^ other.p)
121
122 def __sub__(self,other):
123 return poly(self.p ^ other.p)
124
125 def __mul__(self,other):
126 a = self.p
127 b = other.p
128 if a == 0 or b == 0: return poly(0)
129 x = 0L
130 while b:
131 if b&1:
132 x = x ^ a
133 a = a<<1
134 b = b>>1
135 return poly(x)
136
137 def __divmod__(self,other):
138 u = self.p
139 m = self.deg()
140 v = other.p
141 n = other.deg()
142 if v == 0: raise ZeroDivisionError('polynomial division by zero')
143 if n == 0: return (self,poly(0))
144 if m < n: return (poly(0),self)
145 k = m-n
146 a = 1L << m
147 v = v << k
148 q = 0L
149 while k > 0:
150 if a & u:
151 u = u ^ v
152 q = q | 1L
153 q = q << 1
154 a = a >> 1
155 v = v >> 1
156 k -= 1
157 if a & u:
158 u = u ^ v
159 q = q | 1L
160 return (poly(q),poly(u))
161
162 def __div__(self,other):
163 return self.__divmod__(other)[0]
164
165 def __mod__(self,other):
166 return self.__divmod__(other)[1]
167
168 def __repr__(self):
169 return 'poly(0x%XL)' % self.p
170
171 def __str__(self):
172 p = self.p
173 if p == 0: return '0'
174 lst = { 0:[], 1:['1'], 2:['x'], 3:['1','x'] }[p&3]
175 p = p>>2
176 n = 2
177 while p:
178 if p&1: lst.append('x^%d' % n)
179 p = p>>1
180 n += 1
181 lst.reverse()
182 return '+'.join(lst)
183
184 def deg(self):
185 '''return the degree of the polynomial'''
186 a = self.p
187 if a == 0: return -1
188 n = 0
189 while a >= 0x10000L:
190 n += 16
191 a = a >> 16
192 a = int(a)
193 while a > 1:
194 n += 1
195 a = a >> 1
196 return n
197
198 #-----------------------------------------------------------------------------
199 # The following functions compute the CRC using direct polynomial division.
200 # These functions are checked against the result of the table driven
201 # algorithms.
202
203 g8p = poly(g8)
204 x8p = poly(1L<<8)
205 def crc8p(d):
206 d = map(ord, d)
207 p = 0L
208 for i in d:
209 p = p*256L + i
210 p = poly(p)
211 return long(p*x8p%g8p)
212
213 g16p = poly(g16)
214 x16p = poly(1L<<16)
215 def crc16p(d):
216 d = map(ord, d)
217 p = 0L
218 for i in d:
219 p = p*256L + i
220 p = poly(p)
221 return long(p*x16p%g16p)
222
223 g24p = poly(g24)
224 x24p = poly(1L<<24)
225 def crc24p(d):
226 d = map(ord, d)
227 p = 0L
228 for i in d:
229 p = p*256L + i
230 p = poly(p)
231 return long(p*x24p%g24p)
232
233 g32p = poly(g32)
234 x32p = poly(1L<<32)
235 def crc32p(d):
236 d = map(ord, d)
237 p = 0L
238 for i in d:
239 p = p*256L + i
240 p = poly(p)
241 return long(p*x32p%g32p)
242
243 g64ap = poly(g64a)
244 x64p = poly(1L<<64)
245 def crc64ap(d):
246 d = map(ord, d)
247 p = 0L
248 for i in d:
249 p = p*256L + i
250 p = poly(p)
251 return long(p*x64p%g64ap)
252
253 g64bp = poly(g64b)
254 def crc64bp(d):
255 d = map(ord, d)
256 p = 0L
257 for i in d:
258 p = p*256L + i
259 p = poly(p)
260 return long(p*x64p%g64bp)
261
262
263 class KnownAnswerTests(unittest.TestCase):
264 test_messages = [
265 'T',
266 'CatMouse987654321',
267 ]
268
269 known_answers = [
270 [ (g8,0,0), (0xFE, 0x9D) ],
271 [ (g8,-1,1), (0x4F, 0x9B) ],
272 [ (g8,0,1), (0xFE, 0x62) ],
273 [ (g16,0,0), (0x1A71, 0xE556) ],
274 [ (g16,-1,1), (0x1B26, 0xF56E) ],
275 [ (g16,0,1), (0x14A1, 0xC28D) ],
276 [ (g24,0,0), (0xBCC49D, 0xC4B507) ],
277 [ (g24,-1,1), (0x59BD0E, 0x0AAA37) ],
278 [ (g24,0,1), (0xD52B0F, 0x1523AB) ],
279 [ (g32,0,0), (0x6B93DDDB, 0x12DCA0F4) ],
280 [ (g32,0xFFFFFFFFL,1), (0x41FB859FL, 0xF7B400A7L) ],
281 [ (g32,0,1), (0x6C0695EDL, 0xC1A40EE5L) ],
282 [ (g32,0,1,0xFFFFFFFF), (0xBE047A60L, 0x084BFF58L) ],
283 ]
284
285 def test_known_answers(self):
286 for crcfun_params, v in self.known_answers:
287 crcfun = mkCrcFun(*crcfun_params)
288 self.assertEqual(crcfun('',0), 0, "Wrong answer for CRC parameters %s, input ''" % (crcfun_params,))
289 for i, msg in enumerate(self.test_messages):
290 self.assertEqual(crcfun(msg), v[i], "Wrong answer for CRC parameters %s, input '%s'" % (crcfun_params,msg))
291 self.assertEqual(crcfun(msg[4:], crcfun(msg[:4])), v[i], "Wrong answer for CRC parameters %s, input '%s'" % (crcfun_params,msg))
292 self.assertEqual(crcfun(msg[-1:], crcfun(msg[:-1])), v[i], "Wrong answer for CRC parameters %s, input '%s'" % (crcfun_params,msg))
293
294
295 class CompareReferenceCrcTest(unittest.TestCase):
296 test_messages = [
297 '',
298 'T',
299 '123456789',
300 'CatMouse987654321',
301 ]
302
303 test_poly_crcs = [
304 [ (g8,0,0), crc8p ],
305 [ (g16,0,0), crc16p ],
306 [ (g24,0,0), crc24p ],
307 [ (g32,0,0), crc32p ],
308 [ (g64a,0,0), crc64ap ],
309 [ (g64b,0,0), crc64bp ],
310 ]
311
312 @staticmethod
313 def reference_crc32(d, crc=0):
314 """This function modifies the return value of binascii.crc32
315 to be an unsigned 32-bit value. I.e. in the range 0 to 2**32-1."""
316 # Work around the future warning on constants.
317 if crc > 0x7FFFFFFFL:
318 x = int(crc & 0x7FFFFFFFL)
319 crc = x | -2147483648
320 x = binascii.crc32(d,crc)
321 return long(x) & 0xFFFFFFFFL
322
323 def test_compare_crc32(self):
324 """The binascii module has a 32-bit CRC function that is used in a wide range
325 of applications including the checksum used in the ZIP file format.
326 This test compares the CRC-32 implementation of this crcmod module to
327 that of binascii.crc32."""
328 # The following function should produce the same result as
329 # self.reference_crc32 which is derived from binascii.crc32.
330 crc32 = mkCrcFun(g32,0,1,0xFFFFFFFF)
331
332 for msg in self.test_messages:
333 self.assertEqual(crc32(msg), self.reference_crc32(msg))
334
335 def test_compare_poly(self):
336 """Compare various CRCs of this crcmod module to a pure
337 polynomial-based implementation."""
338 for crcfun_params, crc_poly_fun in self.test_poly_crcs:
339 # The following function should produce the same result as
340 # the associated polynomial CRC function.
341 crcfun = mkCrcFun(*crcfun_params)
342
343 for msg in self.test_messages:
344 self.assertEqual(crcfun(msg), crc_poly_fun(msg))
345
346
347 class CrcClassTest(unittest.TestCase):
348 """Verify the Crc class"""
349
350 msg = 'CatMouse987654321'
351
352 def test_simple_crc32_class(self):
353 """Verify the CRC class when not using xorOut"""
354 crc = Crc(g32)
355
356 str_rep = \
357 '''poly = 0x104C11DB7
358 reverse = True
359 initCrc = 0xFFFFFFFF
360 xorOut = 0x00000000
361 crcValue = 0xFFFFFFFF'''
362 self.assertEqual(str(crc), str_rep)
363 self.assertEqual(crc.digest(), '\xff\xff\xff\xff')
364 self.assertEqual(crc.hexdigest(), 'FFFFFFFF')
365
366 crc.update(self.msg)
367 self.assertEqual(crc.crcValue, 0xF7B400A7L)
368 self.assertEqual(crc.digest(), '\xf7\xb4\x00\xa7')
369 self.assertEqual(crc.hexdigest(), 'F7B400A7')
370
371 # Verify the .copy() method
372 x = crc.copy()
373 self.assertTrue(x is not crc)
374 str_rep = \
375 '''poly = 0x104C11DB7
376 reverse = True
377 initCrc = 0xFFFFFFFF
378 xorOut = 0x00000000
379 crcValue = 0xF7B400A7'''
380 self.assertEqual(str(crc), str_rep)
381 self.assertEqual(str(x), str_rep)
382
383 def test_full_crc32_class(self):
384 """Verify the CRC class when using xorOut"""
385
386 crc = Crc(g32, initCrc=0, xorOut= ~0L)
387
388 str_rep = \
389 '''poly = 0x104C11DB7
390 reverse = True
391 initCrc = 0x00000000
392 xorOut = 0xFFFFFFFF
393 crcValue = 0x00000000'''
394 self.assertEqual(str(crc), str_rep)
395 self.assertEqual(crc.digest(), '\x00\x00\x00\x00')
396 self.assertEqual(crc.hexdigest(), '00000000')
397
398 crc.update(self.msg)
399 self.assertEqual(crc.crcValue, 0x84BFF58L)
400 self.assertEqual(crc.digest(), '\x08\x4b\xff\x58')
401 self.assertEqual(crc.hexdigest(), '084BFF58')
402
403 # Verify the .copy() method
404 x = crc.copy()
405 self.assertTrue(x is not crc)
406 str_rep = \
407 '''poly = 0x104C11DB7
408 reverse = True
409 initCrc = 0x00000000
410 xorOut = 0xFFFFFFFF
411 crcValue = 0x084BFF58'''
412 self.assertEqual(str(crc), str_rep)
413 self.assertEqual(str(x), str_rep)
414
415 # Verify the .new() method
416 y = crc.new()
417 self.assertTrue(y is not crc)
418 self.assertTrue(y is not x)
419 str_rep = \
420 '''poly = 0x104C11DB7
421 reverse = True
422 initCrc = 0x00000000
423 xorOut = 0xFFFFFFFF
424 crcValue = 0x00000000'''
425 self.assertEqual(str(y), str_rep)
426
427
428 class PredefinedCrcTest(unittest.TestCase):
429 """Verify the predefined CRCs"""
430
431 test_messages_for_known_answers = [
432 '', # Test cases below depend on this first entry being the empty string.
433 'T',
434 'CatMouse987654321',
435 ]
436
437 known_answers = [
438 [ 'crc-aug-ccitt', (0x1D0F, 0xD6ED, 0x5637) ],
439 [ 'x-25', (0x0000, 0xE4D9, 0x0A91) ],
440 [ 'crc-32', (0x00000000, 0xBE047A60, 0x084BFF58) ],
441 ]
442
443 def test_known_answers(self):
444 for crcfun_name, v in self.known_answers:
445 crcfun = mkPredefinedCrcFun(crcfun_name)
446 self.assertEqual(crcfun('',0), 0, "Wrong answer for CRC '%s', input ''" % crcfun_name)
447 for i, msg in enumerate(self.test_messages_for_known_answers):
448 self.assertEqual(crcfun(msg), v[i], "Wrong answer for CRC %s, input '%s'" % (crcfun_name,msg))
449 self.assertEqual(crcfun(msg[4:], crcfun(msg[:4])), v[i], "Wrong answer for CRC %s, input '%s'" % (crcfun_name,msg))
450 self.assertEqual(crcfun(msg[-1:], crcfun(msg[:-1])), v[i], "Wrong answer for CRC %s, input '%s'" % (crcfun_name,msg))
451
452 def test_class_with_known_answers(self):
453 for crcfun_name, v in self.known_answers:
454 for i, msg in enumerate(self.test_messages_for_known_answers):
455 crc1 = PredefinedCrc(crcfun_name)
456 crc1.update(msg)
457 self.assertEqual(crc1.crcValue, v[i], "Wrong answer for crc1 %s, input '%s'" % (crcfun_name,msg))
458
459 crc2 = crc1.new()
460 # Check that crc1 maintains its same value, after .new() call.
461 self.assertEqual(crc1.crcValue, v[i], "Wrong state for crc1 %s, input '%s'" % (crcfun_name,msg))
462 # Check that the new class instance created by .new() contains the initialisation value.
463 # This depends on the first string in self.test_messages_for_known_answers being
464 # the empty string.
465 self.assertEqual(crc2.crcValue, v[0], "Wrong state for crc2 %s, input '%s'" % (crcfun_name,msg))
466
467 crc2.update(msg)
468 # Check that crc1 maintains its same value, after crc2 has called .update()
469 self.assertEqual(crc1.crcValue, v[i], "Wrong state for crc1 %s, input '%s'" % (crcfun_name,msg))
470 # Check that crc2 contains the right value after calling .update()
471 self.assertEqual(crc2.crcValue, v[i], "Wrong state for crc2 %s, input '%s'" % (crcfun_name,msg))
472
473 def test_function_predefined_table(self):
474 for table_entry in _predefined_crc_definitions:
475 # Check predefined function
476 crc_func = mkPredefinedCrcFun(table_entry['name'])
477 calc_value = crc_func("123456789")
478 self.assertEqual(calc_value, table_entry['check'], "Wrong answer for CRC '%s'" % table_entry['name'])
479
480 def test_class_predefined_table(self):
481 for table_entry in _predefined_crc_definitions:
482 # Check predefined class
483 crc1 = PredefinedCrc(table_entry['name'])
484 crc1.update("123456789")
485 self.assertEqual(crc1.crcValue, table_entry['check'], "Wrong answer for CRC '%s'" % table_entry['name'])
486
487
488 def runtests():
489 print "Using extension:", _usingExtension
490 print
491 unittest.main()
492
493
494 if __name__ == '__main__':
495 runtests()