Skip to content

Commit 721016d

Browse files
committed
[finished hometask] code checking unittests
1 parent c35a88c commit 721016d

File tree

4 files changed

+37
-68
lines changed

4 files changed

+37
-68
lines changed

libs/element.py

Lines changed: 18 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -59,31 +59,22 @@ def __init__(self, expression, func=None):
5959
:param expression: mathematical expression as string
6060
"""
6161
# Validate on expression and raise exception if not true
62-
63-
# if " " in expression:
64-
# raise ExpressionFormatException("Expression should not de with spaces")
65-
66-
# expression = expression.replace(" ", "")
67-
6862
if not expression:
6963
raise NoExpressionException("The expression was not passed")
7064

71-
# if expression.startswith("--") or expression.startswith("=") or expression.startswith("+"):
72-
# raise ExpressionFormatException("The expression bad format")
73-
# if expression.endswith("-"):
74-
# raise ExpressionFormatException("The expression bad format")
75-
76-
# TODO: comment
65+
# Validate function and constant function in expression
7766
self._mathematical_functions = {
7867
name: val for name, val in getmembers(math) if type(val).__name__ == "builtin_function_or_method"
7968
}
8069
self._mathematical_functions["abs"] = abs
8170
self._mathematical_functions["round"] = round
8271

72+
# Validate mathematical constants in expression
8373
self._mathematical_constants = {
8474
name: val for name, val in getmembers(math) if type(val).__name__ == "float"
8575
}
8676

77+
# Check function in expression
8778
self._func = None
8879
if func:
8980
func = func.strip()
@@ -158,12 +149,14 @@ def __init__(self, expression, func=None):
158149
bracket_closed = False
159150

160151
# Validate and count brackets
152+
161153
if i == "(":
162154
bracket_level += 1
163155
if bracket_level == 1:
164156
continue
165157

166158
# Validate and sorted data in brackets
159+
167160
elif i == ")":
168161
bracket_level -= 1
169162
bracket_closed = True
@@ -190,7 +183,10 @@ def __init__(self, expression, func=None):
190183
if item:
191184
if item in self._mathematical_constants:
192185
item = self._mathematical_constants[item]
193-
self._expression.append(float(item))
186+
try:
187+
self._expression.append(float(item))
188+
except ValueError:
189+
raise ExpressionFormatException("Could not convert string to float: '{}'".format(item))
194190
item = []
195191

196192
# Handle double mathematical operation
@@ -216,6 +212,7 @@ def __init__(self, expression, func=None):
216212
except ValueError:
217213
raise ExpressionFormatException("Could not convert string to float: '{}'".format(item))
218214

215+
# Conversation to string expression
219216
def __str__(self):
220217
"""
221218
String representation of the class
@@ -229,6 +226,7 @@ def __str__(self):
229226
data=", ".join(result)
230227
)
231228

229+
# Calculate comparison expression
232230
def _calculate_boolean_expression(self):
233231
boolean_value = True
234232
for i, v in enumerate(self._expression):
@@ -260,6 +258,7 @@ def _calculate_boolean_expression(self):
260258
return boolean_value
261259
return boolean_value
262260

261+
# Calculate mathematical expression
263262
def _calculate_mathematical_expression(self):
264263
operation = None
265264
first_negative = False
@@ -275,8 +274,6 @@ def _calculate_mathematical_expression(self):
275274
if el == "^":
276275
self._expression.pop(i)
277276
power = self._expression.pop(i)
278-
if power == "-":
279-
power = -self._expression.pop(i)
280277
self._expression[i - 1] **= power
281278
i -= 1
282279

@@ -313,8 +310,6 @@ def _calculate_mathematical_expression(self):
313310
if isinstance(i, str):
314311
if i in ("+", "-",):
315312
operation = i
316-
# else:
317-
# raise UnsupportedMathematicalOperationException("We do not support '{}' operation".format(i))
318313
elif operation:
319314
if operation == "+":
320315
value += i
@@ -330,23 +325,13 @@ def _calculate_mathematical_expression(self):
330325

331326
return value
332327

328+
# Calculate value expression
333329
def value(self):
334330
"""
335331
Method for expression calculation
336332
:return: calculate value
337333
"""
338-
339-
# Validate mathematical operations and calculate nested expressions
340-
# i = len(self._expression) - 1
341-
# last_operation = None
342-
# print(">>", self._expression)
343-
# while i >= 0:
344-
# el = self._expression[i]
345-
# if isinstance(el, Element):
346-
# self._expression[i] = el.value()
347-
# last_operation = None
348-
# elif isinstance(el, str):
349-
334+
# Validate unary operation
350335
for i, v in enumerate(self._expression):
351336
if isinstance(v, Element):
352337
self._expression[i] = v.value()
@@ -360,9 +345,11 @@ def value(self):
360345
if v.startswith("+"):
361346
self._expression[i] = "+"
362347

