第十一章課後習題

11-1 城市和國家:編寫一個函數,它接受兩個形參:一個城市名和一個國家名。這個函數返回一個格式爲 City, Country 的字符串,如 Santiago, Chile。將這個函數存儲在一個名爲 city _functions.py 的模塊中。創建一個名爲 test_cities.py 的程序,對剛編寫的函數進行測試(別忘了,你需要導入模塊 unittest 以及要測試的函數)。編寫一個名爲 test_city_country()的方法,覈實使用類似於'santiago''chile'這樣的值來調用前述函數時,得到的字符串是正確的。運行 test_cities.py,確認測試 test_city_country()通過了。

city_functions.py

def cityName(city,country,population):
	format_name=city.title()+','+country.title()
	return format_name

test_cities.py

from city_functions import *
import unittest

class cityTest(unittest.TestCase):
	"""docstring for cityTest"""
	def test_city_country(self):
		format_name=cityName('guangzhou','china')
		self.assertEqual(format_name,'Guangzhou,China')

unittest.main()

運行結果:


11-2 人口數量:修改前面的函數,使其包含第三個必不可少的形參 population,並
返回一個格式爲
City, Country – population xxx 的字符串,如 Santiago, Chile –
population 5000000
。運行 test_cities.py,確認測試 test_city_country()未通過。

city_functions.py

def cityName(city,country,population):
	format_name=city.title()+','+country.title()+'-'+"population "+str(population)
	return format_name

運行結果:


修改上述函數,將形參 population 設置爲可選的。再次運行 test_cities.py,確認測

test_city_country()又通過了。

city_functions.py

def cityName(city,country,population=''):
	format_name=city.title()+','+country.title()
	if population:
		format_name+=("population "+str(population))
	return format_name

運行結果:


再編寫一個名爲 test_city_country_population()的測試,覈實可以使用類似於
'santiago''chile''population=5000000'這樣的值來調用這個函數。再次運行
test_cities.py,確認測試 test_city_country_population()通過了。

from city_functions import *
import unittest

class cityTest(unittest.TestCase):
	"""docstring for cityTest"""
	def test_city_country(self):
		format_name=cityName('guangzhou','china')
		self.assertEqual(format_name,'Guangzhou,China')
	def test_city_country_population(self):
		format_name=cityName('guangzhou','china',500000)
		self.assertEqual(format_name,'Guangzhou,China-population 500000')
unittest.main()

運行結果:


11-3 僱員:編寫一個名爲 Employee 的類,其方法__init__()接受名、姓和年薪,並
將它們都存儲在屬性中。編寫一個名爲
give_raise()的方法,它默認將年薪增加 5000
美元,但也能夠接受其他的年薪增加量。
Employee 編寫一個測試用例,其中包含兩個測試方法: test_give_default_
raise()
test_give_custom_raise()。使用方法 setUp(),以免在每個測試方法中都創

建新的僱員實例。運行這個測試用例,確認兩個測試都通過了。

import unittest
class Employee(object):
	"""docstring for Employee"""
	def __init__(self, first, last, ymon):
		self.first=first
		self.last=last
		self.ymon=ymon
	def give_raise(self,increase=5000):
		self.ymon+=increase

class testEmployee(unittest.TestCase):
	"""docstring for testEmployee"""
	def setUp(self):
		self.employee=Employee('ke','sibo',1000)
	def test_give_default_raise(self):
		self.employee.give_raise()
		self.assertEqual(self.employee.ymon,6000)
	def test_give_custom_raise(self):
		self.employee.give_raise(2000)
		self.assertEqual(self.employee.ymon,3000)

unittest.main()

運行結果:



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章