how to make a calculator 7
I want to test the calculator with a dictionary
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 def setUp(self):
13 self.random_first_number = a_random_number()
14 self.random_second_number = a_random_number()
15
16 x = self.random_first_number
17 y = self.random_second_number
18
19 try:
20 division_result = x / y
21 except ZeroDivisionError:
22 division_result = 'brmph?! I cannot divide by 0. Try again...'
23
24 self.arithmetic_tests = {
25 'addition': {
26 'function': src.calculator.add,
27 'expectation': x+y,
28 },
29 'subtraction': {
30 'function': src.calculator.subtract,
31 'expectation': x-y,
32 },
33 'division': {
34 'function': src.calculator.divide,
35 'expectation': division_result,
36 },
37 'multiplication': {
38 'function': src.calculator.multiply,
39 'expectation': x*y,
40 }
41 }
42
43 def test_calculator_w_list_items(self):
44 # two_numbers = [
45 # self.random_first_number,
46 # self.random_second_number
47 # ]
48 a_dictionary = {
49 'x': self.random_first_number,
50 'y': self.random_second_number
51 }
52 two_numbers = list(a_dictionary.values())
53
54 for operation in self.arithmetic_tests:
55 with self.subTest(operation=operation):
56 self.assertEqual(
57 self.arithmetic_tests[operation]['function'](
58 *two_numbers
59 ),
60 self.arithmetic_tests[operation]['expectation']
61 )
62
63 self.assertEqual(
64 src.calculator.add(
65 two_numbers[0],
66 two_numbers[1]
67 ),
68 self.random_first_number+self.random_second_number
69 )
70 self.assertEqual(
71 src.calculator.divide(
72 two_numbers[-2],
73 two_numbers[-1]
74 ),
75 self.random_first_number/self.random_second_number
76 )
77 self.assertEqual(
78 src.calculator.multiply(
79 two_numbers[1],
80 two_numbers[-1]
81 ),
82 self.random_second_number*self.random_second_number
83 )
84 self.assertEqual(
85 src.calculator.subtract(
86 two_numbers[-2],
87 two_numbers[0]
88 ),
89 self.random_first_number-self.random_first_number
90 )
91
92 def test_calculator_w_dictionary_items(self):
93 two_numbers = {
94 'first_input': self.random_first_number,
95 'second_input': self.random_second_number,
96 }
97
98 for operation in self.arithmetic_tests:
99 with self.subTest(operation=operation):
100 self.assertEqual(
101 self.arithmetic_tests[operation]['function'](
102 **two_numbers
103 ),
104 self.arithmetic_tests[operation]['expectation']
105 )
106
107 self.assertEqual(
108 src.calculator.add(
109 two_numbers['first_input'],
110 two_numbers['second_input']
111 ),
112 self.random_first_number+self.random_second_number
113 )
114 self.assertEqual(
115 src.calculator.divide(
116 two_numbers['first_input'],
117 two_numbers['second_input']
118 ),
119 self.random_first_number/self.random_second_number
120 )
121 self.assertEqual(
122 src.calculator.multiply(
123 two_numbers['second_input'],
124 two_numbers['second_input']
125 ),
126 self.random_second_number*self.random_second_number
127 )
128 self.assertEqual(
129 src.calculator.subtract(
130 two_numbers['first_input'],
131 two_numbers['first_input']
132 ),
133 self.random_first_number-self.random_first_number
134 )
135
136 def test_calculator_:ref:`raises<how to raise an Exception>`type_error_when_given_more_than_two_inputs(self):
137 for operation in self.arithmetic_tests:
138 with (
139 self.subTest(operation=operation),
140 self.assertRaises(TypeError),
141 ):
142 self.arithmetic_tests[operation]['function'](
143 [0, 1, 2]
144 )
145
146 def test_calculator_sends_message_when_input_is_not_a_number(self):
147 for bad_input in (
148 None,
149 True, False,
150 str(), 'text',
151 tuple(), (0, 1, 2, 'n'),
152 list(), [0, 1, 2, 'n'],
153 set(), {0, 1, 2, 'n'},
154 dict(), {'key': 'value'},
155 ):
156 for operation in self.arithmetic_tests:
157 with self.subTest(
158 operation=operation,
159 bad_input=bad_input,
160 ):
161 self.assertEqual(
162 self.arithmetic_tests[operation]['function'](
163 bad_input, a_random_number()
164 ),
165 'brmph?! Numbers only. Try again...'
166 )
167
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
180# Exceptions seen
181# AssertionError
182# NameError
183# AttributeError
184# TypeError
185# 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 7 items tests/test_calculator.py ....... [100%] ======================== 7 passed in X.YZs =========================I hold ctrl on the keyboard, then click on
tests/test_calculator.pyto open it
test_calculator_w_dictionary_items
RED: make it fail
I add a new test
58 def test_calculator_w_list_items(self):
59 two_numbers = [
60 self.random_first_number,
61 self.random_second_number
62 ]
63
64 self.assertEqual(
65 src.calculator.add(
66 two_numbers[0],
67 two_numbers[1]
68 ),
69 self.random_first_number+self.random_second_number
70 )
71 self.assertEqual(
72 src.calculator.divide(
73 two_numbers[-2],
74 two_numbers[-1]
75 ),
76 self.random_first_number/self.random_second_number
77 )
78 self.assertEqual(
79 src.calculator.multiply(
80 two_numbers[1],
81 two_numbers[-1]
82 ),
83 self.random_second_number*self.random_second_number
84 )
85 self.assertEqual(
86 src.calculator.subtract(
87 two_numbers[-2],
88 two_numbers[0]
89 ),
90 self.random_first_number-self.random_first_number
91 )
92 self.assertEqual(
93 src.calculator.add(*two_numbers),
94 self.random_first_number+self.random_second_number
95 )
96 self.assertEqual(
97 src.calculator.divide(*two_numbers),
98 self.random_first_number/self.random_second_number
99 )
100 self.assertEqual(
101 src.calculator.multiply(*two_numbers),
102 self.random_first_number*self.random_second_number
103 )
104 self.assertEqual(
105 src.calculator.subtract(*two_numbers),
106 self.random_first_number-self.random_second_number
107 )
108
109 def test_calculator_w_dictionary_items(self):
110 two_numbers = {
111 'x': self.random_first_number,
112 'y': self.random_second_number,
113 }
114
115 self.assertEqual(
116 src.calculator.add(
117 two_numbers['x'],
118 two_numbers['y']
119 ),
120 self.random_first_number+self.random_first_number
121 )
122
123 def test_calculator_:ref:`raises<how to raise an Exception>`type_error_when_given_more_than_two_inputs(self):
the terminal is my friend, and shows AssertionError
GREEN: make it pass
I change the expectation to the right calculation
115 self.assertEqual(
116 src.calculator.add(
117 two_numbers['x'],
118 two_numbers['y']
119 ),
120 self.random_first_number+self.random_second_number
121 )
the test passes. two_numbers is a dictionary with two key-value pairs
'x': self.random_first_number'y': self.random_second_number
this means
two_numbers['x']isself.random_first_numbertwo_numbers['y']isself.random_second_number
REFACTOR: make it better
I add an assertion for the divide function
the terminal is my friend, and shows AssertionError
I change the calculation to division
the test passes.
I add an assertion for the multiply function
the terminal is my friend, and shows AssertionError
I change the expectation to use the correct variables
the test passes.
I add an assertion for the subtract function
the terminal is my friend, and shows AssertionError
I change the expectation to match
the test passes.
test calculator with ** expression
RED: make it fail
I use ** like I did for the keyword arguments in test_unknown_number_of_arguments
136 self.assertEqual(
137 src.calculator.subtract(
138 two_numbers['x'],
139 two_numbers['x'],
140 ),
141 self.random_first_number-self.random_first_number
142 )
143 self.assertEqual(
144 src.calculator.add(**two_numbers),
145 self.random_first_number-self.random_second_number
146 )
the terminal is my friend, and shows TypeError
the names of the keys in the two_numbers dictionary must be the same as the names of the arguments the calculator functions receive - first_input and second_input not x and y
GREEN: make it pass
I change
xandytofirst_inputandsecond_inputin the dictionaryI add KeyError to the list of Exceptions seen
I remove the comments to put
xandyback as keys in the dictionarythe terminal is my friend, and shows TypeError
the same Exception I had before I added the keys to the dictionary
I change
two_numbers['x']totwo_numbers['first_input']to use the new keys in the assertions for additionthe same Exception I had before I added the keys to the dictionary
I comment out the assertion with
**two_numbersthe test is green again
I use
two_numbers['second_input']fortwo_numbers['y']the test is still green.
I remove the commented lines then make the same change for division
still green.
I do the same thing for the multiply function
green.
I do it in the assertions for the subtract function
still green.
I remove the
xandykeys from the dictionarythe tests are still green.
I remove the comments from the assertion with
**two_numbersthe terminal is my friend, and shows AssertionError
I change the calculation in the assertion to addition
the test passes.
REFACTOR: make it better
I add an assertion for the divide function
the terminal is my friend, and shows AssertionError
I change the calculation to use division
the test passes.
I add an assertion for the multiply function
the terminal is my friend, and shows AssertionError
I change the calculation to multiplication
the test passes.
I add the next assertion
the terminal is my friend, and shows AssertionError
I change the expectation
the test passes.
test calculator with dictionary values
RED: make it fail
I can use the values method of dictionaries to make a list to test the calculator in test_calculator_w_list_items
58 def test_calculator_w_list_items(self):
59 # two_numbers = [
60 # self.random_first_number,
61 # self.random_second_number
62 # ]
63 a_dictionary = {
64 'x': self.random_first_number,
65 'y': self.random_second_number
66 }
67
68 self.assertEqual(
69 src.calculator.add(
70 two_numbers[0],
71 two_numbers[1]
72 ),
73 self.random_first_number+self.random_second_number
74 )
GREEN: make it pass
I add a new variable and make a list from the values of the dictionary
58 def test_calculator_w_list_items(self):
59 # two_numbers = [
60 # self.random_first_number,
61 # self.random_second_number
62 # ]
63 a_dictionary = {
64 'x': self.random_first_number,
65 'y': self.random_second_number
66 }
67 two_numbers = list(a_dictionary.values())
68
69 self.assertEqual(
70 src.calculator.add(
71 two_numbers[0],
72 two_numbers[1]
73 ),
74 self.random_first_number+self.random_second_number
75 )
76 self.assertEqual(
77 src.calculator.divide(
78 two_numbers[-2],
79 two_numbers[-1]
80 ),
81 self.random_first_number/self.random_second_number
82 )
83 self.assertEqual(
84 src.calculator.multiply(
85 two_numbers[1],
86 two_numbers[-1]
87 ),
88 self.random_second_number*self.random_second_number
89 )
90 self.assertEqual(
91 src.calculator.subtract(
92 two_numbers[-2],
93 two_numbers[0]
94 ),
95 self.random_first_number-self.random_first_number
96 )
97 self.assertEqual(
98 src.calculator.add(*two_numbers),
99 self.random_first_number+self.random_second_number
100 )
101 self.assertEqual(
102 src.calculator.divide(*two_numbers),
103 self.random_first_number/self.random_second_number
104 )
105 self.assertEqual(
106 src.calculator.multiply(*two_numbers),
107 self.random_first_number*self.random_second_number
108 )
109 self.assertEqual(
110 src.calculator.subtract(*two_numbers),
111 self.random_first_number-self.random_second_number
112 )
113
114 def test_calculator_w_dictionary_items(self):
the test is green again
test_calculator_w_for_loops_and_dictionaries
I can use a dictionary with a for loop in test_calculator_sends_message_when_input_is_not_a_number
RED: make it fail
I add a new test with a dictionary
arithmeticis a dictionary with the names of the Arithmetic operations as keys, this meansarithmetic['addition'] is src.calculator.add arithmetic['subtract'] is src.calculator.subtract arithmetic['multiplication'] is src.calculator.multiply arithmetic['division'] is src.calculator.divideit also means that
arithmetic['addition'](x, y) is src.calculator.add(x, y) arithmetic['subtract'](x, y) is src.calculator.subtract(x, y) arithmetic['multiplication'](x, y) is src.calculator.multiply(x, y) arithmetic['division'](x, y) is src.calculator.divide(x, y)I add for loops with the subTest method
the terminal is my friend, and shows AssertionError
SUBFAILED(operation='addition', bad_input=None) ... - AssertionError: 'brmph?! Numbers only. Try again...' != 'BOOM!!!' SUBFAILED(operation='subtraction', bad_input=None) ... - AssertionError: 'brmph?! Numbers only. Try again...' != 'BOOM!!!' SUBFAILED(operation='multiplication', bad_input=None) ... - AssertionError: 'brmph?! Numbers only. Try again...' != 'BOOM!!!' SUBFAILED(operation='division', bad_input=None) ... - AssertionError: 'brmph?! Numbers only. Try again...' != 'BOOM!!!' ... SUBFAILED(operation='addition', bad_input={'key': 'value'}) ... - AssertionError: 'brmph?! Numbers only. Try again...' != 'BOOM!!!' SUBFAILED(operation='subtraction', bad_input={'key': 'value'}) ... - AssertionError: 'brmph?! Numbers only. Try again...' != 'BOOM!!!' SUBFAILED(operation='multiplication', bad_input={'key': 'value'}) ... - AssertionError: 'brmph?! Numbers only. Try again...' != 'BOOM!!!' SUBFAILED(operation='division', bad_input={'key': 'value'}) ... - AssertionError: 'brmph?! Numbers only. Try again...' != 'BOOM!!!' =================== 52 failed, 9 passed in R.STs ===================The second for loop goes over the keys of the dictionary and runs 4 tests for every bad input in the
bad_inputstuple. The two for loops together go every combination of operations and bad inputs(addition, None) (subtraction, None) (multiplication, None) (division, None) ... (addition, tuple()) (subtraction, tuple()) (multiplication, tuple()) (division, tuple()) ... (addition, {'key': 'value'}) (subtraction, {'key': 'value'}) (multiplication, {'key': 'value'}) (division, {'key': 'value'})this means I do not have to write 52 tests
GREEN: make it pass
I change the expectation to the error message
252 self.assertEqual(
253 arithmetic[operation](
254 bad_input, a_random_number()
255 ),
256 'brmph?! Numbers only. Try again...'
257 )
the test passes.
REFACTOR: make it better
I remove test_calculator_sends_message_when_input_is_not_a_number because test_calculator_sends_message_when_input_is_not_a_number covers all its assertions
I change the name of test_calculator_w_for_loops_and_dictionaries to test_calculator_sends_message_when_input_is_not_a_number to say what it does
this solution is not as easy to read as what was there before. Is there a better way?
test_calculator_functions
I want to use a dictionary to write one test that covers all the 4 arithmetic functions: addition, subtraction, division and multiplication and check their results are correct
RED: make it pass
I add a new test
the terminal is my friend, and shows AssertionError for the 4 arithmetic operations
SUBFAILED(operation='addition') ... - AssertionError: QRS.TUVWXYZABCDEF != 'BOOM!!!' SUBFAILED(operation='subtraction') ... - AssertionError: GHI.JKLMNOPQRSTUVWX != 'BOOM!!!' SUBFAILED(operation='division') ... - AssertionError: Y.ABCDEFGHIJKLMNOP != 'BOOM!!!' SUBFAILED(operation='multiplication') ... - AssertionError: QRSTUV.WXYZABCDEFG != 'BOOM!!!'how do I add the results?
GREEN: make it pass
I add a dictionary for the calculations of each operation
I use the new dictionary for the calculation in the assertion
the test passes.
This test goes through every operation in the arithmetic dictionary then calls the function that is its value with self.random_first_number and self.random_second_number as input, and checks if the result is the value for the operation key in the expectations dictionary. I think of it as
self.assertEqual(
arithmetic[operation](x, y),
expectations[operation]
)
operationcan beaddition,subtraction,multiplicationordivisionin this case
xisself.first_random_numberin this case
yisself.second_random_number
this means all these statements are the same
for addition
arithmetic['addition'](x, y) src.calculator.add(x, y) expectations['addition'] x + yfor subtraction
arithmetic['subtraction'](x, y) src.calculator.add(x, y) expectations['subtraction'] x - yfor multiplication
arithmetic['multiplication'](x, y) src.calculator.add(x, y) expectations['multiplication'] x * yfor division
arithmetic['division'](x, y) src.calculator.add(x, y) expectations['division'] x / y
REFACTOR: make it better
I can put the two dictionaries in this test together because they have the same keys
I add a new assertion in a for loop with the subTest method
the terminal is my friend, and shows AssertionError:
SUBFAILED(operation='addition') ... - AssertionError: HIJ.KLMNOPQRSTUVW != 'BOOM!!!' SUBFAILED(operation='subtraction') ... - AssertionError: XYZA.BCDEFGHIJKLMN != 'BOOM!!!' SUBFAILED(operation='division') ... - AssertionError: NO.PQRSTUVWXYZABCDE != 'BOOM!!!' SUBFAILED(operation='multiplication') ... - AssertionError: FGHIJKLM.NOPQRSTUVW != 'BOOM!!!'I change the expectation
the test passes.
I remove the other dictionaries and for loop
much better
I remove test_addition, test_subtraction and test_multiplication
I have to handle ZeroDivisionError in test_calculator_functions before I can remove test_division
I change
yto0in test_calculator_functionsthe terminal is my friend, and shows ZeroDivisionError
good
I add an exception handler to make a variable for the result of division
here is what the exception handler does
try: division_result = x / ytry to point
division_resultto the result of dividingxbyyif ZeroDivisionError is raised when trying to divide
xbyy, pointdivision_resultto'BOOM!!!'I use
division_resultin thearithmetic_testsdictionarythe terminal is my friend, and shows AssertionError
I change
'BOOM!!!'to the error messagethe test passes. Progress
I change
yback toself.random_second_numberthe test is still green.
I can put the arithmetic_tests dictionary from test_calculator_functions and the arithmetic dictionary from test_calculator_sends_message_when_input_is_not_a_number together because they have the same keys.
I add the variables from test_calculator_functions to the `setUp method`_
I use the new object attribute in the for loop in test_calculator_functions
the test is still green.
I use it in the assertion
still green.
I use it for the expectation
the test is still green.
I comment out the
arithmetic_testsdictionary in test_calculator_functionsstill green.
I comment out the exception handler
green.
I comment out the
xandyvariablesthe terminal is my friend, and shows NameError
SUBFAILED(operation='addition') ... - NameError: name 'x' is not defined SUBFAILED(operation='subtraction') ... - NameError: name 'x' is not defined SUBFAILED(operation='division') ... - NameError: name 'x' is not defined SUBFAILED(operation='multiplication') ... - NameError: name 'x' is not definedI undo the change
the test is green again
I change the inputs in the assertion
the test is still green.
I comment out
xandyagaingreen.
I remove the commented lines
the test is still green.
I use the new object attribute in the for loop in test_calculator_sends_message_when_input_is_not_a_number
still green.
I use it in the assertion
green.
I remove the commented lines and the
arithmeticvariable because it is no longer usedgreen around the roses
I add a for loop to use the
self.arithmetic_testsdictionary in test_calculator_:ref:`raises<how to raise an Exception>`type_error_when_given_more_than_two_inputsthe terminal is my friend, and shows TypeError for all 4 cases
SUBFAILED(operation='addition') ... - TypeError: src.calculator.numbers_only.<locals>.decorator() argument after ** must be a m... SUBFAILED(operation='subtraction') ... - TypeError: src.calculator.numbers_only.<locals>.decorator() argument after ** must be a m... SUBFAILED(operation='division') ... - TypeError: src.calculator.numbers_only.<locals>.decorator() argument after ** must be a m... SUBFAILED(operation='multiplication') ... - TypeError: src.calculator.numbers_only.<locals>.decorator() argument after ** must be a m...lovely! The test works
I add the `assertRaises method`_
the test passes.
I remove the other assertions
the test is still green.
I use the list for the variable in the assertion
still green.
I put the two with statements together
green.
I remove the commented lines and
not_two_numbersvariablestill green.
I add a for loop to use the
self.arithmetic_testsdictionary in test_calculator_w_dictionary_itemsthe terminal is my friend, and shows AssertionError for the 4 operations
SUBFAILED(operation='addition') ... - AssertionError: XYZ.ABCDEFGHIJKLM != 'BOOM!!!' SUBFAILED(operation='subtraction') ... - AssertionError: NOP.QRSTUVWXYZABC != 'BOOM!!!' SUBFAILED(operation='division') ... - AssertionError: D.EFGHIJKLMNOPQRS != 'BOOM!!!' SUBFAILED(operation='multiplication') ... - AssertionError: TUVWX.YZABCDEFGHI != 'BOOM!!!'I change the expectation
the test passes.
I remove all the assertions that have
**two_numbersthe test is still green.
I add a for loop to use the
self.arithmetic_testsdictionary in test_calculator_w_list_itemsthe terminal is my friend, and shows AssertionError for the 4 operations
SUBFAILED(operation='addition') ... - AssertionError: JK.LMNOPQRSTUVWXYZ != 'BOOM!!!' SUBFAILED(operation='subtraction') ... - AssertionError: ABCD.EFGHIJKLMNOPQ != 'BOOM!!!' SUBFAILED(operation='division') ... - AssertionError: R.STUVWXYZABCDEFGH != 'BOOM!!!' SUBFAILED(operation='multiplication') ... - AssertionError: IJKLMN.OPQRSTUVWXY != 'BOOM!!!'I change the expectation
the test passes.
I remove all the other assertions that have
*two_numbersthe test is still green.
I think it is time to take nap. That was a lot.
close the project
I close
test_calculator.pyI click in the terminal where the tests are running, then use q on the keyboard to leave the tests. The terminal goes back to the command line, the terminal is my friend, and shows
(.venv) .../pumping_python/calculatorI deactivate the `virtual environment`_
the terminal goes back to the command line,
(.venv)is no longer on the left side.../pumping_python/calculatorI change directory to the parent of
calculatorthe terminal is my friend, and shows
.../pumping_pythonI am back in the
pumping_pythondirectory.
review
I added these tests for the calculator program with dictionaries which made testing the program easier
code from the chapter
Do you want to see all the CODE I typed in this chapter?
what is next?
I know how to make a Python Test Driven Development environment manually.
what you can do with dictionaries
I edited makePythonTdd.sh or makePythonTdd.ps1 for the last few projects. I want to automate the process so that I can call the program and it does all the steps for me when I give it the name of the project.
Would you like to know how to make a Python Test Driven Development environment automatically with variables?
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.