test_calc.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import unittest
  2. from src.parser import Parser
  3. from src.node import ExpressionNode as N, ExpressionLeaf as L
  4. from tests.parser import ParserWrapper, run_expressions
  5. class TestCalc(unittest.TestCase):
  6. def test_constructor(self):
  7. assert ParserWrapper(Parser).run(['1+4']) \
  8. == N('+', L(1), L(4))
  9. def test_basic_on_exp(self):
  10. expressions = [('4', L(4)),
  11. ('3+4', N('+', L(3), L(4))),
  12. ('3-4', N('-', L(3), L(4))),
  13. ('3/4', N('/', L(3), L(4))),
  14. ('-4', N('-', L(4))),
  15. ('3^4', N('^', L(3), L(4))),
  16. ('(2)', L(2))]
  17. run_expressions(Parser, expressions)
  18. def test_infinity(self):
  19. expressions = [('2^3000', N('^', L(2), L(3000))),
  20. ('2^-3000', N('^', L(2), N('-', L(3000))))]
  21. # ('2^99999999999', None),
  22. # ('2^-99999999999', 0.0)]
  23. run_expressions(Parser, expressions)
  24. def test_concat_easy(self):
  25. expressions = [
  26. ('xy', N('*', L('x'), L('y'))),
  27. ('2x', N('*', L(2), L('x'))),
  28. ('x4', N('^', L('x'), L(4))),
  29. ('3 4', N('*', L(3), L(4))),
  30. ('xy4', N('*', L('x'), N('^', L('y'), L(4)))),
  31. ('(x)4', N('*', L('x'), L(4))),
  32. ('(3+4)2', N('*', N('+', L(3), L(4)), L(2))),
  33. ]
  34. run_expressions(Parser, expressions)
  35. def test_concat_intermediate(self):
  36. expressions = [
  37. ('(3+4)(5+7)', N('*', N('+', L(3), L(4)),
  38. N('+', L(5), L(7)))),
  39. ('(a+b)(c+d)', N('*', N('+', L('a'), L('b')),
  40. N('+', L('c'), L('d')))),
  41. ('a+b(c+d)', N('+', L('a'), N('*', L('b'),
  42. N('+', L('c'), L('d'))))),
  43. ('abcd', N('*', L('a'), L('b'), L('c'), L('d'))),
  44. ('ab(c)d', N('*', L('a'), L('b'), L('c'), L('d'))),
  45. #('ab(c)d', N('*', L('a'), N('*', L('b'),
  46. # N('*', L('c'), L('d'))))),
  47. ('ab*(c)*d', N('*', L('a'), L('b'), L('c'), L('d'))),
  48. ('ab*(c)^d', N('*', L('a'), L('b'),
  49. N('^', L('c'), L('d')))),
  50. ]
  51. run_expressions(Parser, expressions)
  52. def test_pow_nested(self):
  53. # a^b^c = a^(b^c) != (a^b)^c
  54. a, b, c, d, e = L('a'), L('b'), L('c'), L('d'), L('e')
  55. expressions = [
  56. ('a^b^c', N('^', a, N('^', b, c))),
  57. ('-1^b^c', N('-', N('^', L(1), N('^', b, c)))),
  58. ('ab^c', N('*', a, N('^', b, c))),
  59. ('a(b)^c', N('*', a, N('^', b, c))),
  60. ('a(b+c)^(d+e)', N('*', a, N('^', N('+', b, c),
  61. N('+', d, e)))),
  62. ('(a(b+c))^(d+e)', N('^', N('*', a, N('+', b, c)),
  63. N('+', d, e))),
  64. ]
  65. run_expressions(Parser, expressions)