CS 149
Professor: Alvin Chao
Unit Testing
The first computer bug (see Grace Hopper)
Tue - Chp 6 reading
Wed HW 6
Thu Practice Quiz 3 in class
Fri Lab Eight Ball
Quiz 2 review
Dropping 1 quiz, but not included until midterm grading after Quiz3.
Rules for Unit testing
Getting started with Unit Testing
#Start with some functions in a basic_math.py file
def add(x, y):
"""Add - sum of x and y.
Args:
x(float): first number
y(float): second number
Returns:
float: sum of x and y
"""
sum = x + y
return sum
Simple Subtraction
def subtract(x, y):
"""Difference between x and y.
Args:
x(float): first number
y(float): second number
Returns:
float: difference between x and y
"""
diff = x - y
return diff
Python built-in Unit tests
import unittest
import basic_math�
class TestBasicMath(unittest.TestCase):
def test_add(self):
expected = 15.5
actual = basic_math.add(7.2, 8.3)
self.assertEqual(expected, actual)
def test_subtract(self):
expected = 2.2
actual = basic_math.subtract(3.5, 1.3)
self.assertEqual(expected, actual)
if __name__ == '__main__':
unittest.main()
Unit Testing in Thonny
Running Unit Test in Thonny
Writing Basic Test Functions
It's generally not enough to test a function just once. To be sure that the function is correct, we need to test multiple times with multiple values.
While loop Exercises
def example():
count = 0
while (True):
print("This is the song that never ends", count)
count += 1
if (count > 100):
break
def main():
example()
main()
Guessing while example with random
import random
def check_value(target, actual):
if target == actual:
return("Correct")
elif (actual < target):
return("Too Low")
else:
return("Too High")
# function definition
def main():
# pick a random number
target = random.randint(1,10)
# get the user's guess
num = int(input("Enter a number from 1 to 10 (inclusive)"))
# get the result
result = check_value(target, num)
# loop while the guess is not correct
while result != "Correct":
# Tell the result and get a new number
num = int(input(result + ". Enter a number from 1 to 10"))
# get the result
result = check_value(target, num)
# Tell the user the number
print("You guessed it! It was", target)
# function call
main()
PI Question
This lab was originally written for Java by Nathan Sprague.
</end>