how to make a calculator 4
I want to use TypeError with exception handlers to make sure that the calculator program only works with numbers, like a Calculator in the real world.
preview
I have these tests by the end of the chapter
1import random
2import src.calculator
3import unittest
4
5
6def a_random_number():
7 return random.triangular(-1000.0, 1000.0)
8
9
10class TestCalculator(unittest.TestCase):
11
12 random_first_number = a_random_number()
13 random_second_number = a_random_number()
14
15 def test_addition(self):
16 self.assertEqual(
17 src.calculator.add(
18 self.random_first_number,
19 self.random_second_number
20 ),
21 self.random_first_number+self.random_second_number
22 )
23
24 def test_subtraction(self):
25 self.assertEqual(
26 src.calculator.subtract(
27 self.random_first_number,
28 self.random_second_number
29 ),
30 self.random_first_number-self.random_second_number
31 )
32
33 def test_multiplication(self):
34 self.assertEqual(
35 src.calculator.multiply(
36 self.random_first_number,
37 self.random_second_number
38 ),
39 self.random_first_number*self.random_second_number
40 )
41
42 def test_division(self):
43 try:
44 self.assertEqual(
45 src.calculator.divide(
46 self.random_first_number,
47 self.random_second_number
48 ),
49 self.random_first_number/self.random_second_number
50 )
51 except ZeroDivisionError:
52 self.assertEqual(
53 src.calculator.divide(self.random_first_number, 0),
54 'brmph?! I cannot divide by 0. Try again...'
55 )
56
57 def test_calculator_sends_message_when_input_is_not_a_number(self):
58 error_message = 'brmph?! Numbers only. Try again...'
59
60 self.assertEqual(
61 src.calculator.add(None, None),
62 error_message
63 )
64 self.assertEqual(
65 src.calculator.divide(None, None),
66 error_message
67 )
68 self.assertEqual(
69 src.calculator.multiply(None, None),
70 error_message
71 )
72 self.assertEqual(
73 src.calculator.subtract(None, None),
74 error_message
75 )
76 self.assertEqual(
77 src.calculator.add('1', '1'),
78 error_message
79 )
80 self.assertEqual(
81 src.calculator.divide('1', '1'),
82 error_message
83 )
84 self.assertEqual(
85 src.calculator.multiply('1', '1'),
86 error_message
87 )
88 self.assertEqual(
89 src.calculator.subtract('1', '1'),
90 error_message
91 )
92
93
94# Exceptions seen
95# AssertionError
96# NameError
97# AttributeError
98# TypeError
open the project
I change directory to the
calculatorfolderthe terminal shows I am in the
calculatorfolder.../pumping_python/calculatorI use
pytest-watcherto run the teststhe terminal is my friend, and shows
I hold ctrl on the keyboard, then click on
tests/test_calculator.pyto open it
test_calculator_:ref:`raises<how to raise an Exception>`type_error_w_none
RED: make it fail
I add a new failing test to show that the calculator raises TypeError when one of the inputs is None, just like in test_type_error_w_objects_that_do_not_mix
42 def test_division(self):
43 try:
44 self.assertEqual(
45 src.calculator.divide(
46 self.random_first_number,
47 self.random_second_number
48 ),
49 self.random_first_number/self.random_second_number
50 )
51 except ZeroDivisionError:
52 self.assertEqual(
53 src.calculator.divide(self.random_first_number, 0),
54 'brmph?! I cannot divide by 0. Try again...'
55 )
56
57 def test_calculator_:ref:`raises<how to raise an Exception>`type_error_w_none(self):
58 src.calculator.add(None, None)
59
60
61# Exceptions seen
GREEN: make it pass
I add assertRaises
57 def test_calculator_:ref:`raises<how to raise an Exception>`type_error_w_none(self):
58 with self.assertRaises(TypeError):
59 src.calculator.add(None, None)
the test passes.
REFACTOR: make it better
I add a failing line for division
I add assertRaises
the test passes.
I add another failing line, this time for multiplication
I add assertRaises
the test passes.
I add another one for subtraction
I add the `assertRaises method`_
the test passes.
The calculator raises TypeError when None is given as input.
What does it do if the input is a boolean, string, tuple, list, set or a dictionary?
test_calculator_:ref:`raises<how to raise an Exception>`type_error_w_strings
RED: make it fail
I add a new test with an assertion from test_assert_keyword, to test the add function with strings
64 with self.assertRaises(TypeError):
65 src.calculator.subtract(None, None)
66
67 def test_calculator_with_strings(self):
68 self.assertEqual(src.calculator.add('1', '1'), '2')
69
70
71# Exceptions seen
the terminal is my friend, and shows AssertionError
GREEN: make it pass
I change the expectation to match reality
67 def test_calculator_with_strings(self):
68 self.assertEqual(src.calculator.add('1', '1'), '11')
the test passes.
REFACTOR: make it better
I add an assertion for the divide function
I change assertEqual method to assertRaises
the test passes.
I try it with the multiply function
the terminal is my friend, and shows TypeError
TypeError: can't multiply sequence by non-int of type 'str'I add assertRaises
the test passes.
I try it with the subtract function
I add assertRaises
the test passes.
how to test if something is an instance of an object in a program
I want the add function to raise TypeError when it gets a string, the same way the other functions raise TypeError when one of the inputs is a string. I can use the `isinstance function`_ which is like the assertIsInstance method from when I tested None, it checks if one thing is an instance or child of an object
I change the assertEqual method to assertRaises in test_calculator_with_strings
the terminal is my friend, and shows AssertionError
I open
calculator/__init__.pyfrom thesrcfolderthen I add an if statement to the add function in
calculator.pythe test passes.
Note
the `isinstance function`_ like the assertIsInstance method checks if the first input it is given is an instance (child) of the object it is given as the second input. It is part of Python’s Built-in Functions
the if statement
if isinstance(first_input, str) or isinstance(second_input, str):is True ifthe statement is only False if
first_inputis NOT a string andsecond_inputis NOT a string.
This is Logical Disjunction from the Truth Table, which only returns False, if the first input is False and the second input is False
I change the name of the test to say what it does
test_calculator_sends_message_when_input_is_not_a_number
I want the calculator functions to send a message when it gets something that is not a number, not raise TypeError which causes the program to stop. I want the user to be able to try again with different input.
RED: make it fail
I change the assertRaises to assertEqual method for the add function in test_calculator_:ref:`raises<how to raise an Exception>`type_error_w_none
57 def test_calculator_:ref:`raises<how to raise an Exception>`type_error_w_none(self):
58 self.assertEqual(
59 src.calculator.add(None, None),
60 'brmph?! Numbers only. Try again...'
61 )
62 with self.assertRaises(TypeError):
63 src.calculator.divide(None, None)
64 with self.assertRaises(TypeError):
65 src.calculator.multiply(None, None)
66 with self.assertRaises(TypeError):
67 src.calculator.subtract(None, None)
GREEN: make it pass
I add an exception handler to the else clause of the add function in calculator.py
16def add(first_input, second_input):
17 if (
18 isinstance(first_input, str)
19 or
20 isinstance(second_input, str)
21 ):
22 raise TypeError
23 else:
24 try:
25 return first_input + second_input
26 except TypeError:
27 return 'brmph?! Numbers only. Try again...'
the test passes.
REFACTOR: make it better
I change the assertRaises to assertEqual method for the divide function
I add another except clause to the exception handler in the divide function in
calculator.pythe terminal is my friend, and shows AssertionError
my change made the assertion in test_calculator_:ref:`raises<how to raise an Exception>`type_error_w_strings fail
I undo the change, then add an if statement
the test passes.
I change the assertRaises to assertEqual method for the multiply function in test_calculator_:ref:`raises<how to raise an Exception>`type_error_w_none in
test_calculator.pyI add an if statement to the multiply function in
calculator.pythe test passes.
I change the assertRaises for the subtract function to assertEqual method in test_calculator_:ref:`raises<how to raise an Exception>`type_error_w_none in
test_calculator.pyI add an if statement to the subtract function in
calculator.py1def subtract(first_input, second_input): 2 if first_input is None or second_input is None: 3 return 'brmph?! Numbers only. Try again...' 4 return first_input - second_input 5 6 7def multiply(first_input, second_input):the test passes.
I add a variable
I use it to remove the repetition of the error message
the test is still green.
what is a decorator function?
3 of the functions in the calculator program have the same if statement
if first_input is None or second_input is None:
return 'brmph?! Numbers only. Try again...'
How can I remove this repetition? The only difference between the 3 functions is in what they do with the inputs
return first_input - second_input
return first_input * second_input
return first_input / second_input
I can use a decorator/wrapper function to remove the repetition from those 3 functions. It is a function that takes another function as input.
I add a decorator function to
calculator.py1def input_is_not_none(function): 2 def wrapper(first_input, second_input): 3 if first_input is None or second_input is None: 4 return 'brmph?! Numbers only. Try again...' 5 return function(first_input, second_input) 6 return wrapper 7 8 9def subtract(first_input, second_input):The
input_is_not_nonefunctiontakes a given function as input
uses logical disjunction to check the inputs
if the first input is None or the second input is None it returns an error message
if the two inputs are both NOT None it returns the result of calling the given function with the inputs
I use it with the subtract function
the tests are still green.
I remove the if statement from the subtract function
still green.
I use
input_is_not_nonewith the multiply functiongreen.
I remove the if statement from the multiply function
still green.
I wrap the divide function with
input_is_not_nonethe tests are still green.
I remove the if statement
1def input_is_not_none(function): 2 def wrapper(first_input, second_input): 3 if first_input is None or second_input is None: 4 return 'brmph?! Numbers only. Try again...' 5 return function(first_input, second_input) 6 return wrapper 7 8 9@input_is_not_none 10def subtract(first_input, second_input): 11 return first_input - second_input 12 13 14@input_is_not_none 15def multiply(first_input, second_input): 16 return first_input * second_input 17 18 19@input_is_not_none 20def divide(first_input, second_input): 21 try: 22 return first_input / second_input 23 except ZeroDivisionError: 24 return 'brmph?! I cannot divide by 0. Try again...' 25 26 27def add(first_input, second_input): 28 if ( 29 isinstance(first_input, str) 30 or 31 isinstance(second_input, str) 32 ): 33 return 'brmph?! Numbers only. Try again...' 34 else: 35 try: 36 return first_input + second_input 37 except TypeError: 38 return 'brmph?! Numbers only. Try again...'still green.
I change assertRaises to assertEqual method for the divide function in
test_calculator.pyI add another except clause to the divide function in
calculator.pythe test passes.
I change assertRaises to assertEqual method for the multiply function in test_calculator_:ref:`raises<how to raise an Exception>`type_error_w_strings in
test_calculator.pythe terminal is my friend, and shows TypeError
TypeError: can't multiply sequence by non-int of type 'str'I add an exception handler to the multiply function in
calculator.pythe test passes.
I change the assertRaises to assertEqual method for the subtract function in
test_calculator.pyI add an exception handler to the subtract function in
calculator.pythe test passes.
3 of the functions in the calculator program have the same exception handler
try:
something
except TypeError:
return 'brmph?! Numbers only. Try again...'
the divide function is different because it has another except clause
I can use a decorator/wrapper function to remove the repetition of the exception handler from the functions
I add a new decorator function to
calculator.py1def type_error_handler(function): 2 def handler(first_input, second_input): 3 try: 4 return function(first_input, second_input) 5 except TypeError: 6 return 'brmph?! Numbers only. Try again...' 7 return handler 8 9 10def input_is_not_none(function):The
type_error_handlerfunctiontakes a given function as input
tries to return the result of calling the given function with the inputs
if the call to the given function with the inputs raises TypeError it returns a message
I use it to wrap the subtract function
the tests are still green.
I remove the exception handler from the subtract function
still green.
I wrap the multiply function
green.
I remove the exception handler from the multiply function
still green.
I wrap the divide function
the test is still green.
I remove the second except clause
still green.
The two decorator functions both return the result of calling the given functions or an error message
return function(first_input, second_input) return 'brmph?! Numbers only. Try again...'I make a new decorator to do the work of
type_error_handlerandinput_is_not_none1def numbers_only(function): 2 def decorator(first_input, second_input): 3 error_message = 'brmph?! Numbers only. Try again...' 4 if first_input is None or second_input is None: 5 return error_message 6 else: 7 try: 8 return function(first_input, second_input) 9 except TypeError: 10 return error_message 11 return decorator 12 13 14def type_error_handler(function):The
numbers_onlyfunctiontakes a given function as input
makes a variable named
error_messagefor the error messageuses logical disjunction to check the inputs
if the first input is None or the second input is None it returns the error message
if the two inputs are both NOT None it tries to return the result of calling the given function with the inputs
if the call to the given function with the inputs raises TypeError it returns a message
I use
numbers_onlyto wrap the subtract functionthe tests are still green.
I remove the other wrappers from the subtract function
still green.
I wrap the multiply function
green.
I remove the other wrappers from the multiply function
still green.
I wrap the divide function
the tests are still green.
I remove the other wrappers from the divide function
still green.
I wrap the add function
green.
I remove the other wrappers from the add function
still green.
I remove
type_error_handlerandinput_is_not_nonebecause they are no longer used1def numbers_only(function): 2 def decorator(first_input, second_input): 3 error_message = 'brmph?! Numbers only. Try again...' 4 if first_input is None or second_input is None: 5 return error_message 6 else: 7 try: 8 return function(first_input, second_input) 9 except TypeError: 10 return error_message 11 return decorator 12 13 14@numbers_only 15def subtract(first_input, second_input):all tests are still green.
I add a variable to test_calculator_:ref:`raises<how to raise an Exception>`type_error_w_strings
I use the variable to remove the repetition of the error message
still green.
I remove the name of test_calculator_:ref:`raises<how to raise an Exception>`type_error_w_strings to make its assertions part of test_calculator_:ref:`raises<how to raise an Exception>`type_error_w_none
I remove the repetition of the
error_messagevariableI change the name from test_calculator_:ref:`raises<how to raise an Exception>`type_error_w_none to
test_calculator_sends_message_when_input_is_not_a_numberto make it clearerthe tests are still green. All these assertions look the same, they check that the calculator functions return an error message if they get input that is NOT a number
self.assertEqual( src.calculator.function(NOT_A_NUMBER, ALSO_NOT_A_NUMBER), error_message )there has to be a better way to test the calculator with inputs that are NOT numbers, especially since I want to test the other data types - booleans, tuples, lists and dictionaries. I do not think I am ready to write 4 assertions for each one.
I can make a function for the condition in the if statement in the add function in
calculator.pythen use
is_stringin the add functionthe test is still green. This removes the repetition of
strin the call to the `isinstance function`_isinstance(first_input, str) isinstance(second_input, str)it also adds 2 lines of code to remove 6 characters. WOW!
I undo the change
I can make a function for the if statement in the add function
then use
one_input_is_a_stringin the add functionthe test is still green. the
one_input_is_a_stringfunctionalso uses logical disjunction like the if statement in
numbers_onlymakes it easier to change the condition later without touching the add function
still adds 2 lines of code
enough experiments for now. I undo the change because I do not need it
1def numbers_only(function): 2 def decorator(first_input, second_input): 3 error_message = 'brmph?! Numbers only. Try again...' 4 if first_input is None or second_input is None: 5 return error_message 6 else: 7 try: 8 return function(first_input, second_input) 9 except TypeError: 10 return error_message 11 return decorator 12 13 14@numbers_only 15def subtract(first_input, second_input): 16 return first_input - second_input 17 18 19@numbers_only 20def multiply(first_input, second_input): 21 return first_input * second_input 22 23 24@numbers_only 25def divide(first_input, second_input): 26 try: 27 return first_input / second_input 28 except ZeroDivisionError: 29 return 'brmph?! I cannot divide by 0. Try again...' 30 31 32@numbers_only 33def add(first_input, second_input): 34 if ( 35 isinstance(first_input, str) 36 or 37 isinstance(second_input, str) 38 ): 39 return 'brmph?! Numbers only. Try again...' 40 else: 41 return first_input + second_inputand all the tests are still passing. The world is my oyster!
close the project
I close
test_calculator.pyandcalculator.pyI click in the terminal where the tests are running
I 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.
review
The calculator program can take 2 inputs and check if they are both numbers, then add, subtract, multiply or divide them
Even though the program says it only works with numbers, I did not add tests for tuples, lists, sets, and dictionaries, though they are touched in test_type_error_w_objects_that_do_not_mix, Do you want to add them or do we already have enough tests to know what would happen?
code from the chapter
what is next?
I know how to make a Python Test Driven Development environment manually.
how to make a Python Test Driven Development environment automatically
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.