how to make a calculator 1
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 self.assertEqual(
44 src.calculator.divide(
45 self.random_first_number,
46 self.random_second_number
47 ),
48 self.random_first_number/self.random_second_number
49 )
50
51
52# Exceptions seen
53# AssertionError
54# NameError
55# AttributeError
56# TypeError
start the project
I name this project
calculatorI open a terminal
I use uv to make a directory for the project and initialize it
the terminal shows
then goes back to the command line.
I use mkdir to make a folder named
srcmkdir srcthe terminal goes back to the command line.
I use the mv program to change the name of
main.pytocalculator.pyand move it to thesrcfolderthe terminal goes back to the command line.
I make a directory for the tests
the terminal goes back to the command line.
I make the
testsdirectory a Python packageDanger
use 2 underscores (__) before and after
initfor__init__.pynot_init_.pythe terminal goes back to the command line.
I make a Python file for the tests in the
testsdirectorytouch tests/test_calculator.pyNew-Item tests/test_calculator.pythe terminal goes back to the command line.
I open
test_calculator.pyI add the first failing test to
test_calculator.py1import unittest 2 3 4class TestCalculator(unittest.TestCase): 5 6 def test_failure(self): 7 self.assertFalse(True)
I add pytest-watcher to the requirements file
the terminal goes back to the command line.
I add pytest-watcher to the requirements file
I use uv to install pytest-watcher with the requirements file
the terminal shows that it installed pytest-watcher and its dependencies.
I use pytest-watcher to run the tests automatically
the terminal is my friend, and shows AssertionError
======================== FAILURES ======================== _____________________ TestCalculator.test_failure ________________________ self = <tests.test_calculator.TestCalculator testMethod=test_failure> def test_failure(self): > self.assertFalse(True) E AssertionError: True is not false tests/test_calculator.py:7: AssertionError ================ short test summary info ================= FAILED tests/test_calculator.py::TestCalculator::test_failure - AssertionError: True is not false =================== 1 failed in X.YZs ====================if the terminal does not show the same error, then check if
your
tests/__init__.pyhas two underscores (__) before and afterinitfor__init__.pynot_init_.pyyou ran
echo "pytest-watcher" >> requirements.txt, to addpytest-watcherto the requirements file
and try
uv run pytest-watcher . --now --patterns "**/*.py"againI hold ctrl (Windows/Linux) or option/command (MacOS) on the keyboard and use the mouse to click on
tests/test_calculator.py:7to put the cursor on line 7I add AssertionError to the list of Exceptions seen, in
test_calculator.pyI change True to False in the assertion
the test passes.
I add a TODO list to keep track of the work for the program
1import unittest 2 3 4class TestCalculator(unittest.TestCase): 5 6 def test_failure(self): 7 self.assertFalse(False) 8 9 10# TODO 11# test addition 12# test subtraction 13# test multiplication 14# test division 15 16 17# Exceptions seen 18# AssertionError
test_addition
RED: make it fail
I change test_failure to
test_additionthen change `assertFalse`_ to `assertEqual`_1import unittest 2 3 4class TestCalculator(unittest.TestCase): 5 6 def test_addition(self): 7 self.assertEqual(src.calculator.add(0, 1), 1)the assertEqual method from AssertionError checks if the two things in parentheses are the same. It is like the statement
assert x == yor askingis x equal to y?I think of
self.assertEqual(src.calculator.add(0, 1), 1)as
self.assertEqual(reality, my_expectation)where
realityissrc.calculator.add(0, 1)my_expectationis1because0 + 1is1
in other words,
self.assertEqual(src.calculator.add(0, 1), 1)checks if the result of callingsrc.calculator.addwith0and1as input is equal to1
the terminal is my friend, and shows NameError
because I do not have a definition for
srcintest_calculator.py
GREEN: make it pass
I add NameError to the list of Exceptions seen, in
test_calculator.pyI add an import statement at the top of the file for the
calculatormodule1import src.calculator 2import unittest 3 4 5class TestCalculator(unittest.TestCase):the terminal is my friend, and shows AttributeError
I think of
src.calculator.addas an address,addis something (an attribute) in the emptycalculator.pyfile from thesrcfolderI add AttributeError to the list of Exceptions seen, in
test_calculator.pyI open
calculator.pyfrom thesrcfolder, then add the name1addthe terminal is my friend, and shows NameError
I have to tell Python what the name
addmeansI point it to None to define it
1add = Nonethe terminal is my friend, and shows TypeError
because the
addvariable is now a name for None, and I cannot call None like a function.I add TypeError to the list of Exceptions seen, in
test_calculator.pyI use the def keyword in
calculator.pyto makeadda function so it is callable1def add(): 2 return Nonethe terminal is my friend, and shows TypeError
the definition of
adddoes not allow it take input, and 2 were given in the call -0and1I add names in the parentheses to make the function take 2 inputs
1def add(first_input, second_input): 2 return Nonethe terminal is my friend, and shows AssertionError
I make the return statement give the test what it wants
1def add(first_input, second_input): 2 return 1the test passes, time for a victory lap!
REFACTOR: make it better
The add function passes the test, and does not do what I want because it always returns 1. I want it to return the result of a calculation with the inputs
I add another assertion to show the problem with the function in
test_calculator.pythe terminal is my friend, and shows AssertionError
I change the return statement in
calculator.py1def add(first_input, second_input): 2 return 2the terminal is my friend, and shows AssertionError
this makes the assertion that was passing before -
src.calculator.add(0, 1)fail. If the test sends0and2tosrc.calculator.addit returns20and1tosrc.calculator.addit returns2
I need a solution that can make the two tests pass. The function should return
2if the test sends0and2tosrc.calculator.addbecause0 + 2 == 21if the test sends0and1tosrc.calculator.addbecause0 + 1 == 1
I make the function return the result of adding the two inputs
1def add(first_input, second_input): 2 return first_input + second_inputthe two tests are passing
I add another test to make sure the function works for other numbers in
test_calculator.pythe terminal is my friend, and shows AssertionError
I change the expectation in the test
the test passes.
I add another test with a different number for the first input
the terminal is my friend, and shows AssertionError
I change the expectation to match reality
the test passes. The
addfunction looks good so far.I add an assertion with bigger numbers
the terminal is my friend, and shows AssertionError
I change the expectation to match reality
the test passes.
I add another assertion with a negative number
the terminal is my friend, and shows AssertionError
I change the expectation to match reality
the test passes.
I try another assertion with two negative numbers
the terminal is my friend, and shows AssertionError
I make the expectation match reality
the test passes. The
addfunction can handle positive and negative whole numbersI add an assertion with floats (binary floating point decimal numbers)
the terminal is my friend, and shows AssertionError
I change the expectation
the test passes.
I add another assertion
the terminal is my friend, and shows AssertionError
whoa!
I change the expectation
the test passes. Why is the result “0.30000000000000004” and not “0.3”?
I add another assertion
the terminal is my friend, and shows AssertionError
whaaaaat?!
I change the expectation
the test passes. Why is the result “-5.555499999999999” not “-5.5555”?
I just did the same kind of calculation 10 times, there is a better way to do this thanks to Substitution. I can use variable a letter or a name for the numbers, so that I can have one test for all possible numbers, it is called a variable.
A variable is a name that is used for values that change. For example, in the tests so far, I have
src.calculator.add(0, 1) is 0 + 1 is 1 src.calculator.add(0, 2) is 0 + 2 is 2 src.calculator.add(0, 3) is 0 + 3 is 3 src.calculator.add(1, 3) is 1 + 3 is 4 src.calculator.add(123456, 789012) is 123456 +789012 is 912468 src.calculator.add(-2, -3) is -2 + -3 is -5 src.calculator.add(-1, 0) is -1 + 0 is -1 src.calculator.add(0.1, 1) is 0.1 + 1 is 1.1 src.calculator.add(0.1, 0.2) is 0.1 + 0.2 is 0.30000000000000004 src.calculator.add(0.1234, -5.6789) is 0.1234 + -5.6789 is -5.555499999999999all of these lines can be written using
xas the name of the first number andyas the name for the second number, like thissrc.calculator.add(x, y) is x + y is x + yI add names to the first assertion
the test is still green.
I do the same thing to the next assertion
still green.
I do the next one
green.
then the next one
still green.
then the next
the test is still green.
on to the next assertion
still green.
and the next
green.
more?
still green.
I add variables to the next assertion
the test is still green.
ah, the last one
still green.
how to use random numbers
All the assertions in test_addition do the same thing
point
first_numberto a valuepoint
second_numberto a valuecall
src.calculator.addwithfirst_numberandsecond_numberas inputcheck if the result of
src.calculator.add(first_number, second_number)is the same asfirst_number + second_number
I want to use random numbers for first_number and second_number to make sure that the add function always returns the result of adding the two numbers without knowing what the numbers are.
I can do this with the random module from The Python Standard Library, it is a module from The Python Standard Library that is used to make fake random numbers
I add an import statement for the random module at the top of
test_calculator.py1import random 2import src.calculator 3import unittestI use a random value for
first_numberin the first assertiongreen.
random.triangular returns a random float that could be any number from
-0.1to1.0in this case, I can also use random.randint if I want a random integerI want to see the test fail to be sure everything works as expected. I change the expectation in the first assertion
I use (ctrl/command+s (Windows & Linux/MacOS)) a few times to run the tests and the terminal is my friend, and shows AssertionError with random values that look like this
the letters are for random numbers
I change the expectation of the assertion back to the right calculation
the test is green again
I remove the commented line then use a random value for
second_numberthe test is still green.
I remove the commented line and the other assertions because they are covered by the one that uses random numbers. I do not need them anymore
still green.
I use the
Rename Symbolfeature to change the name of variables to say what they aregreen.
There is some repetition, If I want to use a different range of random numbers for the test, I have to make a change in more than one place. For example
still green.
I add a function to remove the repetition
1import random 2import src.calculator 3import unittest 4 5 6def a_random_number(): 7 return random.triangular(-10.0, 10.0) 8 9 10class TestCalculator(unittest.TestCase):I use the new function to get random values for the
random_first_numberandrandom_second_numbervariablesthe test is still green.
I remove the commented lines
I change the expectation in the assertion to make sure the test works
the terminal is my friend, and shows AssertionError
I undo the change
the test is green again
I now only need to change the range of random numbers for the test in one place
the test is still green.
I can use any range of numbers the computer can handle, for example
the terminal is my friend, and shows OverflowError
because the numbers are too big
**is the symbol for raise to the power (exponents)10.0**100000is how to write10.0raised to the power of100,000
I make the range smaller
the test is still green, though the test takes a little longer to run
I remove
test additionfrom the TODO list
test_subtraction
RED: make it fail
I add a test for subtraction in test_calculator.py
12 def test_addition(self):
13 random_first_number = a_random_number()
14 random_second_number = a_random_number()
15
16 self.assertEqual(
17 src.calculator.add(
18 random_first_number,
19 random_second_number
20 ),
21 random_first_number+random_second_number
22 )
23
24 def test_subtraction(self):
25 random_first_number = a_random_number()
26 random_second_number = a_random_number()
27
28 self.assertEqual(
29 src.calculator.subtract(
30 random_first_number,
31 random_second_number
32 ),
33 random_first_number-random_second_number
34 )
35
36
37# TODO
the terminal is my friend, and shows AttributeError
calculator.py in the src folder does not have anything named subtract in it
GREEN: make it pass
I add the name to
calculator.py1def add(first_input, second_input): 2 return first_input + second_input 3 4 5subtractI point
subtractto Nonethe terminal is my friend, and shows TypeError
I have seen this before
I make
subtracttake inputsthe terminal is my friend, and shows AssertionError
subtractreturns None, the assertion expectsrandom_first_number-random_second_numberwhich isfirst_input-second_inputthe difference between the two numbers
I make the
subtractfunction return the difference between the inputsthe test passes. SUCCESS!
I remove
test subtractionfrom the TODO list intest_calculator.py
test_multiplication
RED: make it fail
I add a failing test for multiplication in test_calculator.py
24 def test_subtraction(self):
25 random_first_number = a_random_number()
26 random_second_number = a_random_number()
27
28 self.assertEqual(
29 src.calculator.subtract(
30 random_first_number,
31 random_second_number
32 ),
33 random_first_number-random_second_number
34 )
35
36 def test_multiplication(self):
37 random_first_number = a_random_number()
38 random_second_number = a_random_number()
39
40 self.assertEqual(
41 src.calculator.multiply(
42 random_first_number,
43 random_second_number
44 ),
45 random_first_number*random_second_number
46 )
47
48
49 # TODO
the terminal is my friend, and shows AttributeError
GREEN: make it pass
Using what I know so far, I add a function to
calculator.pythe test passes.
I remove
test_multiplicationfrom the TODO list intest_calculator.py
Note
*is the symbol for multiplication**is the symbol for raise to the power (exponent)
test_division
RED: make it fail
Time for division. I add a new test to test_calculator.py
36 def test_multiplication(self):
37 random_first_number = a_random_number()
38 random_second_number = a_random_number()
39
40 self.assertEqual(
41 src.calculator.multiply(
42 random_first_number,
43 random_second_number
44 ),
45 random_first_number*random_second_number
46 )
47
48 def test_division(self):
49 random_first_number = a_random_number()
50 random_second_number = a_random_number()
51
52 self.assertEqual(
53 src.calculator.divide(
54 random_first_number,
55 random_second_number
56 ),
57 random_first_number/random_second_number
58 )
59
60
61# TODO
62# test division
the terminal is my friend, and shows AttributeError
GREEN: make it pass
I add the function to
calculator.pythe test passes.
I remove the TODO list from
test_calculator.py
REFACTOR: make it better
I have some repetition to remove, the code below happens in every test, that is 4 times in
test_calculator.pyrandom_first_number = a_random_number() random_second_number = a_random_number()I add object attributes (variables) to remove the repetition and use the same numbers for all the tests
I use the new object attributes in test_addition
the test is still green.
I use the object attributes for the variables in the call to
src.calculator.addin the assertionstill green.
I use the object attributes for the variables in the expectation of the assertion
green.
I remove the commented lines and the
random_first_numberandrandom_second_numbervariables from test_additionstill green.
I use the new object attributes in test_subtraction
the test is still green.
I use the object attributes for the variables in the call to
src.calculator.subtractin the assertionstill green.
I use the object attributes for the variables in the expectation of the assertion
green.
I remove the commented lines and the
random_first_numberandrandom_second_numbervariables from test_subtractionstill green.
I use the new object attributes in test_multiplication
the test is still green.
I use the object attributes for the variables in the call to
src.calculator.multiplyin the assertionstill green.
I use the object attributes for the variables in the expectation of the assertion
green.
I remove the commented lines and the
random_first_numberandrandom_second_numbervariables from test_multiplicationstill green.
I use the new object attributes in test_division
the test is still green.
I use the object attributes for the variables in the call to
src.calculator.dividein the assertionstill green.
I use the object attributes for the variables in the expectation of the assertion
green.
I remove the commented lines and the
random_first_numberandrandom_second_numbervariables from test_divisionstill green.
All the tests are passing, though they all look the same, there has to be a better way.
The random_first_number and random_second_number variables are made once as object attributes and used later in each test with self.random_first_number and self.random_second_number, the same way I use unittest.TestCase assert methods like assertEqual method with self.assertEqual
test_calculator_tests
Since everything is green, I can write the program that makes the tests pass without looking at the tests
RED: make it fail
I close
test_calculator.pyI delete all the text in
calculator.py, the terminal is my friend, and shows 4 failures- caption:
terminal
FAILED … - AttributeError: module ‘src.calculator’ has no attribute ‘add’ FAILED … - AttributeError: module ‘src.calculator’ has no attribute ‘divide’ FAILED … - AttributeError: module ‘src.calculator’ has no attribute ‘multiply’ FAILED … - AttributeError: module ‘src.calculator’ has no attribute ‘subtract’ =========================== 4 failed in X.YZs ============================
I start with the last AttributeError
What other Exceptions do you think are raised as I go along?
GREEN: make it pass
I add the name to
calculator.py1subtractI point it to None to define it
1subtract = NoneI change
subtractto a function1def subtract(): 2 return NoneI add positional arguments to the function
1def subtract(first_input, second_input): 2 return Nonethe terminal is my friend, and shows AssertionError with random numbers
I change the return statement to see the difference between the inputs and expected output, remember the identity function?
1def subtract(first_input, second_input): 2 return first_input, second_inputthe terminal is my friend, and shows AssertionError with random numbers that look like this
the name of the function is
subtractand the assertion expects the difference between the two inputsI make the return statement match the expectation
1def subtract(first_input, second_input): 2 return first_input - second_inputthe terminal is my friend, and shows AttributeError
I add a function
1def subtract(first_input, second_input): 2 return first_input - second_input 3 4 5def multiply(): 6 return Nonethe terminal is my friend, and shows TypeError
I add 2 names for the positional arguments
the terminal is my friend, and shows AssertionError
I change the return statement to see the difference between the inputs and the expected output, this is the identity function again
the terminal is my friend, and shows AssertionError with random numbers that look like this
I change it to the multiplication of the inputs to match the name of the function
the terminal is my friend, and shows AttributeError
I add another function
the terminal is my friend, and shows AssertionError with random numbers that look like this
I change the return statement to give the test what it wants
the terminal is my friend, and shows AttributeError
the return statement of the last 3 functions matched their names, I do the same thing for the new one
1def subtract(first_input, second_input): 2 return first_input - second_input 3 4 5def multiply(first_input, second_input): 6 return first_input * second_input 7 8 9def divide(first_input, second_input): 10 return first_input / second_input 11 12 13def add(first_input, second_input): 14 return first_input + second_inputand all the tests are passing with no random failures, or are they?
close the project
I close
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 wrote these tests for a program that can add, subtract, multiply and divide
I also saw these Exceptions
code from the chapter
what is next?
Would you like to see a better way to write test_why_use_a_function?