test_calc.py 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. ('xy4', N('*', L('x'), N('^', L('y'), L(4)))),
  30. ('(x)4', N('*', L('x'), L(4))),
  31. ('(3+4)2', N('*', N('+', L(3), L(4)), L(2))),
  32. ]
  33. run_expressions(Parser, expressions)
  34. def test_concat_intermediate(self):
  35. expressions = [
  36. ('(3+4)(5+7)', N('*', N('+', L(3), L(4)),
  37. N('+', L(5), L(7)))),
  38. ('(a+b)(c+d)', N('*', N('+', L('a'), L('b')),
  39. N('+', L('c'), L('d')))),
  40. ('a+b(c+d)', N('+', L('a'), N('*', L('b'),
  41. N('+', L('c'), L('d'))))),
  42. ('abcd', N('*', L('a'), L('b'), L('c'), L('d'))),
  43. ('ab(c)d', N('*', L('a'), L('b'), L('c'), L('d'))),
  44. #('ab(c)d', N('*', L('a'), N('*', L('b'),
  45. # N('*', L('c'), L('d'))))),
  46. ('ab*(c)*d', N('*', L('a'), L('b'), L('c'), L('d'))),
  47. ('ab*(c)^d', N('*', L('a'), L('b'),
  48. N('^', L('c'), L('d')))),
  49. ]
  50. run_expressions(Parser, expressions)
  51. def test_pow_nested(self):
  52. # a^b^c = a^(b^c) != (a^b)^c
  53. a, b, c, d, e = L('a'), L('b'), L('c'), L('d'), L('e')
  54. expressions = [
  55. ('a^b^c', N('^', a, N('^', b, c))),
  56. ('-1^b^c', N('-', N('^', L(1), N('^', b, c)))),
  57. ('ab^c', N('*', a, N('^', b, c))),
  58. ('a(b)^c', N('*', a, N('^', b, c))),
  59. ('a(b+c)^(d+e)', N('*', a, N('^', N('+', b, c),
  60. N('+', d, e)))),
  61. ('(a(b+c))^(d+e)', N('^', N('*', a, N('+', b, c)),
  62. N('+', d, e))),
  63. ]
  64. run_expressions(Parser, expressions)