how to make a calculator 9
I want to make a website for the calculator so that anyone can use it in their browser without installing Python or running code.
preview
I have these tests by the end of the chapter
1import src.website
2import tests.test_calculator
3import unittest
4
5
6class TestCalculatorWebsite(unittest.TestCase):
7
8 def setUp(self):
9 self.client = src.website.app.test_client()
10 self.x = tests.test_calculator.a_random_number()
11
12 def test_home_page(self):
13 response = self.client.get('/')
14 self.assertEqual(response.status_code, 200)
15 self.assertIn(
16 b'<h1>Calculator</h1>',
17 response.data
18 )
19
20 def test_calculations(self):
21 y = tests.test_calculator.a_random_number()
22
23 operations = {
24 'add': '+',
25 'subtract': '-',
26 'divide': '/',
27 'multiply': '*',
28 }
29
30 for operation in operations:
31 with self.subTest(operation=operation):
32 response = self.client.post(
33 '/calculate',
34 data={
35 'first_input': self.x,
36 'second_input': y,
37 'operation': operation,
38 }
39 )
40 self.assertEqual(response.status_code, 200)
41
42 function = src.calculator.__getattribute__(
43 operation
44 )
45 result = function(self.x, y)
46 self.assertEqual(
47 response.data.decode(),
48 (
49 f'<h2>{self.x} {operations[operation]} {y} '
50 f'= {result}</h2>'
51 )
52 )
53
54 def test_website_handling_zero_division_error(self):
55 response = self.client.post(
56 '/calculate',
57 data={
58 'first_input': self.x,
59 'second_input': 0,
60 'operation': 'divide',
61 }
62 )
63 self.assertEqual(
64 response.data.decode(),
65 (
66 f'<h2>{self.x} / 0.0 = '
67 'brmph?! I cannot divide by 0. Try again...</h2>'
68 )
69 )
70
71
72# Exceptions seen
73# NameError
74# ModuleNotFoundError
75# AttributeError
76# AssertionError
77# jinja2.exceptions.TemplateNotFound
78# SyntaxError
open the project
I change directory to the
calculatorfolderthe terminal shows I am in the
calculatorfolder.../pumping_python/calculatorI make a new test file for the website
touch tests/test_calculator_website.pyI add Flask to the
requirements.txtfileecho "flask" >> requirements.txtFlask is a Python library that is used for making websites, it is not part of The Python Standard Library
I use uv to install pytest-watcher with the requirements file
the terminal shows that it installed the Python packages
I use
pytest-watcherto run the testsuv run pytest-watcher . --now --patterns "**/*.py"the terminal is my friend, and shows
rootdir: .../pumping_python/calculator configfile: pyproject.toml collected 5 items tests/test_calculator.py ..... [100%] ======================== 5 passed in X.YZs =========================
test_home_page
RED: make it fail
I open
test_calculator_website.pyfrom thetestsfolderI add a test to
test_calculator_website.py1import unittest 2 3 4class TestCalculatorWebsite(unittest.TestCase): 5 6 def test_home_page(self): 7 client = src.website.app.test_client()the terminal is my friend, and shows NameError
- caption:
terminal
NameError: name ‘src’ is not defined
I add NameError to the list of Exceptions seen
GREEN: make it pass
I add an import statement for the
websitemodule1import src.website 2import unittestthe terminal is my friend, and shows ModuleNotFoundError
I add ModuleNotFoundError to the list of Exceptions seen
then I add
website.pyto thesrcfolder and the terminal is my friend, and shows AttributeErrorI add AttributeError to the list of Exceptions seen
I make the Flask app in
website.py1import flask 2 3 4app = flask.Flask(__name__)the test passes.
REFACTOR: make it better
I add an assertion to test_home_page in
test_calculator_website.pythe terminal is my friend, and shows AssertionError
I add AssertionError to the list of Exceptions seen
I change the expectation in the assertion
the test passes.
client = src.website.app.test_client()points the nameclientto the Flask app inwebsite.pyresponse = client.get('/')points the nameresponseto the result of the call to thegetmethod of the client objectthe
getmethod calls the GET request method which is an HTTP request method to get information from a serverclient.get('/')returns a response object'/'is short for root or home in this case, the homepage of the website I am making also known asindex.htmlresponse.status_codegets thestatus_codeattribute or the response objectthe above can also be written as
src.website.app.test_client().get('/').status_code404is HTTP status code, it is short for 404 Not Found which means the page cannot be foundI want a
200HTTP status code, it is short for 200 OK and means the request was successful
I change the expectation in the assertion
the terminal is my friend, and shows AssertionError
I add a function for the homepage in
website.py1import flask 2 3 4app = flask.Flask(__name__) 5 6 7@app.route('/') 8def home(): 9 return flask.render_template('index.html')the terminal is my friend, and shows AssertionError
it also shows jinja2.exceptions.TemplateNotFound
jinja2.exceptions.TemplateNotFound: index.htmlI have to make a template file for
index.html@app.routeis a decorator function that routes the pages of the website to the function it wraps'/'is short for root or home in this case, the homepage of the website I am making also known asindex.html
I add jinja2.exceptions.TemplateNotFound to the list of Exceptions seen
I add a new folder to the
srcfolder namedtemplates, the terminal still shows the same ExceptionI add a new file in the
templatesfolder namedindex.html, the terminal still shows the same ExceptionI go back to
test_calculator_website.pythen use ctrl+s on the keyboard to save the file which makes pytest-watcher run the tests again, and the test passes.
how to view the website
I want to see what I just made. I open a new terminal, then use uv to run the Flask server
the terminal is my friend, and shows
* Serving Flask app 'src/website' * Debug mode: on WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Running on http://127.0.0.1:5000 Press CTRL+C to quit * Restarting with watchdog (inotify) * Debugger is active! * Debugger PIN: ABC-DEF-GHIit might also show a dialog box like this, and I click on
Open in Browser
or I use ctrl/option on the keyboard and click on
http://127.0.0.1:5000with the mouse to open the browser and it shows an empty page. Success!I add another assertion for text from the website to test_home_page in
test_calculator_website.pythe terminal is my friend, and shows AssertionError
there is nothing in
src/templates/index.htmlb''is the empty bytes objectbytes objects are like strings , they have a
bbefore the quotes, for exampleb'single quote bytes' b'''triple single quote bytes''' b"double quote bytes" b"""triple double quote bytes"""
I open
index.htmlfrom thetemplatesfolder, then add some HTML1<h1>Calculator</h1>the terminal still shows AssertionError because pytest-watcher only checks my Python files, it does not run the tests when I change other files
<></>are called tags, they are enclosures<h1>HEADING</h1>tells the computer to makeHEADINGa heading
I go back to
test_calculator_website.pyand use ctrl+s on the keyboard to run the test, the terminal is my friend, and shows AssertionErrorI make the expectation a bytes object
the test passes.
I go back to the browser and click
refresh, it showsCalculator
Yes! I know how to make a website with Python!!
test_calculations
RED: make it fail
I add a new test for doing calculations with the website
7 def test_home_page(self):
8 client = src.website.app.test_client()
9 response = client.get('/')
10 self.assertEqual(response.status_code, 200)
11 self.assertEqual(
12 response.data.decode(),
13 '<h1>Calculator</h1>'
14 )
15
16 def test_calculation(self):
17 client = src.website.app.test_client()
18 response = client.post(
19 '/calculate',
20 data={
21 'first_input': 0,
22 'second_input': 1,
23 }
24 )
25 self.assertEqual(response.status_code, 200)
26
27
28 # Exceptions seen
the terminal is my friend, and shows AssertionError
this is like AttributeError, the address for calculate does not exist yet.
client.postcalls thepostmethodwhich calls the POST request method, an HTTP request method that sends information to a server. I am using it to test sending numbers to the website to do a calculation
the
postmethod is called with 2 inputs in this case'/calculate'- the path to the function inwebsite.pydata- a dictionary with the inputs I want the function to process
GREEN: make it pass
I add a new function to
website.py@app.routeis a decorator function that routes the pages of the website to the function it wraps'/calculate'is the route I want to point to thecalculatefunction['POST']is a list of HTTP request methods that I can send, in this case I am using the POST request method to send information to the serverflask.request.form.get(NAME)uses the get method to get the value of theNAMEkey from the dictionary when the user makes a request<h2>SMALLER HEADING</h2>tells the computer to makeSMALLER HEADINGa heading that is smaller thanh1headings
the terminal is my friend, and shows NameError
- caption:
terminal
NameError: name ‘calculator’ is not defined. Did you mean: ‘calculate’?
I add an import statement for the
calculatormodule at the top of the file1import calculator 2import flaskthe terminal is my friend, and shows ModuleNotFoundError
because the test cannot find the
calculator.pymoduleI change the import statement
1import src.calculator 2import flaskthe test passes and the terminal for the website shows ModuleNotFoundError
this is a problem
website.pyis in thesrcfolder withcalculator.pysoimport src.calculatorwill not work for the websitetest_calculator_website.pyis in thetestsfolder soimport calculatorwill not work for the tests
I need a way that allows both the tests and website to work
I change the import statement back
1import calculator 2import flaskthe terminal is my friend, and shows ModuleNotFoundError
I add an import statement for the sys module, it is part of The Python Standard Library
1import sys 2 3import calculator 4import flaskI can use sys to get variables that the computer uses without going to the terminal
I add another import statement
1import pathlib 2import sys 3 4import calculator 5import flaskthe pathlib module is also part of The Python Standard Library
I can use it to get paths(addresses) for files and folders on the computer without going to the terminal
I use pathlib to add the path for
calculator.pyto the system path which is a list of strings where Python looks for modules when I write an import statement1import pathlib 2import sys 3sys.path.insert( 4 0, str(pathlib.Path(__file__).resolve().parent) 5) 6 7import calculator 8import flaskthe test passes and the terminal for the browser shows no errors
the path to
calculator.pyis now correct forwebsite.pyandtest_calculator.pysys.path.insertuses the insert method of lists to place thesrcfolder as the first item in the list for Python to look for modulespathlib.Path(__file__).resolve().parentreturns the parent of the current file -srcin this case__file__is a variable with the name of the filewebsite.pyin this casethe route to
/calculatenow exists
REFACTOR: make it better
I add an assertion to make sure I get the right result back in
test_calculator_website.pythe terminal is my friend, and shows AssertionError
Ah! The calculator only works with numbers. The numbers I sent as values in the test
0and1are getting converted to something the calculator does not likeI change
first_inputto a float inwebsite.pyI change
second_inputto a floatthe terminal is my friend, and shows AssertionError
I copy the result from the terminal and paste it in
test_calculator_website.pythe test passes.
I want to use random numbers in the test. I add an import statement for the
test_calculatormodule1import src.website 2import tests.test_calculator 3import unittestI point a variable to the result of a call to the
a_random_numberfunction oftest_calculatorI use the new variable as the first input
the terminal is my friend, and shows AssertionError
AssertionError: b'<h2>ABC.DEFGHIJKLMNOP + 1.0 = ABQ.DEFGHIJKLMNOP</h2>' != b'<h2>0.0 + 1.0 = 1.0</h2>'good, the input gets to the website
I try an `f-string`_ so I can use the variable in the assertion
the terminal is my friend, and shows SyntaxError
I cannot make a bytes object an `f-string`_
I add SyntaxError to the list of Exceptions seen
how to change a bytes object to a string
I change the bytes object to a string with bytes.decode
the terminal is my friend, and shows AssertionError
AssertionError: '<h2>RS.TUVWXYZABCDEFG + 1.0 = RH.TUVWXYZABCDEFG</h2>' != '<h2>0.0 + 1.0 = 1.0</h2>'response.data.decode()returns the result of calling the decode method of thedataattribute of theresponseobjectthe decode method is part of the bytes data type, it converts bytes to strings
I add the variable to the expectation
the test passes.
I add another variable
I use the variable for the second input
the terminal is my friend, and shows AssertionError
I add
yto the `f-string`_ in the expectationthe test passes.
I remove the comments
the test is still green.
I want to test the other operations. I add a dictionary for the operations
I add a for loop to the test
I add a key to the
datadictionaryI add a variable for the calculator function
I add another variable for the expected result
I change the expectation in the assertion to use the new variables
the terminal is my friend, and shows AssertionError
AssertionError: '<h2>YZA.BCDEFGHIJKLMNO + PQR.STUVWXYZABCDEFG = HIJ.KLMNOPQRSTUVWXY</h2>' != '<h2>YZA.BCDEFGHIJKLMNO * PQR.STUVWXYZABCDEFG = ZABCD.EFGHIJKLMNO</h2>'the subtest for addition passes
the operation symbols for the other 3 functions and their results changed
I add a variable for value the test passes for the operation
the test still shows AssertionError for the 3 sub tests
I add a dictionary for the operations
I use the
__getattribute__method for the resultI change the return statement
the test passes.
I remove the commented lines
the test is still green.
I remove the comments from test_calculations in
test_calculator_website.py
how to make a form
HTML Forms are the most popular thing we see with websites, we use them when we sign in or put any information on a website. I can add a form to the website for users to do calculations since the route now exists.
RED: make it fail
I add more HTML to
index.htmlin thetemplatesfolder in thesrcfolder1 <h1>Calculator</h1> 2 <form method="post" action="/calculate"> 3 </form>method="post"means the form will use the POST request methodaction="/calculate"means the form will send the data to thecalculatefunction inwebsite.py
I go to the website and click refresh, there is no change
I click on
test_calculator_website.pyand use ctrl+s on the keyboard to run the tests again, the terminal is my friend, and shows AssertionErrorAssertionError: b'<h1>Calculator</h1>\n<form method="post" action="/calculate">\n</form>' != b'<h1>Calculator</h1>'the change made test_home_page fail because there is now more HTML
GREEN: make it pass
I change the assertion to look for the title and not the entire page
8 def test_home_page(self):
9 client = src.website.app.test_client()
10 response = client.get('/')
11 self.assertEqual(response.status_code, 200)
12 self.assertIn(
13 b'<h1>Calculator</h1>',
14 response.data
15 )
16
17 def test_calculations(self):
the test passes because the assertIn method of the unittest.TestCase class checks if the thing on the left is in the object on the right
REFACTOR: make it better
I add more HTML to
index.htmlin thetemplatesfolder in thesrcfolder2<form method="post" action="/calculate"> 3 <input type="number" name="first_input" required> 4</form>I go to the browser and click refresh to see the change, the website has a place where I can put numbers or use the up and down arrows to change the numbers
I use ctrl+s on the keyboard in
test_calculator_website.pyto run the tests, still green.I add another input for the second number in
index.html2<form method="post" action="/calculate"> 3 <input type="number" name="first_input" required> 4 <input type="number" name="second_input" required> 5</form>I go to the browser and click refresh to see the change, the website now has 2 places for me to put numbers
I use ctrl+s on the keyboard in
test_calculator_website.pyto run the tests, greenI add options for the operation in
index.html2<form method="post" action="/calculate"> 3 <input type="number" name="first_input" required> 4 <input type="number" name="second_input" required> 5 <select name="operation"> 6 <option value="add">+</option> 7 </select> 8</form>I go to the browser and click refresh to see the change, the website now has a place for me to choose the operation, even though
+is the only option
I use ctrl+s on the keyboard in
website.pyto run the tests, they are still green.I want the operation to show up between the two numbers, I change the order in
index.html2<form method="post" action="/calculate"> 3 <input type="number" name="first_input" required> 4 <select name="operation"> 5 <option value="add">+</option> 6 </select> 7 <input type="number" name="second_input" required> 8</form>I go to the browser and click refresh to see the change, the operation is now between the two numbers
I use ctrl+s on the keyboard in
website.pyto run the tests. GreenI add the other operations to
index.html2<form method="post" action="/calculate"> 3 <input type="number" name="first_input" required> 4 <select name="operation"> 5 <option value="add">+</option> 6 <option value="subtract">-</option> 7 <option value="divide">/</option> 8 <option value="multiply">*</option> 9 </select> 10 <input type="number" name="second_input" required> 11</form>the browser shows all the options when I click refresh
I add a button to the form so the user can submit the numbers and operation for a calculation
1<h1>Calculator</h1> 2<form method="post" action="/calculate"> 3 <input type="number" name="first_input" required> 4 <select name="operation"> 5 <option value="add">+</option> 6 <option value="subtract">-</option> 7 <option value="divide">/</option> 8 <option value="multiply">*</option> 9 </select> 10 <input type="number" name="second_input" required> 11 <button type="submit">calculate</button> 12</form>I go to the browser and click refresh to see the change
I enter
10000as the first number and20000as the second number, with*as the operation
I click
calculateand the browser shows
ugly and it works
fix handling ZeroDivisionError in division
I want to make sure the division function returns a message when the second number is 0
RED: make it fail
I add a new test
17 def test_calculations(self):
18 x = tests.test_calculator.a_random_number()
19 y = tests.test_calculator.a_random_number()
20
21 operations = {
22 'add': '+',
23 'subtract': '-',
24 'divide': '/',
25 'multiply': '*',
26 }
27
28 client = src.website.app.test_client()
29
30 for operation in operations:
31 with self.subTest(operation=operation):
32 response = client.post(
33 '/calculate',
34 data={
35 'first_input': x,
36 'second_input': y,
37 'operation': operation,
38 }
39 )
40 self.assertEqual(response.status_code, 200)
41
42 function = src.calculator.__getattribute__(
43 operation
44 )
45 result = function(x, y)
46 self.assertEqual(
47 response.data.decode(),
48 (
49 f'<h2>{x} {operations[operation]} {y} '
50 f'= {result}</h2>'
51 )
52 )
53
54 def test_website_handling_zero_division_error(self):
55 x = tests.test_calculator.a_random_number()
56 client = src.website.app.test_client()
57
58 response = client.post(
59 '/calculate',
60 data={
61 'first_input': x,
62 'second_input': 0,
63 'operation': 'divide',
64 }
65 )
66 self.assertEqual(
67 response.data.decode(),
68 'brmph?! I cannot divide by 0. Try again...'
69 )
70
71
72# Exceptions seen
the terminal is my friend, and shows AssertionError in short test summary info
AssertionError: '<!doctype html>\n<html lang=en>\n<title>5[225 chars]p>\n' != 'brmph?! I cannot divide by 0.
and in the traceback it shows the AssertionError was caused by ZeroDivisionError
good
GREEN: make it pass
I open
calculator/__init__.pyfrom thesrcfolderI add an exception handler to the divide function in
calculator.pythe terminal is my friend, and shows AssertionError
AssertionError: '<h2>PQ.RSTUVWXYZABCDEF / 0.0 = brmph?! I cannot divide by 0. Try again...</h2>' != 'brmph?! I cannot divide by 0. Try again...'okay. It returns the right error message
I change the expectation of the assertion in
test_calculator_website.pythe test passes.
REFACTOR: make it better
I made the same client in each test. I add an object attribute for it in the `setUp method`_
I use the new object attribute in test_home_page
the test is still green.
I use it directly in the response
still green.
I remove the
clientvariable and the commented linegreen.
I use the object attribute in test_calculations
still green.
I remove the commented line and the
clientvariablethe test is still green.
I use the object attribute in test_website_handling_zero_division_error
still green.
I remove the commented line and
clientvariablegreen.
I add object attributes for the random numbers to the `setUp method`_
I use it in test_calculations
still green.
I use the
Rename Symbolto changextoself.xthe test is still green.
I remove the commented line and
self.x = self.xI use the
Rename Symbolfeature to changextoself.xin test_website_handling_zero_division_errorstill green.
I remove
self.x = tests.test_calculator.a_random_number()
test_calculator_sends_message_when_inputs_are_not_numbers
time to fix the problem with the second input in test_calculator_sends_message_when_input_is_not_a_number
RED: make it fail
GREEN: make it pass
I add a condition to the if statement in the
check_inputdecorator function incalculator.py1def check_input(function): 2 def wrapper(first_input, second_input): 3 if isinstance( 4 first_input, 5 (dict, set, list, tuple, str, bool) 6 ) or isinstance( 7 second_input, 8 (dict, set, list, tuple, str, bool) 9 ) or first_input is None: 10 return 'brmph?! Numbers only. Try again...' 11 return function(first_input, second_input) 12 return wrapperthe terminal is my friend, and shows TypeError
SUBFAILED(operation='add', bad_input=None) ... - TypeError: unsupported operand type(s) for +: 'float' and 'NoneType' SUBFAILED(operation='subtract', bad_input=None) ... - TypeError: unsupported operand type(s) for -: 'float' and 'NoneType' SUBFAILED(operation='multiply', bad_input=None) ... - TypeError: unsupported operand type(s) for *: 'float' and 'NoneType' SUBFAILED(operation='divide', bad_input=None) ... - TypeError: unsupported operand type(s) for /: 'float' and 'NoneType'I add a condition for when the second input is None to the if statement in
check_inputincalculator.py1def check_input(function): 2 def wrapper(first_input, second_input): 3 if isinstance( 4 first_input, 5 (dict, set, list, tuple, str, bool) 6 ) or isinstance( 7 second_input, 8 (dict, set, list, tuple, str, bool) 9 ) or first_input is None or second_input is None: 10 return 'brmph?! Numbers only. Try again...' 11 return function(first_input, second_input) 12 return wrapperthe test passes.
REFACTOR: make it better
I change the name of test_calculator_sends_message_when_input_is_not_a_number to test_calculator_sends_message_when_inputs_are_not_numbers in
test_calculator.pyI make a variable for the bad inputs, to remove repetition in
calculator.py1def check_input(function): 2 def wrapper(first_input, second_input): 3 bad_inputs = (dict, set, list, tuple, str, bool) 4 if isinstance(I use the new variable in the if statement
1def check_input(function): 2 def wrapper(first_input, second_input): 3 bad_inputs = (dict, set, list, tuple, str, bool) 4 if isinstance( 5 first_input, bad_inputs 6 # (dict, set, list, tuple, str, bool) 7 ) or isinstance( 8 second_input, bad_inputs 9 # (dict, set, list, tuple, str, bool) 10 ) or first_input is None or second_input is None: 11 return 'brmph?! Numbers only. Try again...' 12 return function(first_input, second_input) 13 return wrapperthe test is still green.
I add a for loop
still green.
I remove the other if statements
1def check_input(function): 2 def wrapper(first_input, second_input): 3 bad_inputs = (dict, set, list, tuple, str, bool) 4 for argument in (first_input, second_input): 5 if ( 6 isinstance(argument, bad_inputs) 7 or 8 argument is None 9 ): 10 return 'brmph?! Numbers only. Try again...' 11 return function(first_input, second_input) 12 return wrappergreen.
close the project
I close
test_calculator.py,test_calculator_website.py,calculator.py,website.pyandindex.htmlI click in the first terminal, then use q on the keyboard to leave the tests. The terminal goes back to the command line.
I change directory to the parent of
calculatorthe terminal is my friend, and shows
.../pumping_pythonI am back in the
pumping_pythondirectory.I click in the second terminal, then use ctrl/command+c on the keyboard to close the web server. The terminal goes back to the command line.
review
I ran tests to show that
I can can make a website with Flask
I can make routes, handle forms, and use the calculator program I made earlier
The website shows error message from the calculator when the user tries to divide by
0The website makes sure the user can only use numbers
My tests make sure that if someone uses the program and does not send numbers, they get a message
code from the chapter
what is next?
I know how to make a Python Test Driven Development environment manually.
how to make dictionaries with functions
what you can do with dictionaries
Would you like to see another way to make a website for the Calculator?
rate pumping python
If this has been a 7 star experience for you, please CLICK HERE to leave a 5 star review of pumping python. It helps other people get into the book too.