Unit test - start of reverse polish notation class
Jump to navigation
Jump to search
These are the two files, I made in class for unit test demo purposes.
My original class in the file: ReversePolishCalc.py
class ReversePolishCalc:
def __init__(self):
self.stack = list()
def _checkstack(self, count):
if len(self.stack) < count:
raise IndexError("Stack does not contain enough elements to perform operaation")
def push(self, vector):
if isinstance(vector, (int, float, str)):
vector = [vector]
if not isinstance(vector, (list, tuple)):
raise ValueError("Input can not be understood as numbers")
for number in vector:
if isinstance(number, (int, float)):
self.stack.append(number)
elif isinstance(number, str):
try:
self.stack.append(int(number))
except ValueError:
try:
self.stack.append(float(number))
except ValueError:
raise ValueError("Input can not be understood as numbers")
else:
raise ValueError("Input can not be understood as numbers")
def pop(self):
self._checkstack(1)
return self.stack.pop()
def add(self):
self._checkstack(2)
self.stack[-2] += self.stack[-1]
del self.stack[-1]
def subtract(self):
self._checkstack(2)
self.stack[-2] -= self.stack[-1]
del self.stack[-1]
def multiply(self):
self._checkstack(2)
self.stack[-2] *= self.stack[-1]
del self.stack[-1]
def divide(self):
self._checkstack(2)
if self.stack[-1] == 0:
raise ZeroDivisionError
self.stack[-2] /= self.stack[-1]
del self.stack[-1]
def factorial(self):
self._checkstack(1)
no = int(self.stack[-1])
if no != self.stack[-1]:
raise ValueError("Factorial with floats is invalid")
if no < 0:
raise ValueError("Factorial can not be calcuated with negatives")
res = 1
for i in range(2, no+1):
res *= i
self.stack[-1] = res
My test file of the class: test_ReversePolishCalc.py
import pytest
from ReversePolishCalc import ReversePolishCalc as rpc
def test_push1():
# Arrange
calc = rpc()
# Act
calc.push(1)
# Assert
assert calc.stack[-1] == 1, "Simple push of integer 1"
def test_push2():
# Arrange
calc = rpc()
# Act
calc.push(1)
# Assert
assert calc.stack[0] == 1, "Simple push of integer 2"
def test_push3():
# Arrange
calc = rpc()
# Act
calc.push(1.2)
# Assert
assert calc.stack[0] == 1.2, "Push of float"
def test_push4():
# Arrange
calc = rpc()
# Act
calc.push("1")
# Assert
assert calc.stack[0] == 1, "Push of 1 as string"
def test_push5():
# Arrange
calc = rpc()
# Act
calc.push([1, 1.5, "2.5"])
# Assert
assert calc.stack == [1, 1.5, 2.5], "Advanced list push of ints, floats and strings"
@pytest.mark.parametrize("x,y", [(1,1), (1.2, 1.2), ("1.2", 1.2), ("1", 1)])
def test_push(x,y):
# Arrange
calc = rpc()
# Act
calc.push(x)
# Assert
assert calc.stack[0] == y, "Push of 1 as string"
def test_pop1():
# Arrange
calc = rpc()
calc.push(1)
# Act
num = calc.pop()
# Assert
assert num == 1
def test_failpop1():
# Arrange
calc = rpc()
# Act
with pytest.raises(IndexError):
num = calc.pop()
# Assert