Chapter 11
11-1 城市和国家
def city_country (city, country) :
info = city.title()+", " +country.title()
return info
import unittest
from city_functions import city_country
class CityCountryTestCase (unittest.TestCase) :
def test_city_country (self) :
formatted_city = city_country("santiago" , "chile" )
self.assertEqual(formatted_city, "Santiago, Chile" )
unittest.main()
11-2 人口数量
def city_country (city, country, population=0 ) :
info = city.title()+", " +country.title()
if population != 0 :
info += " - population " + str(population)
return info
import unittest
from city_functions import city_country
class CityCountryTestCase (unittest.TestCase) :
def test_city_country (self) :
formatted_city = city_country("santiago" , "chile" )
self.assertEqual(formatted_city, "Santiago, Chile" )
def test_city_country_population (self) :
formatted_city = city_country("santiago" , "chile" , 5000000 )
self.assertEqual(formatted_city, "Santiago, Chile - population 5000000" )
unittest.main()
11-3 雇员
import unittest
class Employee :
def __init__ (self, first, last, income) :
self.first = first
self.last = last
self.income = income
def give_raise (self, amount=5000 ) :
self.income += amount
class EmployTestCase (unittest.TestCase) :
def setUp (self) :
self.employee = Employee("James" , 'Brown' , 8000 )
def test_give_default_raise (self) :
income = self.employee.income
self.employee.give_raise()
self.assertEqual(self.employee.income, income + 5000 )
def test_give_custom_raise (self) :
income = self.employee.income
self.employee.give_raise(3000 )
self.assertEqual(self.employee.income, income + 3000 )
unittest.main()