how to make a calculator 5

I want to practice using lists with the calculator project


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        a_list = [0, 1, 2, 3]
 94
 95        self.assertEqual(
 96            src.calculator.add(a_list, 0),
 97            error_message
 98        )
 99        self.assertEqual(
100            src.calculator.divide(a_list, 1),
101            error_message
102        )
103        self.assertEqual(
104            src.calculator.multiply(a_list, 2),
105            error_message
106        )
107        self.assertEqual(
108            src.calculator.subtract(a_list, 3),
109            error_message
110        )
111
112    def test_calculator_w_list_items(self):
113        two_numbers = [
114            self.random_first_number,
115            self.random_second_number
116        ]
117
118        self.assertEqual(
119            src.calculator.add(
120                two_numbers[0],
121                two_numbers[1]
122            ),
123            self.random_first_number+self.random_second_number
124        )
125        self.assertEqual(
126            src.calculator.divide(
127                two_numbers[-2],
128                two_numbers[-1]
129            ),
130            self.random_first_number/self.random_second_number
131        )
132        self.assertEqual(
133            src.calculator.multiply(
134                two_numbers[1],
135                two_numbers[-1]
136            ),
137            self.random_second_number*self.random_second_number
138        )
139        self.assertEqual(
140            src.calculator.subtract(
141                two_numbers[-2],
142                two_numbers[0]
143            ),
144            self.random_first_number-self.random_first_number
145        )
146        self.assertEqual(
147            src.calculator.add(*two_numbers),
148            self.random_first_number+self.random_second_number
149        )
150        self.assertEqual(
151            src.calculator.divide(*two_numbers),
152            self.random_first_number/self.random_second_number
153        )
154        self.assertEqual(
155            src.calculator.multiply(*two_numbers),
156            self.random_first_number*self.random_second_number
157        )
158        self.assertEqual(
159            src.calculator.subtract(*two_numbers),
160            self.random_first_number-self.random_second_number
161        )
162
163    def test_calculator_:ref:`raises<how to raise an Exception>`type_error_when_given_more_than_two_inputs(self):
164        not_two_numbers = [0, 1, 2]
165
166        with self.assertRaises(TypeError):
167            src.calculator.add(*not_two_numbers)
168        with self.assertRaises(TypeError):
169            src.calculator.divide(*not_two_numbers)
170        with self.assertRaises(TypeError):
171            src.calculator.multiply(*not_two_numbers)
172        with self.assertRaises(TypeError):
173            src.calculator.subtract(*not_two_numbers)
174
175
176# Exceptions seen
177# AssertionError
178# NameError
179# AttributeError
180# TypeError

open the project

  • I change directory to the calculator folder

    terminal
    cd calculator
    

    the terminal shows I am in the calculator folder

    .../pumping_python/calculator
    
  • I use pytest-watcher to run the tests

    terminal
    uv 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 =========================
    
  • I hold ctrl on the keyboard, then click on tests/test_calculator.py to open it


test_calculator_sends_message_when_input_is_a_list

I want to see what happens when I send a list as input to the calculator program, will it send a message or raise TypeError?


RED: make it fail


I add a test to see what happens when I send a list as input

 88        self.assertEqual(
 89            src.calculator.subtract('1', '1'),
 90            error_message
 91        )
 92
 93    def test_calculator_sends_message_when_input_is_a_list(self):
 94        a_list = [0, 1, 2, 3]
 95
 96        self.assertEqual(
 97            src.calculator.add(a_list, 0),
 98            'BOOM!!!'
 99        )
100
101
102# Exceptions seen

the terminal is my friend, and shows AssertionError

terminal
AssertionError: 'brmph?! Numbers only. Try again...' != 'BOOM!!!'

GREEN: make it pass


I change the expectation to match

96        self.assertEqual(
97            src.calculator.add(a_list, 0),
98            'brmph?! Numbers only. Try again...'
99        )

the test passes.


REFACTOR: make it better



how to multiply a list


test_calculator_w_list_items

I can use a list to test the calculator functions as long as its items are numbers


RED: make it fail


I add a new test to use the index of the items in the list to test the calculator

107          self.assertEqual(
108              src.calculator.subtract(a_list, 3),
109              error_message
110          )
111
112      def test_calculator_w_list_items(self):
113          two_numbers = [
114              self.random_first_number,
115              self.random_second_number
116          ]
117
118          self.assertEqual(
119              src.calculator.add(
120                  two_numbers[0],
121                  two_numbers[1]
122              ),
123              self.random_first_number-self.random_second_number
124          )
125
126
127  # Exceptions seen

the terminal is my friend, and shows AssertionError

terminal
AssertionError: ABC.DEFGHIJKLMNOPQ != RST.UVWXYZABCDEFG

GREEN: make it pass


I change the expectation to the right calculation

118          self.assertEqual(
119              src.calculator.add(
120                  two_numbers[0],
121                  two_numbers[1]
122              ),
123              self.random_first_number+self.random_second_number
124          )

