Files @ cc4182acd584
Branch filter:

Location: Shamira/src/tests/test_gf256.py - annotation

Laman
reformatted whitespace with more respect for PEP-8
# GNU GPLv3, see LICENSE

import random
import unittest
from unittest import TestCase

from gf256 import _gfmul
from gf256 import *


class TestGF256(TestCase):
	def test_gfmul(self):
		self.assertEqual(_gfmul(0, 0), 0)
		self.assertEqual(_gfmul(1, 1), 1)
		self.assertEqual(_gfmul(2, 2), 4)
		self.assertEqual(_gfmul(0, 21), 0)
		self.assertEqual(_gfmul(0x53, 0xca), 0x01)
		self.assertEqual(_gfmul(0xff, 0xff), 0x13)

	def testGfmul(self):
		for a in range(256):
			for b in range(256):
				self.assertEqual(_gfmul(a, b), gfmul(a, b))

	def testEvaluate(self):
		for x in range(256):
			(a0, a1, a2, a3) = (x, x>>1, x>>2, x>>3)
			self.assertEqual(evaluate([17], x), 17)  # constant polynomial
			self.assertEqual(evaluate([a0, a1, a2, a3], 0), x)  # any polynomial at 0
			self.assertEqual(evaluate([a0, a1, a2, a3], 1), a0^a1^a2^a3)  # polynomial at 1 == sum of coefficients

	def testGetConstantCoef(self):
		self.assertEqual(getConstantCoef((1, 1), (2, 2), (3, 3)), 0)

		random.seed(17)
		randomMatches = 0
		for i in range(10):
			k = random.randint(2, 255)

			# exact
			res = self.checkCoefsMatch(k, k)
			self.assertEqual(res[0], res[1])

			# overdetermined
			res = self.checkCoefsMatch(k, 256)
			self.assertEqual(res[0], res[1])

			# underdetermined => random
			res = self.checkCoefsMatch(k, k-1)
			if res[0]==res[1]:
				randomMatches += 1
		self.assertLess(randomMatches, 2)  # with a chance (255/256)**10=0.96 there should be no match

	def checkCoefsMatch(self, k, m):
		coefs = [random.randint(0, 255) for i in range(k)]
		points = [(j, evaluate(coefs, j)) for j in range(1, 256)]
		random.shuffle(points)
		return (getConstantCoef(*points[:m]), coefs[0])


if __name__=='__main__':
	unittest.main()