习题11-1&11-2
name_function.py
#!/usr/bin/env python
#-*-coding:utf8-*-
def format_name (first,last,middle=''):
""" 格式化一个姓名"""
if middle:
fullname = first +' '+middle+' '+last
else:
fullname = first +' '+last
return fullname.title()
def format_city (city,country,population=''):
""" 格式化一个国家和城市 """
if population:
city_country = city +','+country+' - population'+' '+population
else:
city_country = city +','+country
return city_country.title()
test_name_function.py
#!/usr/bin/env python
#-*-condig:utf8-*-
import unittest
from name_function import format_name
from name_function import format_city
class NameTestCase(unittest.TestCase):
""" 测试name_function.py """
def test_first_last_name (self):
""" 能够正确的处理像james hardon这样的姓名吗? """
formattedname = format_name('james','hardon')
self.assertEqual(formattedname,'James Hardon')
def test_first_middle_last_name (self):
""" 能够正确的处理像james hardon ding这样的姓名吗?"""
formattedname = format_name('james','hardon','ding')
self.assertEqual(formattedname,'James Ding Hardon')
def test_city_country(self):
"""能够正确的处理像santiago,chile"""
formattedcity = format_city('santiago','chile')
self.assertEqual(formattedcity,'Santiago,Chile')
def test_city_country_population (self):
""" 能够处理带人口的城市吗? """
formattedcity = format_city('santiago','chile',population='500000')
self.assertEqual(formattedcity,'Santiago,Chile - Population 500000')
unittest.main()
习题11-3
Employee.py
#!/usr/bin/env python
#-*-coding:utf8-*-
class Employee:
""" 收集雇员信息 """
def __init__ (self,first,last,salary):
""" 雇员信息 """
self.first = first
self.last = last
self.salary = salary
def give_raise (self,addsalary=5000):
""" Function doc """
self.salary+=addsalary
test_Employee.py
#!/usr/bin/env python
#-*-coding:utf8-*-
import unittest
from Employee import Employee
class EmployeeTestCase(unittest.TestCase):
""" 测试不同的雇员信息 """
def setUp (self):
""" 初始化雇员信息 """
self.formatted_default = Employee('ding','yuanxue',1000)
def test_give_default_raise (self):
""" 默认加薪 """
self.formatted_default.give_raise()
self.assertEqual(self.formatted_default.salary,6000)
def test_give_coustom_raise (self):
"""特殊加薪"""
self.formatted_default.give_raise(8000)
self.assertEqual(self.formatted_default.salary,9000)
unittest.main()