Compare commits

...

2 commits

Author SHA1 Message Date
b4dc6e5f18 Splitting TestCase in different files 2020-01-25 16:02:33 +01:00
1e608ca59f New long compilation tests 2020-01-25 15:57:05 +01:00
3 changed files with 214 additions and 134 deletions

124
tests/tests_pyrpn.py Executable file
View file

@ -0,0 +1,124 @@
#!/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 pickle
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 !")
if __name__ == '__main__':
unittest.main()

89
tests/tests_rpn_compile.py Executable file
View file

@ -0,0 +1,89 @@
#!/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 pickle
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 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(0x100,0x10000,0x500):
with self.subTest('Testing expression with %X ops' % i):
for argc in range(1,32, 8):
args = [random.randint(0,IMAX) for _ in range(argc)]
expr = pyrpn.RPNExpr(pyrpn.random_expr(argc, i), argc)
del(expr)
def test_very_long(self):
""" Compile a very long expression """
argc = 4
codelen = 0x500000
import time
for i in range(3):
args = [random.randint(0,IMAX) for _ in range(argc)]
expr_str = pyrpn.random_expr(argc, codelen)
expr = pyrpn.RPNExpr(expr_str, argc)
del(expr)
def test_pickling(self):
""" Pickle & unpickle tests """
argc = 4
for _ in range(512):
expr = pyrpn.RPNExpr(pyrpn.random_expr(2,10), argc)
pik = pickle.dumps(expr)
new_expr = pickle.loads(pik)
self.assertEqual(str(expr), str(new_expr))
args = [random.randint(0,IMAX) for _ in range(argc)]
self.assertEqual(expr.eval(*args), new_expr.eval(*args))
if __name__ == '__main__':
unittest.main()

View file

@ -34,131 +34,6 @@ except (ImportError, NameError) as e:
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)
def test_pickling(self):
""" Pickle & unpickle tests """
argc = 4
for _ in range(512):
expr = pyrpn.RPNExpr(pyrpn.random_expr(2,10), argc)
pik = pickle.dumps(expr)
new_expr = pickle.loads(pik)
self.assertEqual(str(expr), str(new_expr))
args = [random.randint(0,IMAX) for _ in range(argc)]
self.assertEqual(expr.eval(*args), new_expr.eval(*args))
class TestRpnEval(unittest.TestCase):
def test_arithm(self):
@ -276,13 +151,5 @@ class TestRpnEval(unittest.TestCase):
'%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())
unittest.main()