Python作業(11.1-11.3)
Python第11章作業
11-1 城市和國家 : 編寫一個函式, 它接受兩個形參: 一個城市名和一個國家名。 這個函式返回一個格式為City, Country 的字串, 如Santiago, Chile 。 將這個函式儲存在一個名為city_functions.py的模組中。建立一個名為test_cities.py的程式, 對剛編寫的函式進行測試(別忘了, 你需要匯入模組unittest 以及要測試的函式) 。 編寫一個名為test_city_country() 的方法, 核實使用類似於'santiago' 和'chile' 這樣的值來呼叫前述函式時, 得到的字串是正確的。 執行test_cities.py
def city_and_country(city,country):
full_show=city+","+country
return full_show
import unittest from city_functions import city_and_country class CityTestCase(unittest.TestCase): def test_city_and_country(self): full_show=city_and_country('santiago', 'chile') self.assertEqual(full_show,'santiago,chile') unittest.main()
11-2 人口數量 : 修改前面的函式, 使其包含第三個必不可少的形參population , 並返回一個格式為City, Country - population xxx 的字串,如Santiago, Chile - population 5000000 。 執行test_cities.py, 確認測試test_city_country() 未通過。修改上述函式, 將形參population 設定為可選的。 再次執行test_cities.py, 確認測試test_city_country() 又通過了。
再編寫一個名為test_city_country_population() 的測試, 核實可以使用類似於
修改後:
def city_and_country(city,country,population):
full_show=city+","+country+"-population"+population
return full_show
測試原來的:
再次修改:
def city_and_country(city,country,population=''):
if population:
full_show=city+","+country+"-population"+population
else:
full_show=city+","+country
return full_show
再次修改:
import unittest
from city_functions import city_and_country
class CityTestCase(unittest.TestCase):
def test_city_and_country(self):
full_show=city_and_country('santiago', 'chile')
self.assertEqual(full_show,'santiago,chile')
def test_city_and_country_and_population(self):
full_show=city_and_country('santigao','chile','5000000')
self.assertEqual(full_show,'santigao,chile-population 5000000')
unittest.main()
11-3 僱員 : 編寫一個名為Employee 的類, 其方法__init__() 接受名、 姓和年薪, 並將它們都儲存在屬性中。 編寫一個名為give_raise() 的方法, 它預設將年薪增加5000美元, 但也能夠接受其他的年薪增加量。為Employee 編寫一個測試用例, 其中包含兩個測試方法: test_give_default_raise() 和test_give_custom_raise() 。 使用方法setUp() , 以免在每個測試方法中都建立新的僱員例項。 執行這個測試用例, 確認兩個測試都通過了。
Employee類:
class Employee():
def __init__(self,given_name,first_name,annual_salary):
self.given_name=given_name
self.first_name=first_name
self.annual_salary=annual_salary
def give_raise(self,add='5000'):
x=int(self.annual_salary)
x+=int(add)
self.annual_salary=str(x)
測試類:
import unittest
from Emp import Employee
class TestEmployee(unittest.TestCase):
def setUp(self):
self.test1=Employee('Ming','Li','0')
self.money='5000'
def test_give_default_raise(self):
self.assertIn('0' , self.test1.annual_salary)
def _give_custom_raise(self):
self.test1.give_raise('4000')
self.assertIn('9000',self.test1.annual_salary)
unittest.main()