Skip to content

Commit

Permalink
Merge pull request #4 from Adal3n3/step1
Browse files Browse the repository at this point in the history
Step1
  • Loading branch information
Adal3n3 authored Apr 23, 2024
2 parents 1b5fb3e + 3018374 commit f9874be
Show file tree
Hide file tree
Showing 4 changed files with 79 additions and 0 deletions.
35 changes: 35 additions & 0 deletions api/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from flask import (
Flask,
request,
)

from calculator.calculator import Calculator

app = Flask(__name__)

@app.route('/api/add', methods=['POST'])
def add():
return operation('add', 2)

@app.route('/api/subtract', methods=['POST'])
def subtract():
return operation('subtract', 2)

@app.route('/api/multiply', methods=['POST'])
def multiply():
return operation('multiply', 2)

@app.route('/api/divide', methods=['POST'])
def divide():
return operation('divide', 2)

def operation(method, num_factors):
factors = []
if num_factors == 2:
factors.append(float(request.json.get('x')))
factors.append(float(request.json.get('y')))

return str(getattr(Calculator, method)(*factors))


app.run(host='0.0.0.0', port=8080)
Empty file added api/calculator/__init__.py
Empty file.
14 changes: 14 additions & 0 deletions api/calculator/calculator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
class Calculator:
def add(x, y):
return x + y

def subtract(x, y):
return x - y

def multiply(x, y):
return x * y

def divide(x, y):
if y == 0:
return 'Cannot divide by 0'
return x * 1.0 / y
30 changes: 30 additions & 0 deletions api/calculator/test_calculator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from .calculator import Calculator


def test_add():
assert Calculator.add(1, 2) == 3.0
assert Calculator.add(1.0, 2.0) == 3.0
assert Calculator.add(0, 2.0) == 2.0
assert Calculator.add(2.0, 0) == 2.0
assert Calculator.add(-4, 2.0) == -2.0

def test_subtract():
assert Calculator.subtract(1, 2) == -1.0
assert Calculator.subtract(2, 1) == 1.0
assert Calculator.subtract(1.0, 2.0) == -1.0
assert Calculator.subtract(0, 2.0) == -2.0
assert Calculator.subtract(2.0, 0.0) == 2.0
assert Calculator.subtract(-4, 2.0) == -6.0

def test_multiply():
assert Calculator.multiply(1, 2) == 2.0
assert Calculator.multiply(1.0, 2.0) == 2.0
assert Calculator.multiply(0, 2.0) == 0.0
assert Calculator.multiply(2.0, 0.0) == 0.0
assert Calculator.multiply(-4, 2.0) == -8.0

def test_divide():
assert Calculator.divide(1, 2) == 0.5
assert Calculator.divide(1.0, 2.0) == 0.5
assert Calculator.divide(0, 2.0) == 0
assert Calculator.divide(-4, 2.0) == -2.0

0 comments on commit f9874be

Please sign in to comment.