How do you test that your program worked? You may put in print statements about what you expect the output to be and compare that to what you actually get to see if your code is correct.
This type of test is better than just printing out actual output because then you have to think about what the correct value should be. It lets you quickly compare the expected value and the actual value. However, you have to visually compare the two, which takes some time and you could miss something that doesnβt match.
The tests above are using a f-string which is an easier way to create a string with expression results in the string. Just add f before the start of the string and {expression} in the string.
Another way to write the code above would be to use a list comprehension. These are a quick way to return a new list by applying some logic to each element of the list.
What types of tests should you create? You should create tests that check that the function works for a variety of normal input. You should also think about how to handle unusual input such as checking that total_even works even for an empty list or a list with only one item.
Another way to test your code is to write unit tests. You have already been using hidden unit tests in this ebook to check your code as shown below. You probably quickly realized that you wanted all the tests to βpassβ which is highlighted in green. This gives you an even quicker visual indication that your code is working than having to compare the expected output to the actual.
Run the code below to see the unit tests again. See the unit tests after the code. The last unit test compares the result of recPerimeter(3.0, 2) to wrong value. Fix the value so that all of the tests pass.
Fix the function below to return the middle characters from the passed string. If the string has an odd length then return the middle character. If the string has an even length return the two middle characters. For example, get_middle('abc') returns 'b' and get_middle('abcd') returns 'bc'. Also add tests cases to test the result when str has only one or two characters in it.
Unit tests in this ebook must include the line from unittest.gui import TestCaseGui and inherit from TestCaseGui. Outside of this ebook you should include the line import unittest and inherit from unittest.TestCase.
Unit tests inherit from a class that includes several methods. As you can see from the code above one of the methods is assertEqual which returns the result of a == b.
Put the code in order to create tests for a Person class initials method that returns the first letter from the first name followed by the first letter of the last name. The Person class initializer takes the personβs first name and last name. First define a setUp method to create two Person objects and then define the test_initials method.