1 of 12

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

2 of 12

Quiz 2 review

Dropping 1 quiz, but not included until midterm grading after Quiz3.

3 of 12

Rules for Unit testing

  • Must Import the unit testing module and the functions from the file you want to test
  • Each test is preceded by test_. This is referred to as an annotation. In this case, the test_ annotation tells Python Unit Testing module to treat the labeled function as a test function.
  • Each test function establishes an expected value and runs the corresponding function to get the actual value.
  • Finally, test functions use self.assertEqual (or other assert functions provided by the unit testing module) to verify correctness.
  • Normally, self.assertEqual takes two arguments: the first is the expected result, the second is the actual result.

4 of 12

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

5 of 12

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

6 of 12

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()

7 of 12

Unit Testing in Thonny

Running Unit Test in Thonny

  • Create a new Python file in Thonny using the example code from basic_math.py above. Save the file.
  • Create a test file from the test code above called test_basic_math.py in the same directory.
  • Press the green play button in Thonny to run test_basic_math.py.
  • You should see something like this: ��----------------------------------------------------------------------�Ran 2 tests in 0.000s��OK
  • Now go back and "break" the code by changing the basic_math.add function: return sum + 1
  • Compile the new code, and then press the play button. What happens when an assertion fails?

8 of 12

Writing Basic Test Functions

  • Implement the following functions in your basic_math file:
    • multiply(x, y)
    • divide(x, y)
  • Now write the corresponding test functions in test_basic_math. Use the same pattern as in test_add andtest_subtract: establish an expected result and an actual result, then compare the two with an assertion.
  • Run your new tests to validate the new functions. Then introduce errors into the new functions, just as you did before with the add function, and run the tests again to see if they are really working.

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.

  • Add the following test cases to the test_add function. (Copy and paste the last three lines of test_add for each case below. For readability, separate each one with a blank line.)
    • case 1: x = 0.0, y = 0.0
    • case 2: x = -5.0, y = 3.5
  • Add two additional test cases to each of the other three test functions. Determine your own expected values for these functions.

9 of 12

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()

10 of 12

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()

11 of 12

PI Question

12 of 12

  • Acknowledgements

This lab was originally written for Java by Nathan Sprague.

</end>