the test passes. two_numbers is a list with two items - self.random_first_number and self.random_second_number, this means

  • two_numbers[0] is self.random_first_number

  • two_numbers[1] is self.random_second_number


REFACTOR: make it better


  • I add an assertion for the divide function

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: D.EFGHIJKLMNOPQRST != UVWXY.ZABCDEFGHIJ
    
  • I change the calculation to division

    the test passes. two_numbers is a list with two items - self.random_first_number and self.random_second_number, this means

  • two_numbers[-2] is self.random_first_number

  • two_numbers[-1] is self.random_second_number

  • I add an assertion for multiplication

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: EFGHIJ.KLMNOPQRSTU != VWXYZ.ABCDEFGHIJKL
    
  • I change the expectation

    the test passes. two_numbers is a list with two items - self.random_first_number and self.random_second_number, this means

  • two_numbers[1] is self.random_second_number

  • two_numbers[-1] is self.random_second_number

  • I add an assertion for the subtract function

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: 0.0 != FGH.IJKLMNOPQRSTU
    
  • I change the expectation to match

    the test passes. two_numbers is a list with two items - self.random_first_number and self.random_second_number, this means

  • two_numbers[-2] is self.random_first_number

  • two_numbers[0] is self.random_first_number


test calculator with * expression

RED: make it fail


I can use a `starred expression`_ to unpack the list in an assertion like the positional arguments in test_unknown_number_of_arguments

139      self.assertEqual(
140          src.calculator.subtract(
141              two_numbers[-2],
142              two_numbers[0]
143          ),
144          self.random_first_number-self.random_first_number
145      )
146      self.assertEqual(
147          src.calculator.add(*two_numbers),
148          self.random_first_number-self.random_second_number
149      )

the terminal is my friend, and shows AssertionError

terminal
AssertionError: GHI.JKLMNOPQRSTUVW != XYZ.ABCDEFGHIJKLMN

GREEN: make it pass


I change the expectation to match the result of adding the two numbers from the list

146        self.assertEqual(
147            src.calculator.add(*two_numbers),
148            self.random_first_number+self.random_second_number
149        )

the test passes. The starred expressions gives the items of the list in the same order every time, this means these statements are the same

src.calculator.add(*two_numbers)
src.calculator.add(self.random_first_number, self.random_second_number)

because two_numbers is a list with two items - self.random_first_number and self.random_second_number


REFACTOR: make it better



test_calculator_:ref:`raises<how to raise an Exception>`type_error_when_given_more_than_two_inputs

It is important to remember that the starred expressions always gives the items from the list in order, and I cannot use a list that has more than 2 numbers with these calculator functions since they only take 2 inputs


RED: make it fail


I add a new test to show the problem when I have more than 2 inputs and use a starred expressions

158        self.assertEqual(
159            src.calculator.subtract(*two_numbers),
160            self.random_first_number-self.random_second_number
161        )
162
163    def test_calculator_:ref:`raises<how to raise an Exception>`type_error_when_given_more_than_two_inputs(self):
164        not_two_numbers = [0, 1, 2]
165
166        src.calculator.add(*not_two_numbers)
167
168
169# Exceptions seen

the terminal is my friend, and shows TypeError

terminal
TypeError: numbers_only.<locals>.wrapper() takes 2 positional arguments but 3 were given

GREEN: make it pass


I add the `assertRaises method`_ to handle the Exception

163    def test_calculator_:ref:`raises<how to raise an Exception>`type_error_when_given_more_than_two_inputs(self):
164        not_two_numbers = [0, 1, 2]
165
166        with self.assertRaises(TypeError):
167            src.calculator.add(*not_two_numbers)

the test passes.


REFACTOR: make it better


  • I add a failing line for division with the new list

    the terminal is my friend, and shows TypeError

    
    
    caption:

    terminal

    TypeError: numbers_only.<locals>.wrapper() takes 2 positional arguments but 3 were given

  • I add assertRaises

    the test passes.

  • I add a line for multiplication

    the terminal is my friend, and shows TypeError

    
    
    caption:

    terminal

    TypeError: numbers_only.<locals>.wrapper() takes 2 positional arguments but 3 were given

  • I add assertRaises

    the test passes.

  • I add the last line

    the terminal is my friend, and shows TypeError

    
    
    caption:

    terminal

    TypeError: numbers_only.<locals>.wrapper() takes 2 positional arguments but 3 were given

  • I handle the Exception

    the test passes.


close the project

  • I close test_calculator.py and calculator.py

  • I 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 calculator

    terminal
    cd ..
    

    the terminal shows

    .../pumping_python
    

    I am back in the pumping_python directory.


review

I added these tests to the calculator program after testing lists


code from the chapter

Do you want to see all the CODE I typed in this chapter?


what is next?

would you like to test list comprehensions? They are a quick way to make lists


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.