Testing is used to determine that the code can work according to the requirements when facing various inputs. Testing in advance is helpful to prevent new code from damaging the existing behavior of the program. This chapter uses the tools in unittest to write test cases and verify the output of the input
formatted format Generate generates neatly neat full complete
1 from name_function import get_formatted_name # from name_ function. Import get from PY_ formatted_ name()
11-1 city and country: write a function that accepts two formal parameters: a city name and a country name. This function returns a string in the format of city and country, such as santiago and chile. Store this function in a file named city_ functions. Py. Create a test_cities.py program to test the function just written (don't forget, you need to import the module unittest and the function to be tested). Write a program called test_city_country() method to verify that the string obtained when calling the above function with values like 'santiago' and 'chile' is correct. Run test_cities.py, confirmation test_city_country() passed.
1 #city_functions.py 2 def city_country(city_name, country_name, middle=','): # 3 """Output city name and country name,for example Santiago, chile""" 4 full_city_country = city_name + middle + country_name 5 return full_city_country.title() 6 7 #city_name_country_name.py 8 from city_functions import city_country 9 print("Enter 'q' at any time to quit.") 10 while True: 11 city_name = input("Enter the city name in person: ") 12 if city_name == 'q': 13 break 14 country_name = input("Enter the country name in person: ") 15 if country_name == 'q': 16 break 17 18 formatted_name = city_country(city_name, country_name) 19 print("\n Output of city and country names: " + formatted_name) 20 21 22 #test_cityname_and_country_name.py 23 import unittest #Import inttest Tools in modules 24 from city_functions import city_country 25 26 class NamesTestCase(unittest.TestCase): #This naming can be arbitrary, but it is usually related to the tested function and should include Test word 27 """test city_functions.py""" #inherit TestCase Class like this Python To know how to run the test you write, you can think of an interface to your function 28 #Run in another place 29 def test_city_country_name(self): #The method of this test file is to use test_Start with,_test Methods that begin with will run automatically when the file runs 30 """Be able to handle images correctly Santigo, Chile What kind of names do you have?""" 31 formatted_name = city_country('Santigo', 'Chile') #The function to be tested is called and the return value is stored in the formatted_name in 32 self.assertEqual(formatted_name, 'Santigo,Chile')#assert method assertEqual Used to verify whether the results obtained are consistent with the expected results 33 34 '''Here, we know get_formatted_name()The city country name should be returned, i.e 35 The first letter is capitalized and there is a between them'，'，So we expect formatted_name The value of is Santigo，Chile. To check if this is true, we call unittest Method of assertEqual()，And pass it formatted_ 36 name and'Santigo Chile'. Code line self.assertEqual(formatted_name, 'Janis Joplin')It means "will" formatted_name The value of is the same as the string'Santigo,Chile'Compare, if they are equal, all is well, if it 37 We are not equal, tell me!''' 38 unittest.main()
11-2 population: modify the previous function to include the third essential formal parameter population, and return a string in the format of City, Country – population xxx, such as Santiago, Chile – population 5000000. Run test_cities.py, confirmation test_city_country() failed. Modify the above function and set the formal parameter population to optional. Run test again_ cities. Py, confirmation test_city_country() passed again. Write another one called test_ city_ country_ The test of population () verifies that this function can be called with values like 'santiago', 'chile' and 'population=5000000'. Run test again_ cities. Py, confirmation test_city_country_population() passed.
1 #Only when I write about it can I see that there are two tests.. One is optional and one is not optional 2 #Not optional 3 def city_country_population(city_name, country_name, population='population-50000'): 4 """Output city name and country name,for example Santiago, chile""" 5 full_city_country = (city_name + ', ' + 6 country_name + str(population)) 7 return full_city_country.title() 8 #city_country_population_name.py 9 from city_country_population import city_country_population 10 population = 'population-500000' 11 print("Enter 'q' at any time to quit.") 12 while True: 13 city_name = input("Enter the city name in person: ") 14 if city_name == 'q': 15 break 16 country_name = input("Enter the country name in person: ") 17 if country_name == 'q': 18 break 19 #population = input("Please enter the population: ") 20 #if population == 'q': 21 #break 22 23 formatted_name = city_country_population(city_name, country_name, population) 24 print("\n Output results of city and country names and population: " + formatted_name) 25 #Optional 26 #city_country_population.py 27 def city_country_population(city_name, country_name, population): 28 """Output city name and country name,for example Santiago, chile""" 29 full_city_country = (city_name + ', ' + 30 country_name + ' -population ' + population) 31 return full_city_country.title() 32 33 #city_country_population_name.py 34 from city_country_population import city_country_population 35 print("Enter 'q' at any time to quit.") 36 while True: 37 city_name = input("Enter the city name in person: ") 38 if city_name == 'q': 39 break 40 country_name = input("Enter the country name in person: ") 41 if country_name == 'q': 42 break 43 population = input("Please enter the population: ") 44 if population == 'q': 45 break 46 47 formatted_name = city_country_population(city_name, country_name, population) 48 print("\n Output results of city and country names and population: " + formatted_name) 49 50 #test_city_and_country_populations.py 51 import unittest 52 from city_country_population import city_country_population 53 54 class NamesTestCase(unittest.TestCase): 55 """test city_functions.py""" 56 57 def test_city_country_population_name(self): 58 """Be able to handle images correctly Santigo, Chile What kind of names do you have?""" 59 formatted_name = city_country_population('Asd', 'Asd', '456') 60 self.assertEqual(formatted_name, 'Asd, Asd -Population 456') 61 62 unittest.main() 63 #I didn't write the test that failed, because there are too many failed methods, and there is no clear definition of what to use
assertEqual(a, b) verify a == b assertNotEqual(a, b) verify a != b assertTrue(x) verify x by True assertFalse(x) verify x by False assertIn(item, list) verify item stay list in assertNotIn(item, list) verify item be not in list in
11-3 Employee: write a class named Employee and its methods__ init__ () accept first name, last name, and annual salary and store them all in properties. Write a program called give_raise(), which increases the annual salary by $5000 by default, but can also accept other annual salary increases. Write a test case for Employee, which contains two test methods: test_give_default_raise() and test_give_custom_raise(). Use the method setUp() to avoid creating a new Employee instance in each test method. Run the test case to confirm that both tests have passed.
1 #Employee.py 2 class Employee: 3 """Collect information about migrant workers""" 4 def __init__(self, firstname, lastname, money): 5 """Employee initialization""" 6 self.firstname = firstname 7 self.lastname = lastname 8 self.money = money 9 def give_raise(self, addmoney=5000): 10 """What should be added(Is it possible)""" 11 self.money += addmoney 12 13 #test case 14 import inttest 15 from Employee import Employee #file Employee Internal Employee class 16 class EmployeeTestCase(unittest.TestCase): #If you are TestCase Class contains methods setUp()，Python Will run first 17 # It, and then run each to test_Starting method 18 """Test the information of different employees""" 19 def setUp(self): 20 """Initialize employee information""" #method setUp()，Let's just create these objects once 21 # Times and use them in each test method. 22 self.default = Employee('xiao', 'ma', 1000) #Variable names contain prefixes self(That is, stored in properties) 23 """Default salary increase""" 24 self.default.give_raise() 25 self.assertEqual(self.default.money,6000) 26 def test_igive_coustom_raise(self): 27 """Special salary increase""" 28 self.default.give_raise(8000) 29 self.assertEqual(self.default.money,9000) 30 unittest.main()
Summary: test code
When participating in a heavy workload project, you should test the important behavior of the functions and classes you write. In the early stage of the project, don't try to write full coverage test cases unless there is a good reason to do so.
Use the tools in the module unittest to write tests for functions and classes; How to write inheritance unittest Testcase classes and how to write test methods to verify that the behavior of functions and classes meets expectations; How to use the method setUp() to efficiently create instances and set their properties based on the class so that they can be used in all test methods of the class.