348+
# Validate negative item in expression
363349
expression = []
364350
last_operation = None
365351
sign = None
352+
366353
for i, v in enumerate(self._expression):
367354
if isinstance(v, str):
368355
if last_operation:
@@ -399,33 +386,14 @@ def value(self):
399386
last_operation = None
400387
if sign == "-":
401388
v = -v
402-
sign = None
389+
sign = None
403390
expression.append(v)
404391

405392
if last_operation or sign:
406393
raise ExpressionFormatException("Expression finishes with mathematical operation.")
407394

408395
self._expression = expression
409396

410-
# for i, v in enumerate(self._expression):
411-
# if isinstance(v, str):
412-
# if last_operation and v in ("+", "-",):
413-
# if last_operation == "+" and v == "-":
414-
# self._expression[i] = "-"
415-
# elif last_operation == "-" and v == "+":
416-
# self._expression[i] = "-"
417-
# del self._expression[i - 1]
418-
# elif last_operation and v in self.MATH_ACTIONS:
419-
# raise DoubleOperationException("'{so}' operation follows '{fo}'".format(
420-
# so=last_operation,
421-
# fo=v
422-
# ))
423-
424-
# if v in self.MATH_ACTIONS:
425-
# last_operation = v
426-
# else:
427-
# last_operation = None
428-
429397
# Evaluate comparison expression
430398
if self._comparison_operation:
431399
return self._calculate_boolean_expression()
@@ -436,6 +404,5 @@ def value(self):
436404
return self._func(*self._expression)
437405
except TypeError:
438406
raise ExpressionFormatException("Expected 2 arguments: '{}'".format(self._func))
439-
440-
# print(self._expression)
407+
# Value mathematical expression
441408
return self._calculate_mathematical_expression()

pycalc

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,5 @@ if __name__ == '__main__':
1515
print(expression.value())
1616
except BaseExpressionException as exc:
1717
print("ERROR: {}".format(str(exc)))
18-
except ValueError as exc:
19-
print("ERROR: {}".format(str(exc)))
20-
except TypeError as exc:
21-
print("ERROR: {}".format(str(exc)))
2218
# expression = Element(expression=args.EXPRESSION)
2319
# print(expression.value())

tests/test_negatives.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -82,10 +82,6 @@ def test_comma_without_func(self):
8282
expression = Element(expression="2+3,4")
8383
expression.value()
8484

85-
# def test_calculate_mathematical_expression(self):
86-
# # with self.assertRaises(UnsupportedMathematicalOperationException):
87-
# expression = Element(expression="")
88-
# expression.value()
8985
def test_bad_expression(self):
9086
with self.assertRaises(ExpressionFormatException):
9187
expression = Element(expression="--+1-")
@@ -96,7 +92,17 @@ def test_expression_bad(self):
9692
expression = Element(expression="2-")
9793
expression.value()
9894

99-
def test_expression_with_space(self):
95+
def test_convert_string_to_float(self):
10096
with self.assertRaises(ExpressionFormatException):
101-
expression = Element(expression="2- 3+")
102-
expression.value()
97+
expression = Element(expression="21 + 2(3 * 4))")
98+
expression.value()
99+
100+
def test_first_comparison(self):
101+
with self.assertRaises(ExpressionFormatException):
102+
expression = Element(expression="<=4+6")
103+
expression.value()
104+
105+
def test_unsupported_operation(self):
106+
with self.assertRaises(DoubleOperationException):
107+
expression = Element(expression="4/*5-3")
108+
expression.value()

tests/test_simple.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def test_exponentiation(self):
4242
self.assertEqual(expression.value(), 3)
4343

4444
def test_str(self):
45-
expression = Element(expression="2+3*((5-1)-2)")
45+
expression = Element(expression="2+3*((5-1)-2) ")
4646
self.assertTrue(str(expression), 8)
4747

4848
def test_mathematical_constant(self):
@@ -58,9 +58,9 @@ def test_two_mathematical_constant(self):
5858
self.assertEqual(expression.value(), 8.539734222673566)
5959

6060
def test_unary_operation(self):
61-
expression = Element(expression="2*4-----3+++4--3")
62-
self.assertEqual(expression.value(), 12)
61+
expression = Element(expression="2*4-----3+++-4*-+-+-3")
62+
self.assertEqual(expression.value(), 17)
6363

64-
def test_various_unary_operation(self):
65-
expression = Element(expression="2*4++4-+++4---3++2----1")
66-
self.assertEqual(expression.value(), 8)
64+
def test_negative_exponentiation(self):
65+
expression = Element(expression="2^-8")
66+
self.assertEqual(expression.value(), 0.00390625)

0 commit comments

Comments
 (0)