Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions src/calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,46 @@
# Multiplication: 8
# Division: 2
#
import enum

class OperationType(enum.Enum):
SUM = 1
DIFFERENCE = 2
MULTIPLICATION = 3
DIVISION = 4

def sum(a, b):
return a + b

def difference(a, b):
return a - b

def multiplication(a, b):
return a * b

def division(a, b):
if b != 0:
return a / b
else:
raise ValueError("Error: Division by zero")

def operation(a, b, op: OperationType):
if op == OperationType.SUM:
return sum(a, b)
elif op == OperationType.DIFFERENCE:
return difference(a, b)
elif op == OperationType.MULTIPLICATION:
return multiplication(a, b)
elif op == OperationType.DIVISION:
return division(a, b)
else:
raise ValueError("Invalid operation")

if __name__ == "__main__":
num1 = float(input("Insert first number: "))
num2 = float(input("Insert second number: "))

print(f"SUM: {operation(num1, num2, OperationType.SUM)}")
print(f"Difference: {operation(num1, num2, OperationType.DIFFERENCE)}")
print(f"Multiplication: {operation(num1, num2, OperationType.MULTIPLICATION)}")
print(f"Division: {operation(num1, num2, OperationType.DIVISION)}")
44 changes: 44 additions & 0 deletions tests/test_calculator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
from src.calculator import operation, OperationType

def test_calculator_operations() -> None:
assert operation(4, 2, op=OperationType.SUM) == 6 # SUM
assert operation(4, 2, op=OperationType.DIFFERENCE) == 2 # DIFFERENCE
assert operation(4, 2, op=OperationType.MULTIPLICATION) == 8 # MULTIPLICATION
assert operation(4, 2, op=OperationType.DIVISION) == 2 # DIVISION
try:
operation(4, 0, op=OperationType.DIVISION)
except ValueError as e:
assert str(e) == "Error: Division by zero" # DIVISION by zero
try:
operation(4, 2, op=None) # Invalid operation
except ValueError as e:
assert str(e) == "Invalid operation"

def test_calculator_main() -> None:
import builtins
import io
import sys

input_values = ["4", "2"]
output = io.StringIO()
sys.stdout = output

def mock_input(s):
return input_values.pop(0)

builtins.input = mock_input

# Re-import the main module to run the main function
import src.calculator as calculator_module

# Restore stdout
sys.stdout = sys.__stdout__

expected_output = (
"Insert first number: Insert second number: SUM: 6.0\n"
"Difference: 2.0\n"
"Multiplication: 8.0\n"
"Division: 2.0\n"
)

assert output.getvalue() == expected_output
Loading