# 11-1 # city_functions.py def get_formatted_city_name(city, country): """生成规范格式的城市名""" return city.title() + ', ' + country.title() # main.py import unittest from city_functions import get_formatted_city_name class CityNamesTestCase(unittest.TestCase): """测试city_functions.py""" def test_city_country(self): formatted_city_name = get_formatted_city_name('santiago', 'chile') self.assertEqual(formatted_city_name, 'Santiago, Chile') unittest.main() # 11-2 # city_functions.py def get_formatted_city_name(city, country, population=None): """生成规范格式的城市名""" name = city.title() + ', ' + country.title() if population: name += ' - population ' + str(population) return name # main.py import unittest from city_functions import get_formatted_city_name class CityNamesTestCase(unittest.TestCase): """测试city_functions.py""" def test_city_country(self): formatted_city_name = get_formatted_city_name('santiago', 'chile') self.assertEqual(formatted_city_name, 'Santiago, Chile') def test_city_country_population(self): formatted_city_name = get_formatted_city_name( 'santiago', 'chile', population=5000000) self.assertEqual(formatted_city_name, 'Santiago, Chile - population 5000000') unittest.main() # 11-3 # employee.py class Employee(): """表示职员的类""" def __init__(self, first_name, last_name, salary): """初始化一个职员,接受名、姓和年薪""" self.first_name = first_name self.last_name = last_name self.salary = salary def give_raise(self, add_salary=5000): self.salary += add_salary # main.py import unittest from employee import Employee class TestEmployee(unittest.TestCase): """测试employee.py""" def setUp(self): self.my_employee = Employee("Albert", "Ye", 1000000) def test_give_default_raise(self): prev = self.my_employee.salary self.my_employee.give_raise() now = self.my_employee.salary self.assertEqual(now, prev + 5000) def test_give_custom_raise(self): prev = self.my_employee.salary self.my_employee.give_raise(1000000) now = self.my_employee.salary self.assertEqual(now, prev + 1000000) unittest.main()