how to make a calculator 8
I can use the __getattribute__ method that comes with every Python object in the calculator tests
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 @staticmethod
13 def get_division_result(x, y):
14 try:
15 return x / y
16 except ZeroDivisionError:
17 return 'brmph?! I cannot divide by 0. Try again...'
18
19 def setUp(self):
20 self.random_first_number = a_random_number()
21 self.random_second_number = a_random_number()
22
23 x = self.random_first_number
24 y = self.random_second_number
25
26 self.calculator_tests = {
27 'add': x+y,
28 'subtract': x-y,
29 'multiply': x*y,
30 'divide': self.get_division_result(x, y)
31 }
32
33 def test_calculator_w_list_items(self):
34 # two_numbers = [
35 # self.random_first_number,
36 # self.random_second_number
37 # ]
38 a_dictionary = {
39 'x': self.random_first_number,
40 'y': self.random_second_number
41 }
42 two_numbers = list(a_dictionary.values())
43
44 for operation in self.calculator_tests:
45 with self.subTest(operation=operation):
46 self.assertEqual(
47 src.calculator.__getattribute__(operation)(
48 *two_numbers
49 ),
50 self.calculator_tests[operation]
51 )
52
53 self.assertEqual(
54 src.calculator.add(
55 two_numbers[0],
56 two_numbers[1]
57 ),
58 self.random_first_number+self.random_second_number
59 )
60 self.assertEqual(
61 src.calculator.divide(
62 two_numbers[-2],
63 two_numbers[-1]
64 ),
65 self.random_first_number/self.random_second_number
66 )
67 self.assertEqual(
68 src.calculator.multiply(
69 two_numbers[1],
70 two_numbers[-1]
71 ),
72 self.random_second_number*self.random_second_number
73 )
74 self.assertEqual(
75 src.calculator.subtract(
76 two_numbers[-2],
77 two_numbers[0]
78 ),
79 self.random_first_number-self.random_first_number
80 )
81
82 def test_calculator_w_dictionary_items(self):
83 two_numbers = {
84 'first_input': self.random_first_number,
85 'second_input': self.random_second_number,
86 }
87
88 for operation in self.calculator_tests:
89 with self.subTest(operation=operation):
90 self.assertEqual(
91 src.calculator.__getattribute__(operation)(
92 **two_numbers
93 ),
94 self.calculator_tests[operation]
95 )
96
97 self.assertEqual(
98 src.calculator.add(
99 two_numbers['first_input'],
100 two_numbers['second_input']
101 ),
102 self.random_first_number+self.random_second_number
103 )
104 self.assertEqual(
105 src.calculator.divide(
106 two_numbers['first_input'],
107 two_numbers['second_input']
108 ),
109 self.random_first_number/self.random_second_number
110 )
111 self.assertEqual(
112 src.calculator.multiply(
113 two_numbers['second_input'],
114 two_numbers['second_input']
115 ),
116 self.random_second_number*self.random_second_number
117 )
118 self.assertEqual(
119 src.calculator.subtract(
120 two_numbers['first_input'],
121 two_numbers['first_input']
122 ),
123 self.random_first_number-self.random_first_number
124 )
125
126 def test_calculator_:ref:`raises<how to raise an Exception>`type_error_when_given_more_than_two_inputs(self):
127 for operation in self.calculator_tests:
128 with (
129 self.subTest(operation=operation),
130 self.assertRaises(TypeError),
131 ):
132 src.calculator.__getattribute__(operation)(
133 [0, 1, 2]
134 )
135
136 def test_calculator_sends_message_when_input_is_not_a_number(self):
137 for bad_input in (
138 None,
139 True, False,
140 str(), 'text',
141 tuple(), (0, 1, 2, 'n'),
142 list(), [0, 1, 2, 'n'],
143 set(), {0, 1, 2, 'n'},
144 dict(), {'key': 'value'},
145 ):
146 for operation in self.calculator_tests:
147 with self.subTest(
148 operation=operation,
149 bad_input=bad_input,
150 ):
151 self.assertEqual(
152 src.calculator.__getattribute__(operation)(
153 bad_input, a_random_number()
154 ),
155 'brmph?! Numbers only. Try again...'
156 )
157
158 def test_calculator_functions(self):
159 for operation in self.calculator_tests:
160 with self.subTest(operation=operation):
161 self.assertEqual(
162 src.calculator.__getattribute__(operation)(
163 self.random_first_number,
164 self.random_second_number
165 ),
166 self.calculator_tests[operation]
167 )
168
169
170# Exceptions seen
171# AssertionError
172# NameError
173# AttributeError
174# TypeError
175# KeyError
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
rootdir: .../pumping_python/calculator configfile: pyproject.toml collected 5 items tests/test_calculator.py ..... [100%] ======================== 5 passed in X.YZs =========================I hold ctrl on the keyboard, then click on
tests/test_calculator.pyto open it
test_calculator_w_getattribute
RED: make it fail
I add a new test
168 def test_calculator_functions(self):
169 for operation in self.arithmetic_tests:
170 with self.subTest(operation=operation):
171 self.assertEqual(
172 self.arithmetic_tests[operation]['function'](
173 self.random_first_number,
174 self.random_second_number
175 ),
176 self.arithmetic_tests[operation]['expectation']
177 )
178
179 def test_calculator_w_getattribute(self):
180 self.assertEqual(
181 src.calculator.__getattribute__('BOOM!!!'),
182 src.calculator.add
183 )
184
185
186# Exceptions seen
the terminal is my friend, and shows AttributeError
__getattribute__is a method that takes a name and checks if the name is an attribute of the objectif the name is NOT an attribute it raises AttributeError
if the name is an attribute it returns the object it points to
src.calculator.__getattribute__('BOOM!!!')checks if thecalculator.pymodule in thesrcfolder has anything namedBOOM!!!
GREEN: make it pass
I change 'BOOM!!!' to 'add'
179 def test_calculator_w_getattribute(self):
180 self.assertEqual(
181 src.calculator.__getattribute__('add'),
182 src.calculator.add
183 )
the test passes because the add function is an attribute of src.calculator
REFACTOR: make it better
I add a call to the add function
the terminal is my friend, and shows AssertionError
AssertionError: <function numbers_only.<locals>.decorator at 0xffffa1234bc0> != DEF.GHIJKLMNOPQRSI have to call the add function after
__getattribute__returns itI add parentheses at the end of the line to make it a call
the test passes.
I add a variables and a dictionary
I use the dictionary to change the expectation of the assertion
the test is still green.
I use the variables for
self.random_first_numberandself.random_second_numberin the assertionstill green.
I remove the commented lines
green.
I add subtraction to the
calculator_testsdictionarythen I add an assertion
the terminal is my friend, and shows AssertionError
I change the expectation
the test passes.
I add multiplication to the
calculator_testsdictionarythen I add an assertion
the terminal is my friend, and shows AssertionError
I change the expectation
the test passes.
I add division to the
calculator_testsdictionarythen I add an assertion
the terminal is my friend, and shows AssertionError
I change the expectation
the test passes.
I add a for loop
the terminal is my friend, and shows AssertionError
SUBFAILED(operation='add') ... - AssertionError: FGH.IJKLMNOPQRSTU != 'BOOM!!!' SUBFAILED(operation='subtract') ... - AssertionError: VWX.YZABCDEFGHIJKL != 'BOOM!!!' SUBFAILED(operation='multiply') ... - AssertionError: MNOP.QRSTUVWXYZAB != 'BOOM!!!' SUBFAILED(operation='divide') ... - AssertionError: CD.EFGHIJKLMNOPQR != 'BOOM!!!'I change the expectation
the test passes.
I remove the other assertions
is this simpler than test_calculator_functions?
I add
calculator_teststo the `setUp method`_ to make it an object attributeI use the new object attribute in test_calculator_w_getattribute
the test is still green.
I use
self.calculator_testsin the for loopstill green.
I use it in the expectation of the assertion
green.
I use
self.random_first_numberforxandself.random_second_numberforyin the assertionstill green.
I remove the commented lines and the variables because they are no longer used
the test is still green.
I remove test_calculator_functions because test_calculator_w_getattribute has the same tests
the tests are still green.
I change the name of test_calculator_w_getattribute to test_calculator_functions
I use
self.calculator_testsin the for loop of test_calculator_sends_message_when_input_is_not_a_numberthe terminal is my friend, and shows KeyError for all 52 sub tests
I use the
__getattribute__method in the assertionthe test passes.
I remove the commented lines
I use
self.calculator_testsin the for loop of test_calculator_:ref:`raises<how to raise an Exception>`type_error_when_given_more_than_two_inputsthe terminal is my friend, and shows KeyError for all 4 sub tests
I use the
__getattribute__method in the assertionthe test passes.
I remove the commented lines
the test is still green.
I use
self.calculator_testsin the for loop of test_calculator_w_dictionary_itemsthe terminal is my friend, and shows KeyError for the 4 tests
I use the
__getattribute__method in the assertionthe terminal is my friend, and shows KeyError for the 4 sub tests
I use
self.calculator_testsin the expectation of the assertionthe test passes.
I remove the commented lines
I use
self.calculator_testsin the for loop of test_calculator_w_list_itemsthe terminal is my friend, and shows KeyError for the 4 sub tests
I use the
__getattribute__method in the assertionthe terminal is my friend, and shows KeyError for the sub tests
I use
self.calculator_testsin the expectation of the assertionthe test passes.
I remove the new commented lines
I comment out
self.arithmetic_testsin the `setUp method`_ to see if there are any tests that still use itthe tests are still green.
I remove the commented lines
I make a function for the division result because I can
I use the new function in
self.calculator_teststhe terminal is my friend, and shows TypeError
TypeError: TestCalculator.get_division_result() takes 2 positional arguments but 3 were givenI forgot to make
get_division_resulta staticmethod_ since it does not do anything with the rest of the objectI wrap
get_division_resultwith the `staticmethod decorator`_the test passes.
I remove the commented line and the exception handler from the `setUp method`_
all the tests are passing and I feel like magic
test calculator tests again
I want to write the solution that will make all the tests in test_calculator.py pass without looking at them
RED: make it fail
I close
test_calculator.pyI open
calculator.pyfrom thesrcfolderthen I delete everything in
calculator.py, the terminal is my friend, and shows 3 passing tests and AttributeError for 70 failing tests, I start with the last oneI add the name to
calculator.py1add
GREEN: make it pass
I point
addto None to define it1add = NoneI change it to a function
1def add(): 2 return NoneI add a name to the parentheses
1def add(x): 2 return NoneI add a second name to the parentheses
1def add(x, y): 2 return Nonethe terminal is my friend, and shows AssertionError
I change the return statement
1def add(x, y): 2 return x + ythe terminal shows AttributeError
I add a function
1def add(x, y): 2 return x + y 3 4 5def divide(x, y): 6 return x / ythe terminal is my friend, and shows AttributeError
I add a function
the terminal is my friend, and shows AttributeError
I add a function for it
I add a name to the divide function
I add a default value to make it a choice
I add
second_inputwith a default value to the functionthe test must be calling divide with positional arguments in some cases and with keyword arguments in others. My solution does not work, I remove
xandyfrom the parenthesesI change the names in the return statement
I use the
Rename Symbolfeature to change the names in the parenthesesI do the same thing to
ythe terminal is my friend, and shows TypeError
same problem, same solution
I change the names
I change the names in the add function
1def add(first_input, second_input): 2 return first_input + second_input
I add an if statement to the divide function
the terminal is my friend, and shows AssertionError
I change the return statement of the if statement
1def add(first_input, second_input): 2 if isinstance(first_input, dict): 3 return 'brmph?! Numbers only. Try again...' 4 return first_input + second_inputI add an if statement to the multiply function
the terminal is my friend, and shows AssertionError
I change the return statement of the if statement
the terminal is my friend, and shows TypeError
SUBFAILED(operation='subtract', bad_input={'key': 'value'}) ... - TypeError: unsupported operand type(s) for -: 'dict' and 'float'same problem, same solution
I add an if statement with the same message in the subtract function
I add the same if statement to the add function
1def add(first_input, second_input): 2 if isinstance(first_input, dict): 3 return 'brmph?! Numbers only. Try again...' 4 return first_input + second_input
I add set to the if statement in the divide function
I do the same thing to the if statement in the multiply function
I change the if statement in the subtract function
I add set to the if statement in the add function
1def add(first_input, second_input): 2 if isinstance(first_input, (dict, set)): 3 return 'brmph?! Numbers only. Try again...' 4 return first_input + second_input
I add list to the if statement of the divide function
the terminal is my friend, and shows TypeError
SUBFAILED(operation='multiply', bad_input=[0, 1, 2, 'n']) ... - TypeError: can't multiply sequence by non-int of type 'float'the error message is different and the function got
[0, 1, 2, 'n']as input, it looks I will have to do this for all the other operationsI add list to the if statement in the other functions
1def add(first_input, second_input): 2 if isinstance(first_input, (dict, set, list)): 3 return 'brmph?! Numbers only. Try again...' 4 return first_input + second_input 5 6 7def divide(first_input=None, second_input=None): 8 if isinstance(first_input, (dict, set, list)): 9 return 'brmph?! Numbers only. Try again...' 10 return first_input / second_input 11 12 13def multiply(first_input, second_input): 14 if isinstance(first_input, (dict, set, list)): 15 return 'brmph?! Numbers only. Try again...' 16 return first_input * second_input 17 18 19def subtract(first_input, second_input): 20 if isinstance(first_input, (dict, set, list)): 21 return 'brmph?! Numbers only. Try again...' 22 return first_input - second_inputthe terminal is my friend, and shows TypeError
SUBFAILED(operation='divide', bad_input=(0, 1, 2, 'n')) ... - TypeError: unsupported operand type(s) for /: 'tuple' and 'float'another data type, there has to be a better way
I add tuple to the isinstance built-in function in the if statement of the divide function
the terminal is my friend, and shows TypeError
SUBFAILED(operation='multiply', bad_input=(0, 1, 2, 'n')) ... - TypeError: can't multiply sequence by non-int of type 'float'same problem, same solution
I add tuple to the if statement of the other functions
I add str to the if statements of the 4 functions
1def add(first_input, second_input): 2 if isinstance(first_input, (dict, set, list, tuple, str)): 3 return 'brmph?! Numbers only. Try again...' 4 return first_input + second_input 5 6 7def divide(first_input=None, second_input=None): 8 if isinstance(first_input, (dict, set, list, tuple, str)): 9 return 'brmph?! Numbers only. Try again...' 10 return first_input / second_input 11 12 13def multiply(first_input, second_input): 14 if isinstance(first_input, (dict, set, list, tuple, str)): 15 return 'brmph?! Numbers only. Try again...' 16 return first_input * second_input 17 18 19def subtract(first_input, second_input): 20 if isinstance(first_input, (dict, set, list, tuple, str)): 21 return 'brmph?! Numbers only. Try again...' 22 return first_input - second_inputthe terminal is my friend, and shows AssertionError
SUBFAILED(operation='divide', bad_input=False) ... - AssertionError: 0.0 != 'brmph?! Numbers only. Try again...'the input is a boolean in this case
I use the bool built-in function to the if statements of the functions
1def add(first_input, second_input): 2 if isinstance( 3 first_input, 4 (dict, set, list, tuple, str, bool) 5 ): 6 return 'brmph?! Numbers only. Try again...' 7 return first_input + second_input 8 9 10def divide(first_input=None, second_input=None): 11 if isinstance( 12 first_input, 13 (dict, set, list, tuple, str, bool) 14 ): 15 return 'brmph?! Numbers only. Try again...' 16 return first_input / second_input 17 18 19def multiply(first_input, second_input): 20 if isinstance( 21 first_input, 22 (dict, set, list, tuple, str, bool) 23 ): 24 return 'brmph?! Numbers only. Try again...' 25 return first_input * second_input 26 27 28def subtract(first_input, second_input): 29 if isinstance( 30 first_input, 31 (dict, set, list, tuple, str, bool) 32 ): 33 return 'brmph?! Numbers only. Try again...' 34 return first_input - second_input
I add None to the call to the isinstance built-in function in the if statement of the divide function
the terminal is my friend, and shows TypeError
I cannot use None in the isinstance built-in function
I undo the change then add a new condition
the terminal is my friend, and shows TypeError
SUBFAILED(operation='multiply', bad_input=None) ... - TypeError: unsupported operand type(s) for *: 'NoneType' and 'float'same problem, same …
I add the new condition to the if statement of the other functions
1def add(first_input, second_input): 2 if isinstance( 3 first_input, 4 (dict, set, list, tuple, str, bool) 5 ) or first_input is None: 6 return 'brmph?! Numbers only. Try again...' 7 return first_input + second_input 8 9 10def divide(first_input=None, second_input=None): 11 if isinstance( 12 first_input, 13 (dict, set, list, tuple, str, bool) 14 ) or first_input is None: 15 return 'brmph?! Numbers only. Try again...' 16 return first_input / second_input 17 18 19def multiply(first_input, second_input): 20 if isinstance( 21 first_input, 22 (dict, set, list, tuple, str, bool) 23 ) or first_input is None: 24 return 'brmph?! Numbers only. Try again...' 25 return first_input * second_input 26 27 28def subtract(first_input, second_input): 29 if isinstance( 30 first_input, 31 (dict, set, list, tuple, str, bool) 32 ) or first_input is None: 33 return 'brmph?! Numbers only. Try again...' 34 return first_input - second_inputthe terminal is my friend, and shows AssertionError
I remove the default values from the divide function because it is the only one that is different from the others
the test passes. Time to play
REFACTOR: make it better
I add a decorator function
1def 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 first_input is None: 7 return 'brmph?! Numbers only. Try again...' 8 return function(first_input, second_input) 9 return wrapper 10 11 12def add(first_input, second_input):I use it to wrap the add function
the test is still green.
I remove the if statement
still green.
I do the same thing to the divide function
green.
I remove the if statement
the test is still green.
I make the same change to the other 2 functions
1def check_input(function): 2 def wrapper(first_input, second_input): 3 if ( 4 isinstance( 5 first_input, 6 (dict, set, list, tuple, str, bool) 7 ) or 8 first_input is None 9 ): 10 return 'brmph?! Numbers only. Try again...' 11 return function(first_input, second_input) 12 return wrapper 13 14 15@check_input 16def add(first_input, second_input): 17 return first_input + second_input 18 19 20@check_input 21def divide(first_input, second_input): 22 return first_input / second_input 23 24 25@check_input 26def multiply(first_input=None, second_input=None): 27 return first_input * second_input 28 29 30@check_input 31def subtract(first_input, second_input): 32 return first_input - second_inputstill green.
All the tests are passing, and there are problems
What happens when the functions receive a bad input as the second input or something that is not a dictionary, set, list, string or boolean? I need a better test
It looks like the test for how the calculator handles ZeroDivisionError never runs. I need to make that test better
I wonder what else I missed. I am still learning
close the project
I close
test_calculator.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
I used the
__getattribute__built-in function to make the calculator tests simpler.I rewrote the solution after rewriting the tests and found that
I did not add a test for bad second inputs
the test for handling ZeroDivisionError has a problem
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
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.