From ae6664b7cf868804fdd8b242c29a5550ae8cb464 Mon Sep 17 00:00:00 2001 From: Lafrite Date: Fri, 28 Feb 2014 10:31:56 +0100 Subject: [PATCH] new unittest for expression --- pymath/expression.py | 2 +- test/test_expression.py | 41 +++++++++++++++++++++++++++++++++++++++-- 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/pymath/expression.py b/pymath/expression.py index 58f9dd6..99f0761 100644 --- a/pymath/expression.py +++ b/pymath/expression.py @@ -111,7 +111,7 @@ class Expression(object): ## --------------------- ## String parsing - ## @classmethod ???? + @classmethod def str2tokens(self, exp): """ Parse the expression, ie tranform a string into a list of tokens diff --git a/test/test_expression.py b/test/test_expression.py index 34cc015..16276ba 100644 --- a/test/test_expression.py +++ b/test/test_expression.py @@ -8,13 +8,16 @@ import unittest from pymath.expression import Expression from pymath.fraction import Fraction from pymath.generic import first_elem +from pymath.renders import txt_render class TestExpression(unittest.TestCase): """Testing functions from pymath.expression""" - def test_init_from_exp(self): - pass + def test_init_from_str(self): + exp = Expression("2 + 3") + self.assertEqual(exp.infix_tokens, [2, "+", 3]) + self.assertEqual(exp.postfix_tokens, [2, 3, "+"]) def test_init_from_exp(self): pass @@ -25,6 +28,30 @@ class TestExpression(unittest.TestCase): def test_postfix_tokens(self): pass + def test_str2tokens_big_num(self): + exp = "123 + 3" + tok = Expression.str2tokens(exp) + self.assertEqual(tok, [123, "+", 3]) + + def test_str2tokens_beg_minus(self): + exp = "-123 + 3" + tok = Expression.str2tokens(exp) + self.assertEqual(tok, [-123, "+", 3]) + + def test_str2tokens_time_lack(self): + exp = "(-3)(2)" + tok = Expression.str2tokens(exp) + self.assertEqual(tok, ["(", -3, ")", "*","(", 2, ")" ]) + + def test_str2tokens_time_lack2(self): + exp = "-3(2)" + tok = Expression.str2tokens(exp) + self.assertEqual(tok, [-3, "*","(", 2, ")" ]) + + def test_str2tokens_error(self): + exp = "1 + $" + self.assertRaises(ValueError, Expression.str2tokens, exp) + def test_doMath(self): ops = [\ {"op": ("+", 1 , 2), "res" : 3}, \ @@ -43,6 +70,16 @@ class TestExpression(unittest.TestCase): def test_isOperator(self): pass + def test_simplify_frac(self): + exp = Expression("1/2 - 4") + steps = ["[1, 2, '/', 4, '-']", \ + "[< Fraction 1 / 2>, 4, '-']", \ + "[1, 1, '*', 2, 1, '*', '/', 4, 2, '*', 1, 2, '*', '/', '-']", \ + "[1, 8, '-', 2, '/']", \ + '[< Fraction -7 / 2>]'] + self.assertEqual(steps, list(exp.simplify())) + + if __name__ == '__main__': unittest.main()