#!/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 . # 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 from utils import Progress, VERBOSE 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 longs expressions (from 256 to 65536 op )""" for i in Progress(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 3 very long expression (5242K op) """ argc = 4 codelen = 0x50000 import time for i in Progress(3): args = [random.randint(0,IMAX) for _ in range(argc)] if VERBOSE: sys.stderr.write('Generate') sys.stderr.flush() expr_str = pyrpn.random_expr(argc, codelen) if VERBOSE: sys.stderr.write('d Compile') sys.stderr.flush() expr = pyrpn.RPNExpr(expr_str, argc) if VERBOSE: sys.stderr.write('d ') sys.stderr.flush() 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)) pik2 = pickle.dumps(new_expr) args = [random.randint(0,IMAX) for _ in range(argc)] self.assertEqual(expr.eval(*args), new_expr.eval(*args)) self.assertEqual(pik, pik2) if __name__ == '__main__': unittest.main()