123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275 |
- #!/usr/bin/python3
- # Copyright 2020 Weber Yann
- #
- # This file is part of geneifs.
- #
- # geneifs is free software: you can redistribute it and/or modify
- # it under the terms of the GNU General Public License as published by
- # the Free Software Foundation, either version 3 of the License, or
- # (at your option) any later version.
- #
- # geneifs is distributed in the hope that it will be useful,
- # but WITHOUT ANY WARRANTY; without even the implied warranty of
- # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- # GNU General Public License for more details.
- #
- # You should have received a copy of the GNU General Public License
- # along with geneifs. If not, see <http://www.gnu.org/licenses/>.
- #
-
- import sys
- import random
- import math
-
- import unittest
- from unittest import skip
-
- IMAX = (1<<64)-1
-
- try:
- import pyrpn
- except (ImportError, NameError) as e:
- print("Error importing pyrpn. Try to run make.",
- file=sys.stderr)
- raise e
-
- class Test0RpnModule(unittest.TestCase):
-
- def test_init(self):
- """ RPNExpr instanciation """
- expr = pyrpn.RPNExpr("42", 2)
-
- def test_init_badargs(self):
- """ RPNExpr instanciation with bad arguments """
- badargs = [('', 2), (), ('ab+',), ('ab+',300), (42, 42), ('ab', '42')]
- for badarg in badargs:
- with self.assertRaises((ValueError, TypeError)):
- expr = pyrpn.RPNExpr(*badarg)
-
- def test_init_loop(self):
- """ Testing pyrpn.RPNExpr multiple instanciation """
- exprs = []
- for i in range(256):
- expr = pyrpn.RPNExpr("42", 2)
-
- def test_init_args(self):
- """ Testing pyrpn.RPNExpr instanciation with arguments """
- for argc in range(0, 256):
- with self.subTest("RPNExpr('42', %d)" % argc):
- expr = pyrpn.RPNExpr("42", argc)
-
- def test_init_stack_sz(self):
- """ Instanciate RPNExpr specifiing a stack_size """
- for argc in range(0,256, 8):
- for sz in range(4, 256, 2):
- with self.subTest("RPNExpr('42', %d,%d)" % (argc, sz)):
- expr = pyrpn.RPNExpr("42", argc, sz)
-
- def test_op_dict(self):
- """ Testing RPNExpr.get_ops() method """
- known_ops = dict([
- ('add', '+'),
- ('sub', '-'),
- ('mul', '*'),
- ('div', '/'),
- ('mod', '%'),
- ('neg', '!'),
- ('not', '~'),
- ('and', '&'),
- ('or', '|'),
- ('xor', '^'),
- ('>>', 'r'),
- ('<<', 'l'),
- ('xchg', 'x'),
- ('dup', 'd'),
- ('pop', 'p'),
- ])
- for long, short in pyrpn.get_ops().items():
- self.assertIn(long, known_ops)
- self.assertEqual(short, known_ops[long])
-
- def test_rand_expr(self):
- """ Testing RPNExpr.random_expr() """
- result = {}
- counters = {'vals': 0, 'args': 0}
- all_count = 0
- for sz in range(1,64,3):
- for argc in range(1,128):
- rnd_expr = pyrpn.random_expr(argc, sz)
- #print(repr(rnd_expr))
- for tok in rnd_expr.split(' '):
- all_count += 1
- if len(tok) == 0:
- continue
- try:
- itok = int(tok, 0)
- counters['vals'] += 1
- continue
- except Exception:
- pass
- if tok[0] == 'A':
- counters['args'] += 1
- else:
- if tok not in counters:
- counters[tok] = 0
- counters[tok] += 1
- all_ops = len(pyrpn.get_ops()) + 2
- entropy = 1-sum([(n/all_count)**2
- for _, n in counters.items()])
- self.assertGreater(entropy, 1-(1/all_ops), "Low entropy !")
-
-
- class TestRpnCompile(unittest.TestCase):
-
- def test_basic(self):
- """ Compile 6 7 * """
- expr = pyrpn.RPNExpr("6 7 *", 2)
-
- def test_base_error(self):
- """ Compile error a b + """
- with self.assertRaises(ValueError):
- expr = pyrpn.RPNExpr("a b +", 3)
-
- def test_various_compile(self):
- """ Compile various expressions """
- exprs = (("42 2 + * /", 0),
- ("A1 A2 A0 * + /", 3),
- )
- for expr, argc in exprs:
- res = pyrpn.RPNExpr(expr, argc)
-
- def test_long_code(self):
- """ Compile long expressions """
- for i in range(64,256,2):
- for j in range(256,4):
- exprs = ' '.join(['+' for _ in range(i)])
- expr = pyrpn.RPNExpr(exprs, j)
-
-
- class TestRpnEval(unittest.TestCase):
-
- def test_arithm(self):
- """ Tests arithmetic ops """
- ops = [
- ('+', '+'),
- ('-', '-'),
- ('*', '*'),
- ('/', '//'),
- ('%', '%'),
- ('&', '&'),
- ('|', '|'),
- ('^', '^'),
- #('l', '<<'),
- #('r', '>>')
- ]
- for rpn_op, pyop in ops:
- with self.subTest('Testing op %s (%s)' % (rpn_op, pyop)):
- sys.stderr.write('.')
- sys.stderr.flush()
- for i in range(0x1000):
- op1, op2 = random.randint(0,IMAX), random.randint(1,IMAX)
- pyexpr = '%d %s %d' % (op1, pyop, op2)
- pyval = eval(pyexpr) % (1<<64)
- rpn_expr = "%d %d %s" % (op1, op2, rpn_op)
- expr = pyrpn.RPNExpr(rpn_expr, 0)
- res = expr.eval()
- self.assertEqual(res, pyval,
- "TEST#%d %s != %s" % (i, rpn_expr, pyexpr))
-
- def test_not(self):
- """ Test unary op """
- ops = [('~', '~%d'), ('!', '-%d')]
- for rpn_op, pystr in ops:
- with self.subTest("Testing op '%sX' (%s)" % (rpn_op, pystr)):
- sys.stderr.write('.')
- sys.stderr.flush()
- for i in range(0x1000):
- op1 = random.randint(0, IMAX)
- pyexpr = pystr % op1
- pyval = eval(pyexpr) % (1<<64)
- rpn_expr = '%d %s' % (op1, rpn_op)
- expr = pyrpn.RPNExpr(rpn_expr, 0)
- res = expr.eval()
- self.assertEqual(res, pyval,
- "TEST#%d %s != %s" % (i, rpn_expr, pyexpr))
-
- def test_div_zero(self):
- """ Test division by zeros """
- tests = ['A0 0 /', 'A0 0 %']
- for test in tests:
- with self.subTest('Testing division by zero using %s' % test):
- for i in range(10):
- expr = pyrpn.RPNExpr(test, 1)
- res = expr.eval(random.randint(0, IMAX))
- self.assertEqual(res, 0)
-
- def test_stack_init(self):
- """ testing that stack is initialized to 0 """
- rpn = ' '.join(['+' for _ in range(15)])
- for stack_size in range(4, 128):
- with self.subTest('Stack with size %d initialized to 0' % stack_size):
- for argc in range(0,256,16):
- expr = pyrpn.RPNExpr(rpn, argc, stack_size)
- r = expr.eval(*[random.randint(0, IMAX)
- for _ in range(argc)])
- self.assertEqual(r, 0,
- '"+ + + +..." should be 0 but %d returned with %d args' % (r, argc))
-
-
- def test_lshift_limit(self):
- """ 2 << 0x10000 == 0 ? """
- expr = pyrpn.RPNExpr("2 %d <<" % 0x100000, 0)
- res = expr.eval()
- self.assertEqual(res, 0)
-
- def test_rshift_limit(self):
- """ (1<<64)-1 >> 0x10000 == 0 ? """
- expr = pyrpn.RPNExpr("%d %d >>" % ((1<<64)-1, 0x100000), 0)
- res = expr.eval()
- self.assertEqual(res, 0)
-
-
- def test_airthm_extended(self):
- """ Extended arithmetic tests """
- exprs = (
- ('A0 A1 +', '{0} + {1}', 2),
- ('A0 A0 A1 + +', '{0} + {1} + {0}', 2),
- ('A1 A0 A0 A0 A0 A0 A0 A0 A0 + + + + + + +', '{0} * 8', 2),
- ('+', '0', 2),
- ('-', '0', 2),
- ('A0 A1 -', '{0} - {1}', 2),
- ('A0 A0 A1 - -', '{0} - ({0} - {1})', 2),
- ('A0 0 A0 - -', '({0} - (0 - {0})) ', 2),
- ('*', '0', 2),
- ('A0 A1 *', '{0} * {1}', 2),
- ('A0 A0 A1 * *', '{0} * {0} * {1}', 2),
- ('A0 A0 A0 * *', '{0} * {0} * {0}', 2),
- ('A0 A1 x /', '{1} // {0}', 2),
- ('A0 A1 A0 pop /', '{0} // {1}', 2),
- ('A0 A1 dup +', '{1} + {1}', 2),
- )
- for rpn, pye, argc in exprs:
- expr = pyrpn.RPNExpr(rpn, argc, 8)
- for _ in range(0x300):
- args = tuple([random.randint(0,255) for _ in range(argc)])
- with self.subTest('%s == %s %r' % (rpn, pye, args)):
- pyexpr = pye.format(*args)
- try:
- respy = eval(pyexpr) % (1<<64)
- except ZeroDivisionError:
- respy = 0
- res = expr.eval(*args)
- self.assertEqual(res, respy,
- '%s%r != %s' % (rpn, args, pyexpr))
-
-
- class SequentialTestLoader(unittest.TestLoader):
- def getTestCaseNames(self, testCaseClass):
- test_names = super().getTestCaseNames(testCaseClass)
- testcase_methods = list(testCaseClass.__dict__.keys())
- test_names.sort(key=testcase_methods.index)
- return test_names
-
-
- if __name__ == '__main__':
- unittest.main(testLoader=SequentialTestLoader())
|