Assignment 13 - ldkvd/CS101L GitHub Wiki
Welcome to the CS101L Wiki!
Unit Testing
Automated testing is an important skill for developers. You can easily run a multitude of tests to make sure your functions and classes work as intended. As you add functionality it will give you the peace of mind to know you haven’t broken anything.
Create a new python program, called Grades.py2. Create a function called total that takes a parameter called values that is a list of numbers and returns a float value, which is the total of all the numbers in the list that is passed. Create another python program that we’ll use to test our function with different values. Put it in the same directory and name it Assignment15_Grades.py. Import unittest and Grades as the top, and add the rest of the following code.
Answers:
The image above is Grades.py code 1/2.
The image above is Grades.py code 2.2.
The image above is unittest code 1/3.
The image above is unittest code 2/3.
The image above is unittest code 3/3.
The image above is output 1/1.
In the program called Grades, the module math is imported. Then, a function that takes a parameter that is a list is defined. This function returns the sum of all the values in the list that is passed. Another function that takes a parameter that is a list is defined. This function returns the average of all the values in the list that is passed. Thirdly, a function that takes a parameter that is a list is defined. This function returns the median value of a list.
In the testing program, the modules unittest, Grades, and math are imported. A class called Grade-Test is created to test all the test methods in the program Grade. A method called test_total_returns_total_of_list is created. This method will test that total returns 33 when the list of 2, 5, 9 is passed. A method called test_total_returns_0 is created. This method will test that total returns 0 when an empty list is passed. A method called test_average_one is created. This method will test that average returns 5.33333 when the list of 2, 5, 9 is passed. A method called test_average_two is created. This method will test that average returns something 4 decimals close 12.0000 when the list. A method called test_average_returns_nan is created. This method will test that average returns math.nan when an empty list is passed. A method called test_median_when_odd is created. This will test that median returns the median value of the list when the length of the list passed is odd. Similarly, a method called test_median_when_even is created. This time, it will test that median returns the median value of the list when the length of the list passed is even. Last, a method called test_median when_empy is created that will test that median raises a ValueError when the list passed is empty. Then call unittest in the main.