Fast IFS using RPN notation
python
c
x86-64
nasm
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

tests_rpn.py 9.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. #!/usr/bin/python3
  2. # Copyright 2020 Weber Yann
  3. #
  4. # This file is part of geneifs.
  5. #
  6. # geneifs is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # geneifs is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with geneifs. If not, see <http://www.gnu.org/licenses/>.
  18. #
  19. import sys
  20. import random
  21. import math
  22. import unittest
  23. from unittest import skip
  24. IMAX = (1<<64)-1
  25. try:
  26. import pyrpn
  27. except (ImportError, NameError) as e:
  28. print("Error importing pyrpn. Try to run make.",
  29. file=sys.stderr)
  30. raise e
  31. class Test0RpnModule(unittest.TestCase):
  32. def test_init(self):
  33. """ RPNExpr instanciation """
  34. expr = pyrpn.RPNExpr("42", 2)
  35. def test_init_badargs(self):
  36. """ RPNExpr instanciation with bad arguments """
  37. badargs = [('', 2), (), ('ab+',), ('ab+',300), (42, 42), ('ab', '42')]
  38. for badarg in badargs:
  39. with self.assertRaises((ValueError, TypeError)):
  40. expr = pyrpn.RPNExpr(*badarg)
  41. def test_init_loop(self):
  42. """ Testing pyrpn.RPNExpr multiple instanciation """
  43. exprs = []
  44. for i in range(256):
  45. expr = pyrpn.RPNExpr("42", 2)
  46. def test_init_args(self):
  47. """ Testing pyrpn.RPNExpr instanciation with arguments """
  48. for argc in range(0, 256):
  49. with self.subTest("RPNExpr('42', %d)" % argc):
  50. expr = pyrpn.RPNExpr("42", argc)
  51. def test_init_stack_sz(self):
  52. """ Instanciate RPNExpr specifiing a stack_size """
  53. for argc in range(0,256, 8):
  54. for sz in range(4, 256, 2):
  55. with self.subTest("RPNExpr('42', %d,%d)" % (argc, sz)):
  56. expr = pyrpn.RPNExpr("42", argc, sz)
  57. def test_op_dict(self):
  58. """ Testing RPNExpr.get_ops() method """
  59. known_ops = dict([
  60. ('add', '+'),
  61. ('sub', '-'),
  62. ('mul', '*'),
  63. ('div', '/'),
  64. ('mod', '%'),
  65. ('neg', '!'),
  66. ('not', '~'),
  67. ('and', '&'),
  68. ('or', '|'),
  69. ('xor', '^'),
  70. ('>>', 'r'),
  71. ('<<', 'l'),
  72. ('xchg', 'x'),
  73. ('dup', 'd'),
  74. ('pop', 'p'),
  75. ])
  76. for long, short in pyrpn.get_ops().items():
  77. self.assertIn(long, known_ops)
  78. self.assertEqual(short, known_ops[long])
  79. def test_rand_expr(self):
  80. """ Testing RPNExpr.random_expr() """
  81. result = {}
  82. counters = {'vals': 0, 'args': 0}
  83. all_count = 0
  84. for sz in range(1,64,3):
  85. for argc in range(1,128):
  86. rnd_expr = pyrpn.random_expr(argc, sz)
  87. #print(repr(rnd_expr))
  88. for tok in rnd_expr.split(' '):
  89. all_count += 1
  90. if len(tok) == 0:
  91. continue
  92. try:
  93. itok = int(tok, 0)
  94. counters['vals'] += 1
  95. continue
  96. except Exception:
  97. pass
  98. if tok[0] == 'A':
  99. counters['args'] += 1
  100. else:
  101. if tok not in counters:
  102. counters[tok] = 0
  103. counters[tok] += 1
  104. all_ops = len(pyrpn.get_ops()) + 2
  105. entropy = 1-sum([(n/all_count)**2
  106. for _, n in counters.items()])
  107. self.assertGreater(entropy, 1-(1/all_ops), "Low entropy !")
  108. class TestRpnCompile(unittest.TestCase):
  109. def test_basic(self):
  110. """ Compile 6 7 * """
  111. expr = pyrpn.RPNExpr("6 7 *", 2)
  112. def test_base_error(self):
  113. """ Compile error a b + """
  114. with self.assertRaises(ValueError):
  115. expr = pyrpn.RPNExpr("a b +", 3)
  116. def test_various_compile(self):
  117. """ Compile various expressions """
  118. exprs = (("42 2 + * /", 0),
  119. ("A1 A2 A0 * + /", 3),
  120. )
  121. for expr, argc in exprs:
  122. res = pyrpn.RPNExpr(expr, argc)
  123. def test_long_code(self):
  124. """ Compile long expressions """
  125. for i in range(64,256,2):
  126. for j in range(256,4):
  127. exprs = ' '.join(['+' for _ in range(i)])
  128. expr = pyrpn.RPNExpr(exprs, j)
  129. class TestRpnEval(unittest.TestCase):
  130. def test_arithm(self):
  131. """ Tests arithmetic ops """
  132. ops = [
  133. ('+', '+'),
  134. ('-', '-'),
  135. ('*', '*'),
  136. ('/', '//'),
  137. ('%', '%'),
  138. ('&', '&'),
  139. ('|', '|'),
  140. ('^', '^'),
  141. #('l', '<<'),
  142. #('r', '>>')
  143. ]
  144. for rpn_op, pyop in ops:
  145. with self.subTest('Testing op %s (%s)' % (rpn_op, pyop)):
  146. sys.stderr.write('.')
  147. sys.stderr.flush()
  148. for i in range(0x1000):
  149. op1, op2 = random.randint(0,IMAX), random.randint(1,IMAX)
  150. pyexpr = '%d %s %d' % (op1, pyop, op2)
  151. pyval = eval(pyexpr) % (1<<64)
  152. rpn_expr = "%d %d %s" % (op1, op2, rpn_op)
  153. expr = pyrpn.RPNExpr(rpn_expr, 0)
  154. res = expr.eval()
  155. self.assertEqual(res, pyval,
  156. "TEST#%d %s != %s" % (i, rpn_expr, pyexpr))
  157. def test_not(self):
  158. """ Test unary op """
  159. ops = [('~', '~%d'), ('!', '-%d')]
  160. for rpn_op, pystr in ops:
  161. with self.subTest("Testing op '%sX' (%s)" % (rpn_op, pystr)):
  162. sys.stderr.write('.')
  163. sys.stderr.flush()
  164. for i in range(0x1000):
  165. op1 = random.randint(0, IMAX)
  166. pyexpr = pystr % op1
  167. pyval = eval(pyexpr) % (1<<64)
  168. rpn_expr = '%d %s' % (op1, rpn_op)
  169. expr = pyrpn.RPNExpr(rpn_expr, 0)
  170. res = expr.eval()
  171. self.assertEqual(res, pyval,
  172. "TEST#%d %s != %s" % (i, rpn_expr, pyexpr))
  173. def test_div_zero(self):
  174. """ Test division by zeros """
  175. tests = ['A0 0 /', 'A0 0 %']
  176. for test in tests:
  177. with self.subTest('Testing division by zero using %s' % test):
  178. for i in range(10):
  179. expr = pyrpn.RPNExpr(test, 1)
  180. res = expr.eval(random.randint(0, IMAX))
  181. self.assertEqual(res, 0)
  182. def test_stack_init(self):
  183. """ testing that stack is initialized to 0 """
  184. rpn = ' '.join(['+' for _ in range(15)])
  185. for stack_size in range(4, 128):
  186. with self.subTest('Stack with size %d initialized to 0' % stack_size):
  187. for argc in range(0,256,16):
  188. expr = pyrpn.RPNExpr(rpn, argc, stack_size)
  189. r = expr.eval(*[random.randint(0, IMAX)
  190. for _ in range(argc)])
  191. self.assertEqual(r, 0,
  192. '"+ + + +..." should be 0 but %d returned with %d args' % (r, argc))
  193. def test_lshift_limit(self):
  194. """ 2 << 0x10000 == 0 ? """
  195. expr = pyrpn.RPNExpr("2 %d <<" % 0x100000, 0)
  196. res = expr.eval()
  197. self.assertEqual(res, 0)
  198. def test_rshift_limit(self):
  199. """ (1<<64)-1 >> 0x10000 == 0 ? """
  200. expr = pyrpn.RPNExpr("%d %d >>" % ((1<<64)-1, 0x100000), 0)
  201. res = expr.eval()
  202. self.assertEqual(res, 0)
  203. def test_airthm_extended(self):
  204. """ Extended arithmetic tests """
  205. exprs = (
  206. ('A0 A1 +', '{0} + {1}', 2),
  207. ('A0 A0 A1 + +', '{0} + {1} + {0}', 2),
  208. ('A1 A0 A0 A0 A0 A0 A0 A0 A0 + + + + + + +', '{0} * 8', 2),
  209. ('+', '0', 2),
  210. ('-', '0', 2),
  211. ('A0 A1 -', '{0} - {1}', 2),
  212. ('A0 A0 A1 - -', '{0} - ({0} - {1})', 2),
  213. ('A0 0 A0 - -', '({0} - (0 - {0})) ', 2),
  214. ('*', '0', 2),
  215. ('A0 A1 *', '{0} * {1}', 2),
  216. ('A0 A0 A1 * *', '{0} * {0} * {1}', 2),
  217. ('A0 A0 A0 * *', '{0} * {0} * {0}', 2),
  218. ('A0 A1 x /', '{1} // {0}', 2),
  219. ('A0 A1 A0 pop /', '{0} // {1}', 2),
  220. ('A0 A1 dup +', '{1} + {1}', 2),
  221. )
  222. for rpn, pye, argc in exprs:
  223. expr = pyrpn.RPNExpr(rpn, argc, 8)
  224. for _ in range(0x300):
  225. args = tuple([random.randint(0,255) for _ in range(argc)])
  226. with self.subTest('%s == %s %r' % (rpn, pye, args)):
  227. pyexpr = pye.format(*args)
  228. try:
  229. respy = eval(pyexpr) % (1<<64)
  230. except ZeroDivisionError:
  231. respy = 0
  232. res = expr.eval(*args)
  233. self.assertEqual(res, respy,
  234. '%s%r != %s' % (rpn, args, pyexpr))
  235. class SequentialTestLoader(unittest.TestLoader):
  236. def getTestCaseNames(self, testCaseClass):
  237. test_names = super().getTestCaseNames(testCaseClass)
  238. testcase_methods = list(testCaseClass.__dict__.keys())
  239. test_names.sort(key=testcase_methods.index)
  240. return test_names
  241. if __name__ == '__main__':
  242. unittest.main(testLoader=SequentialTestLoader())