test.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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. import unittest
  25. from array import array
  26. import binascii
  27. from .crcmod import mkCrcFun, Crc
  28. from .crcmod import _usingExtension
  29. from .predefined import PredefinedCrc
  30. from .predefined import mkPredefinedCrcFun
  31. from .predefined import _crc_definitions as _predefined_crc_definitions
  32. #-----------------------------------------------------------------------------
  33. # This polynomial was chosen because it is the product of two irreducible
  34. # polynomials.
  35. # g8 = (x^7+x+1)*(x+1)
  36. g8 = 0x185
  37. #-----------------------------------------------------------------------------
  38. # The following reproduces all of the entries in the Numerical Recipes table.
  39. # This is the standard CCITT polynomial.
  40. g16 = 0x11021
  41. #-----------------------------------------------------------------------------
  42. g24 = 0x15D6DCB
  43. #-----------------------------------------------------------------------------
  44. # This is the standard AUTODIN-II polynomial which appears to be used in a
  45. # wide variety of standards and applications.
  46. g32 = 0x104C11DB7
  47. #-----------------------------------------------------------------------------
  48. # I was able to locate a couple of 64-bit polynomials on the web. To make it
  49. # easier to input the representation, define a function that builds a
  50. # polynomial from a list of the bits that need to be turned on.
  51. def polyFromBits(bits):
  52. p = 0
  53. for n in bits:
  54. p = p | (1 << n)
  55. return p
  56. # The following is from the paper "An Improved 64-bit Cyclic Redundancy Check
  57. # for Protein Sequences" by David T. Jones
  58. g64a = polyFromBits([64, 63, 61, 59, 58, 56, 55, 52, 49, 48, 47, 46, 44, 41,
  59. 37, 36, 34, 32, 31, 28, 26, 23, 22, 19, 16, 13, 12, 10, 9, 6, 4,
  60. 3, 0])
  61. # The following is from Standard ECMA-182 "Data Interchange on 12,7 mm 48-Track
  62. # Magnetic Tape Cartridges -DLT1 Format-", December 1992.
  63. g64b = polyFromBits([64, 62, 57, 55, 54, 53, 52, 47, 46, 45, 40, 39, 38, 37,
  64. 35, 33, 32, 31, 29, 27, 24, 23, 22, 21, 19, 17, 13, 12, 10, 9, 7,
  65. 4, 1, 0])
  66. #-----------------------------------------------------------------------------
  67. # This class is used to check the CRC calculations against a direct
  68. # implementation using polynomial division.
  69. class poly:
  70. '''Class implementing polynomials over the field of integers mod 2'''
  71. def __init__(self,p):
  72. p = int(p)
  73. if p < 0: raise ValueError('invalid polynomial')
  74. self.p = p
  75. def __int__(self):
  76. return self.p
  77. def __eq__(self,other):
  78. return self.p == other.p
  79. def __ne__(self,other):
  80. return self.p != other.p
  81. # To allow sorting of polynomials, use their long integer form for
  82. # comparison
  83. def __cmp__(self,other):
  84. return cmp(self.p, other.p)
  85. def __bool__(self):
  86. return self.p != 0
  87. def __neg__(self):
  88. return self # These polynomials are their own inverse under addition
  89. def __invert__(self):
  90. n = max(self.deg() + 1, 1)
  91. x = (1 << n) - 1
  92. return poly(self.p ^ x)
  93. def __add__(self,other):
  94. return poly(self.p ^ other.p)
  95. def __sub__(self,other):
  96. return poly(self.p ^ other.p)
  97. def __mul__(self,other):
  98. a = self.p
  99. b = other.p
  100. if a == 0 or b == 0: return poly(0)
  101. x = 0
  102. while b:
  103. if b&1:
  104. x = x ^ a
  105. a = a<<1
  106. b = b>>1
  107. return poly(x)
  108. def __divmod__(self,other):
  109. u = self.p
  110. m = self.deg()
  111. v = other.p
  112. n = other.deg()
  113. if v == 0: raise ZeroDivisionError('polynomial division by zero')
  114. if n == 0: return (self,poly(0))
  115. if m < n: return (poly(0),self)
  116. k = m-n
  117. a = 1 << m
  118. v = v << k
  119. q = 0
  120. while k > 0:
  121. if a & u:
  122. u = u ^ v
  123. q = q | 1
  124. q = q << 1
  125. a = a >> 1
  126. v = v >> 1
  127. k -= 1
  128. if a & u:
  129. u = u ^ v
  130. q = q | 1
  131. return (poly(q),poly(u))
  132. def __div__(self,other):
  133. return self.__divmod__(other)[0]
  134. def __mod__(self,other):
  135. return self.__divmod__(other)[1]
  136. def __repr__(self):
  137. return 'poly(0x%XL)' % self.p
  138. def __str__(self):
  139. p = self.p
  140. if p == 0: return '0'
  141. lst = { 0:[], 1:['1'], 2:['x'], 3:['1','x'] }[p&3]
  142. p = p>>2
  143. n = 2
  144. while p:
  145. if p&1: lst.append('x^%d' % n)
  146. p = p>>1
  147. n += 1
  148. lst.reverse()
  149. return '+'.join(lst)
  150. def deg(self):
  151. '''return the degree of the polynomial'''
  152. a = self.p
  153. if a == 0: return -1
  154. n = 0
  155. while a >= 0x10000:
  156. n += 16
  157. a = a >> 16
  158. a = int(a)
  159. while a > 1:
  160. n += 1
  161. a = a >> 1
  162. return n
  163. #-----------------------------------------------------------------------------
  164. # The following functions compute the CRC using direct polynomial division.
  165. # These functions are checked against the result of the table driven
  166. # algorithms.
  167. g8p = poly(g8)
  168. x8p = poly(1<<8)
  169. def crc8p(d):
  170. p = 0
  171. for i in d:
  172. p = p*256 + i
  173. p = poly(p)
  174. return int(p*x8p%g8p)
  175. g16p = poly(g16)
  176. x16p = poly(1<<16)
  177. def crc16p(d):
  178. p = 0
  179. for i in d:
  180. p = p*256 + i
  181. p = poly(p)
  182. return int(p*x16p%g16p)
  183. g24p = poly(g24)
  184. x24p = poly(1<<24)
  185. def crc24p(d):
  186. p = 0
  187. for i in d:
  188. p = p*256 + i
  189. p = poly(p)
  190. return int(p*x24p%g24p)
  191. g32p = poly(g32)
  192. x32p = poly(1<<32)
  193. def crc32p(d):
  194. p = 0
  195. for i in d:
  196. p = p*256 + i
  197. p = poly(p)
  198. return int(p*x32p%g32p)
  199. g64ap = poly(g64a)
  200. x64p = poly(1<<64)
  201. def crc64ap(d):
  202. p = 0
  203. for i in d:
  204. p = p*256 + i
  205. p = poly(p)
  206. return int(p*x64p%g64ap)
  207. g64bp = poly(g64b)
  208. def crc64bp(d):
  209. p = 0
  210. for i in d:
  211. p = p*256 + i
  212. p = poly(p)
  213. return int(p*x64p%g64bp)
  214. class KnownAnswerTests(unittest.TestCase):
  215. test_messages = [
  216. b'T',
  217. b'CatMouse987654321',
  218. ]
  219. known_answers = [
  220. [ (g8,0,0), (0xFE, 0x9D) ],
  221. [ (g8,-1,1), (0x4F, 0x9B) ],
  222. [ (g8,0,1), (0xFE, 0x62) ],
  223. [ (g16,0,0), (0x1A71, 0xE556) ],
  224. [ (g16,-1,1), (0x1B26, 0xF56E) ],
  225. [ (g16,0,1), (0x14A1, 0xC28D) ],
  226. [ (g24,0,0), (0xBCC49D, 0xC4B507) ],
  227. [ (g24,-1,1), (0x59BD0E, 0x0AAA37) ],
  228. [ (g24,0,1), (0xD52B0F, 0x1523AB) ],
  229. [ (g32,0,0), (0x6B93DDDB, 0x12DCA0F4) ],
  230. [ (g32,0xFFFFFFFF,1), (0x41FB859F, 0xF7B400A7) ],
  231. [ (g32,0,1), (0x6C0695ED, 0xC1A40EE5) ],
  232. [ (g32,0,1,0xFFFFFFFF), (0xBE047A60, 0x084BFF58) ],
  233. ]
  234. def test_known_answers(self):
  235. for crcfun_params, v in self.known_answers:
  236. crcfun = mkCrcFun(*crcfun_params)
  237. self.assertEqual(crcfun(b'',0), 0, "Wrong answer for CRC parameters %s, input ''" % (crcfun_params,))
  238. for i, msg in enumerate(self.test_messages):
  239. self.assertEqual(crcfun(msg), v[i], "Wrong answer for CRC parameters %s, input '%s'" % (crcfun_params,msg))
  240. self.assertEqual(crcfun(msg[4:], crcfun(msg[:4])), v[i], "Wrong answer for CRC parameters %s, input '%s'" % (crcfun_params,msg))
  241. self.assertEqual(crcfun(msg[-1:], crcfun(msg[:-1])), v[i], "Wrong answer for CRC parameters %s, input '%s'" % (crcfun_params,msg))
  242. class CompareReferenceCrcTest(unittest.TestCase):
  243. test_messages = [
  244. b'',
  245. b'T',
  246. b'123456789',
  247. b'CatMouse987654321',
  248. ]
  249. test_poly_crcs = [
  250. [ (g8,0,0), crc8p ],
  251. [ (g16,0,0), crc16p ],
  252. [ (g24,0,0), crc24p ],
  253. [ (g32,0,0), crc32p ],
  254. [ (g64a,0,0), crc64ap ],
  255. [ (g64b,0,0), crc64bp ],
  256. ]
  257. @staticmethod
  258. def reference_crc32(d, crc=0):
  259. """This function modifies the return value of binascii.crc32
  260. to be an unsigned 32-bit value. I.e. in the range 0 to 2**32-1."""
  261. # Work around the future warning on constants.
  262. if crc > 0x7FFFFFFF:
  263. x = int(crc & 0x7FFFFFFF)
  264. crc = x | -2147483648
  265. x = binascii.crc32(d,crc)
  266. return int(x) & 0xFFFFFFFF
  267. def test_compare_crc32(self):
  268. """The binascii module has a 32-bit CRC function that is used in a wide range
  269. of applications including the checksum used in the ZIP file format.
  270. This test compares the CRC-32 implementation of this crcmod module to
  271. that of binascii.crc32."""
  272. # The following function should produce the same result as
  273. # self.reference_crc32 which is derived from binascii.crc32.
  274. crc32 = mkCrcFun(g32,0,1,0xFFFFFFFF)
  275. for msg in self.test_messages:
  276. self.assertEqual(crc32(msg), self.reference_crc32(msg))
  277. def test_compare_poly(self):
  278. """Compare various CRCs of this crcmod module to a pure
  279. polynomial-based implementation."""
  280. for crcfun_params, crc_poly_fun in self.test_poly_crcs:
  281. # The following function should produce the same result as
  282. # the associated polynomial CRC function.
  283. crcfun = mkCrcFun(*crcfun_params)
  284. for msg in self.test_messages:
  285. self.assertEqual(crcfun(msg), crc_poly_fun(msg))
  286. class CrcClassTest(unittest.TestCase):
  287. """Verify the Crc class"""
  288. msg = b'CatMouse987654321'
  289. def test_simple_crc32_class(self):
  290. """Verify the CRC class when not using xorOut"""
  291. crc = Crc(g32)
  292. str_rep = \
  293. '''poly = 0x104C11DB7
  294. reverse = True
  295. initCrc = 0xFFFFFFFF
  296. xorOut = 0x00000000
  297. crcValue = 0xFFFFFFFF'''
  298. self.assertEqual(str(crc), str_rep)
  299. self.assertEqual(crc.digest(), b'\xff\xff\xff\xff')
  300. self.assertEqual(crc.hexdigest(), 'FFFFFFFF')
  301. crc.update(self.msg)
  302. self.assertEqual(crc.crcValue, 0xF7B400A7)
  303. self.assertEqual(crc.digest(), b'\xf7\xb4\x00\xa7')
  304. self.assertEqual(crc.hexdigest(), 'F7B400A7')
  305. # Verify the .copy() method
  306. x = crc.copy()
  307. self.assertTrue(x is not crc)
  308. str_rep = \
  309. '''poly = 0x104C11DB7
  310. reverse = True
  311. initCrc = 0xFFFFFFFF
  312. xorOut = 0x00000000
  313. crcValue = 0xF7B400A7'''
  314. self.assertEqual(str(crc), str_rep)
  315. self.assertEqual(str(x), str_rep)
  316. def test_full_crc32_class(self):
  317. """Verify the CRC class when using xorOut"""
  318. crc = Crc(g32, initCrc=0, xorOut= ~0)
  319. str_rep = \
  320. '''poly = 0x104C11DB7
  321. reverse = True
  322. initCrc = 0x00000000
  323. xorOut = 0xFFFFFFFF
  324. crcValue = 0x00000000'''
  325. self.assertEqual(str(crc), str_rep)
  326. self.assertEqual(crc.digest(), b'\x00\x00\x00\x00')
  327. self.assertEqual(crc.hexdigest(), '00000000')
  328. crc.update(self.msg)
  329. self.assertEqual(crc.crcValue, 0x84BFF58)
  330. self.assertEqual(crc.digest(), b'\x08\x4b\xff\x58')
  331. self.assertEqual(crc.hexdigest(), '084BFF58')
  332. # Verify the .copy() method
  333. x = crc.copy()
  334. self.assertTrue(x is not crc)
  335. str_rep = \
  336. '''poly = 0x104C11DB7
  337. reverse = True
  338. initCrc = 0x00000000
  339. xorOut = 0xFFFFFFFF
  340. crcValue = 0x084BFF58'''
  341. self.assertEqual(str(crc), str_rep)
  342. self.assertEqual(str(x), str_rep)
  343. # Verify the .new() method
  344. y = crc.new()
  345. self.assertTrue(y is not crc)
  346. self.assertTrue(y is not x)
  347. str_rep = \
  348. '''poly = 0x104C11DB7
  349. reverse = True
  350. initCrc = 0x00000000
  351. xorOut = 0xFFFFFFFF
  352. crcValue = 0x00000000'''
  353. self.assertEqual(str(y), str_rep)
  354. class PredefinedCrcTest(unittest.TestCase):
  355. """Verify the predefined CRCs"""
  356. test_messages_for_known_answers = [
  357. b'', # Test cases below depend on this first entry being the empty string.
  358. b'T',
  359. b'CatMouse987654321',
  360. ]
  361. known_answers = [
  362. [ 'crc-aug-ccitt', (0x1D0F, 0xD6ED, 0x5637) ],
  363. [ 'x-25', (0x0000, 0xE4D9, 0x0A91) ],
  364. [ 'crc-32', (0x00000000, 0xBE047A60, 0x084BFF58) ],
  365. ]
  366. def test_known_answers(self):
  367. for crcfun_name, v in self.known_answers:
  368. crcfun = mkPredefinedCrcFun(crcfun_name)
  369. self.assertEqual(crcfun(b'',0), 0, "Wrong answer for CRC '%s', input ''" % crcfun_name)
  370. for i, msg in enumerate(self.test_messages_for_known_answers):
  371. self.assertEqual(crcfun(msg), v[i], "Wrong answer for CRC %s, input '%s'" % (crcfun_name,msg))
  372. self.assertEqual(crcfun(msg[4:], crcfun(msg[:4])), v[i], "Wrong answer for CRC %s, input '%s'" % (crcfun_name,msg))
  373. self.assertEqual(crcfun(msg[-1:], crcfun(msg[:-1])), v[i], "Wrong answer for CRC %s, input '%s'" % (crcfun_name,msg))
  374. def test_class_with_known_answers(self):
  375. for crcfun_name, v in self.known_answers:
  376. for i, msg in enumerate(self.test_messages_for_known_answers):
  377. crc1 = PredefinedCrc(crcfun_name)
  378. crc1.update(msg)
  379. self.assertEqual(crc1.crcValue, v[i], "Wrong answer for crc1 %s, input '%s'" % (crcfun_name,msg))
  380. crc2 = crc1.new()
  381. # Check that crc1 maintains its same value, after .new() call.
  382. self.assertEqual(crc1.crcValue, v[i], "Wrong state for crc1 %s, input '%s'" % (crcfun_name,msg))
  383. # Check that the new class instance created by .new() contains the initialisation value.
  384. # This depends on the first string in self.test_messages_for_known_answers being
  385. # the empty string.
  386. self.assertEqual(crc2.crcValue, v[0], "Wrong state for crc2 %s, input '%s'" % (crcfun_name,msg))
  387. crc2.update(msg)
  388. # Check that crc1 maintains its same value, after crc2 has called .update()
  389. self.assertEqual(crc1.crcValue, v[i], "Wrong state for crc1 %s, input '%s'" % (crcfun_name,msg))
  390. # Check that crc2 contains the right value after calling .update()
  391. self.assertEqual(crc2.crcValue, v[i], "Wrong state for crc2 %s, input '%s'" % (crcfun_name,msg))
  392. def test_function_predefined_table(self):
  393. for table_entry in _predefined_crc_definitions:
  394. # Check predefined function
  395. crc_func = mkPredefinedCrcFun(table_entry['name'])
  396. calc_value = crc_func(b"123456789")
  397. self.assertEqual(calc_value, table_entry['check'], "Wrong answer for CRC '%s'" % table_entry['name'])
  398. def test_class_predefined_table(self):
  399. for table_entry in _predefined_crc_definitions:
  400. # Check predefined class
  401. crc1 = PredefinedCrc(table_entry['name'])
  402. crc1.update(b"123456789")
  403. self.assertEqual(crc1.crcValue, table_entry['check'], "Wrong answer for CRC '%s'" % table_entry['name'])
  404. class InputTypesTest(unittest.TestCase):
  405. """Check the various input types that CRC functions can accept."""
  406. msg = b'CatMouse987654321'
  407. check_crc_names = [
  408. 'crc-aug-ccitt',
  409. 'x-25',
  410. 'crc-32',
  411. ]
  412. array_check_types = [
  413. 'B',
  414. 'H',
  415. 'I',
  416. 'L',
  417. ]
  418. def test_bytearray_input(self):
  419. """Test that bytearray inputs are accepted, as an example
  420. of a type that implements the buffer protocol."""
  421. for crc_name in self.check_crc_names:
  422. crcfun = mkPredefinedCrcFun(crc_name)
  423. for i in range(len(self.msg) + 1):
  424. test_msg = self.msg[:i]
  425. bytes_answer = crcfun(test_msg)
  426. bytearray_answer = crcfun(bytearray(test_msg))
  427. self.assertEqual(bytes_answer, bytearray_answer)
  428. def test_array_input(self):
  429. """Test that array inputs are accepted, as an example
  430. of a type that implements the buffer protocol."""
  431. for crc_name in self.check_crc_names:
  432. crcfun = mkPredefinedCrcFun(crc_name)
  433. for i in range(len(self.msg) + 1):
  434. test_msg = self.msg[:i]
  435. bytes_answer = crcfun(test_msg)
  436. for array_type in self.array_check_types:
  437. if i % array(array_type).itemsize == 0:
  438. test_array = array(array_type, test_msg)
  439. array_answer = crcfun(test_array)
  440. self.assertEqual(bytes_answer, array_answer)
  441. def test_unicode_input(self):
  442. """Test that Unicode input raises TypeError"""
  443. for crc_name in self.check_crc_names:
  444. crcfun = mkPredefinedCrcFun(crc_name)
  445. with self.assertRaises(TypeError):
  446. crcfun("123456789")
  447. def runtests():
  448. print("Using extension:", _usingExtension)
  449. print()
  450. unittest.main()
  451. if __name__ == '__main__':
  452. runtests()